0

I want to make an API that when you access it it will show result in text format of how many rows are on my database.

Database info:

Username: predator_db

DB Name: predator_db

Table Name: database

I tried a couple of codes and I could not get it to work.

Code tried:

<?php
$con = mysql_connect("localhost","predator_db","PASS");
if (!$con) {
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("predator_db", $con);

$result = mysql_query("select count(1) FROM database");
$row = mysql_fetch_array($result);

$total = $row[0];
echo "Total rows: " . $total;

mysql_close($con);
?>

Response Of Code: "Total Rows: " < Does not show how many rows. Error Log:

[05-Feb-2015 23:44:58 UTC] PHP Deprecated:  mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home/predator/public_html/api/resolver/number.php on line 2
[05-Feb-2015 23:44:58 UTC] PHP Warning:  mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/predator/public_html/api/resolver/number.php on line 10
halfer
  • 19,824
  • 17
  • 99
  • 186
Kevin Schwertz
  • 123
  • 2
  • 12

3 Answers3

1

You're trying to fetch the results from database... not from your actual database of predator_db.

I'll do it with the basics, but please look into MySQLi prepared statements and/or PDO.

$link = mysqli_connect("localhost", "predator_db", "PASS", "predator_db");
$result = mysqli_query($link, "select COUNT(id) AS count FROM `database`");
// make sure it worked
if(!$result) {
    die('Error: ' . mysqli_error($link));
} else {
    $num_rows = mysqli_fetch_assoc($result);
    // echo it
    echo "Rows: " . $num_rows['count'];
}
Darren
  • 13,050
  • 4
  • 41
  • 79
1

First off, it's not a good idea to name a table after a reserved keyword like database. However, if you are going to go that route, you will always have to place the name in backticks ``. So, your query should be

$result = mysql_query("select count(1) FROM `database`");

Also, look into MYSQLi, as the old MySQL driver is deprecated.

ChicagoRedSox
  • 638
  • 6
  • 18
0
<?php
$link = mysqli_connect("localhost", "DB_USER", "DB_PASS", "DB_NAME");
$result = mysqli_query($link, "select COUNT(*) AS count FROM DB_NAME.DB_TABLE");
if(!$result) {
    die('Error: ' . mysqli_error($link));
} else {
    $num_rows = mysqli_fetch_assoc($result);
    echo "Rows: " . $num_rows['count'];
}
?> 
Kevin Schwertz
  • 123
  • 2
  • 12