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
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'];
}
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.
<?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'];
}
?>
Related
I got this error in mysqli
mysqli_select_db() expects exactly 2 parameters, 1 given in
/home/u751513549/public_html/recent.php on line 6
This is the code
<?php // Connects to your Database
mysqli_connect("localhost", "u751513549_liker", "xxxxxxxx") or die(mysqli_error());
mysqli_select_db("u851654599_liker") or die(mysqli_error());
$data = mysqli_query("SELECT *
FROM token_all
ORDER BY RAND() LIMIT 0,9; ") or die(mysqli_error());
Print "<table";
while ($info = mysqli_fetch_array($data)) {
Print "<tr>";
Print " <a href=\"https://www.facebook.com/" . $info['id'] . "/\"/> <img src=\"https://graph.facebook.com/" . $info['id'] . "/picture\"/></a>";
}
Print "</table>";
Please help me to fix this error I am a beginner.
Try this (I have added another parameter to mysqli_select_db):
$con = mysqli_connect("localhost", "u751513549_liker", "xxxxxxxx") or die(mysqli_error($con));
mysqli_select_db($con, "u851654599_liker") or die(mysqli_error($con));
Step 1: Create Connection
$conn = mysqli_connect("localhost","u751513549_liker","xxxxxxxx","u851654599_liker");
Step 2: Run your Query
$query= mysqli_query($conn,"Your Query") or die(mysqli_error($conn));
Step 3 : Fetch records
$result = mysqli_fetch_all($query);
Step 4 : Display Records
var_dump($result);
Ive been trying to display a "bid" from the database to no success.
here is my error
Fatal error: Function name must be a string in /home/rslistc1/public_html/get-bids.php on line 7
here is my code
<?php
include('session.php');
?>
<?php
require_once('mysql_connect.php');
$query3 = "SELECT id, username, bid FROM bids WHERE username = '$login_session'";
$result3 = mysql_query($query3) OR die($mysql_error());
$num = mysql_num_rows($result3);
while ($row = mysql_fetch_array($result3, MYSQL_ASSOC)) { ?>
<?php echo''.$row['bid'].'';
}
?>
Any idea
Before we address the line 7 issue, lets check other errors. In order to request a query to a MYSQL database, we need to create a connection:
$con = mysqli_connect("ip_address","user","password","database_name");
Once we have that connection, let us check if we can actually connect to the database:
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
Appreciate that mysqli_error() function uses the connection. Now the query string:
$query3 = "SELECT id, username, bid FROM bids WHERE username = '$login_session'";
You are sending a query to look for a username called "$login_session" and it would most likely not find any match. To add strings from variables will be as follow:
$query3 = "SELECT id, username, bid FROM bids WHERE username = '" . $login_session . "'";
Now, for the error in line 7
result3 = mysql_query($con, $query3) OR die($mysql_error($con));
As you can see, both mysql function use the connection to check for errors. Try it and let me know if everything works fine.
Edit:
Terribly sorry my friend, I just forgot to put a little letter "i" on the line, also, I would like to show you my way to deal with the query result. First, the line as it should be:
$result3 = mysqli_query($con, $query3);
Notice the i after mysql. Now let us check whether we got some rows or not:
if (!$result3) {
die('Could not retrieve data: ' . mysqli_error($con));
} else {
while ($row = mysqli_fetch_array($result3)) {
//Show your results
}
}
I'm trying to count entries in a database based on 2 basic criteria. It is returning a blank result, even though there are results to be found. Anyone have any idea what I am doing wrong here? I have tried it so many different ways and they all return no result. (If I enter the query directly in phpmyadmin it returns a result.)
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
$numericalResult = mysql_query($sql, $con);
$row = mysql_fetch_object($numericalResult);
$totalOrders1 = $row->total_count;
echo "My orders:" . $totalOrders1;
As others stated, make sure you sanitize variables before they go into query.
$sql = "SELECT * FROM orderOption3Detail WHERE orderDate = '" . $orderDate . "' AND studentID = '" . $studentID . "'";
$sql_request_data = mysql_query($sql) or die(mysql_error());
$sql_request_data_count = mysql_num_rows($sql_request_data);
echo "Number of rows found: " . $sql_request_data_count;
That's all you need.
Edited: providing full code corrected:
$con=mysqli_connect($db_host,$db_user,$db_pass,$db_name); // Check connection
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //global option 1
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
//echo $sql;
$numericalResult = $con->query($sql);
$row = mysqli_fetch_object($numericalResult);
echo $row->total_count; //echo (int) $row->total_count;
Please test this and let me know. Good luck!
----- End Editing ----
Have you tested assigning values directly as a test in your SQL string, like:
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='05/23/2012' AND studentID='17'";
Also, did you check if the date's format is correct, reading that $orderdate variable and testing it in PHPMyAdmin?
Did you read the $sql with values inserted and test in PHPMyAdmin and worked?
Also, check the connection to assure there is no problem there.
One more thing, sorry. You seem to be using the wrong syntax in your mysql_query statement. That way works for mysqli_query, and the parameters would be inverted. Try only:
$numericalResult = mysql_query($sql);
Provided you made the connection and database selection previously, like in:
$connection=mysql_connect($db_host, $db_username, $db_password);
if (!$connection)
{
$result=FALSE;
die('Error connecting to database: ' . mysql_error());
}
// Selects database
mysql_select_db($db_database, $connection);
Best wishes,
here is my db connection code and query code:
// Connecting, selecting database
$link = mysql_connect('MySQLA22.webcontrolcenter.com', 'shudson', '*******')
or die('Could not connect: ' . mysql_error());
mysql_select_db('henrybuilt') or die('Could not select database');
$sql = "SELECT ID, vcImageName FROM corp_images WHERE idPage = 6";
$query = mysql_query($sql) or die ("Error");
There is no 'or die' error upon connecting, selecting, or querying
There is no error_log file
The sql query executes if I run it in my sql browser
What is going on???
$sql = "SELECT ID, vcImageName FROM corp_images WHERE idPage = 6"
Its missing ;
$sql = "SELECT ID, vcImageName FROM corp_images WHERE idPage = 6";
It appears correct...try adding this adapted code from the manual to further debug and see what you learn:
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$query) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $sql;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($query)) {
echo $row['ID'];
echo $row['vcImageName'];
}
What is the best MySQL command to count the total number of rows in a table without any conditions applied to it? I'm doing this through php, so maybe there is a php function which does this for me? I don't know. Here is an example of my php:
<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("some command");
$row = mysql_fetch_array($result);
mysql_close($con);
?>
<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("select count(1) FROM table");
$row = mysql_fetch_array($result);
$total = $row[0];
echo "Total rows: " . $total;
mysql_close($con);
?>
Either use COUNT in your MySQL query or do a SELECT * FROM table and do:
$result = mysql_query("SELECT * FROM table");
$rows = mysql_num_rows($result);
echo "There are " . $rows . " rows in my table.";
mysqli_num_rows is used in php 5 and above.
e.g
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("Result set has %d rows.\n",$rowcount);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
Use COUNT in a SELECT query.
$result = mysql_query('SELECT COUNT(1) FROM table');
$num_rows = mysql_result($result, 0, 0);
you can do it only in one line as below:
$cnt = mysqli_num_rows(mysql_query("SELECT COUNT(1) FROM TABLE"));
echo $cnt;
use num_rows to get correct count for queries with conditions
$result = $connect->query("select * from table where id='$iid'");
$count=$result->num_rows;
echo "$count";
for PHP 5.3 using PDO
<?php
$staff=$dbh->prepare("SELECT count(*) FROM staff_login");
$staff->execute();
$staffrow = $staff->fetch(PDO::FETCH_NUM);
$staffcount = $staffrow[0];
echo $staffcount;
?>
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
echo "number of rows: ",$rowcount;
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
it is best way (I think) to get the number of special row in mysql with php.
<?php
$conn=mysqli_connect("127.0.0.1:3306","root","","admin");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="select count('user_id') from login_user";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result);
echo "$row[0]";
mysqli_close($conn);
?>
Still having problem visit my tutorial http://www.studentstutorial.com/php/php-count-rows.php
$sql = "select count(column_name) as count from table";
Well, I used the following approach to do the same: I have to get a count of many tables for listing the number of services, projects, etc on the dashboard. I hope it helps.
PHP Code
// create a function 'cnt' which accepts '$tableName' as the parameter.
function cnt($tableName){
global $conection;
$itemCount = mysqli_num_rows(mysqli_query($conection, "SELECT * FROM `$tableName`"));
echo'<h6>'.$itemCount.'</h6>';
}
Then when I need to get the count of items in the table, I call the function like following
<?php
cnt($tableName = 'projects');
?>
In my HTML front end, so it renders the count number
It's to be noted that I create the cnt() function as a global function in a separate file which I include in my head, so I can call it from anywhere in my code.