Mysql Count query returning "Query was empty" - php

I am using the following script to try and count the rows in a table, the problem I keep getting is the error :
Query was empty
Quiz Name
and a blank page. Im new to COUNT, so I think I might be making a mess of it :-S .
My database layout is as follows :
itsnb_chronoforms_data_createquestions cf_id ,cf_uid,cf_created ,cf_modified, cf_ipaddress, cf_user_id, quizID, questionID, quizquestion, quizanswer1, quizanswer2, quizanswer3, quizanswer4, questionformat ,correctanswer
The script I am working on is :
// Define Quiz Variables
$quiz = $row['quizID'];
$quizcfid = $row['cf_id'];
$quizname = $row['quizname'];
// Finish Define Quiz Variables
///////////////////////////////////////////////////////////////////////////////////////////////
// Make a MySQL Connection
$query8 = "SELECT COUNT(*) as 'numberofquestions' FROM employees WHERE quizID='$quiz'";
$result8 = mysql_query($query) or die(mysql_error());
// Print out result
while($row8 = mysql_fetch_array($result8)){
echo 'There are '. $row8['COUNT(quizID)'] . ' questions';
}
///////////////////////////////////////////////////////////////////////////////////////////////

Your problem is that you are running the wrong query, you are running $query and not $query8
change to this :
$result8 = mysql_query($query8) or die(mysql_error());
in a second glance, you should also change to :
echo 'There are '. $row8['numberofquestions'] . ' questions';
as you set numberofquestion to be the count alias.

$result8 = mysql_query($query) or die(mysql_error());
should be
$result8 = mysql_query($query8) or die(mysql_error());
since i'm guessing the variable $query is empty which you were passing it before.
As for COUNT() stay away from COUNT(*), instead use COUNT(field_name) and for even faster results ensure that the field_name is in the index being used.
Count simply counts the total rows returned for the specified field.
Also, be carefull of using COUNT(*) in innodb as it will force a TABLE SCAN if not used with a WHERE clause on an index.

Replace your following line:
echo 'There are '. $row8['COUNT(quizID)'] . ' questions';
for this one:
echo 'There are '. $row8['numberofquestions'] . ' questions';
As numberofquestions is the name of the only field from your query result set.

To get the number of rows in your result use mysql_num_rows:
$numberOfRows = mysql_num_rows($result8)

You have misstyped this
$result8 = mysql_query($query8) or die(mysql_error());
and also
echo 'There are '. $row8['numberofquestions'] . ' questions';

The sentence sql i see rigth.
But i use this
$result8 = mysql_query($query) or die(mysql_error());
$count = mysql_fetch_row($result8);
echo 'There are '.$count[0].' '. questions';
Other Option:
while($row8 = mysql_fetch_array($result8,MYSQL_ASSOC)){
echo 'There are '. $row8['numberofquestions'] . ' questions';
}

Related

Mysql if 'where' Clause condition failed then print php "message" else update row

I have a mysql 'udate' query with 'where' condition checks '$mobile' with table
column_field 'Mobile', if the value from 'textfield' to the 'where'
condition is not matching with table column_field (Then the updation will
not occur on table row).
If the 'where' condition does NOT match on the table column_field
'Mobile'='$mobile' , how can i print "Error Message" on php code.
<?php
$sql ="update mytable set total_amount = total_amount + '$total_amt',
remaning_points = earned_points - redeemed_points where Mobile = '$mobile'";
$result = query($sql);
if (!$result)
{
echo "USER NOT EXISTING";
exit;
}
else
{
echo "UPDATED";
}
?>
You can easily do it as per answers or comments here, but the ideal way to do such things is to check for existence of the record, before you perform insert/update anything in database.
$query = 'select * from table where mobile="' . $mobile . '"';
$result = mysqli_query($con,$query);
if ($result->num_rows > 0) {
$query = 'update mytable set total_amount = total_amount + ' . $total_amt . ',
remaning_points = earned_points - redeemed_points where Mobile = "' . $mobile . '"';
$result = mysqli_query($con,$query);
}
else {
echo "No record matched";
}
You can send this message to the other page by using Session or GET. This will your code will ensure ACID properties of Database. It should perform the check before performing Data Manipulation Language (DML) Statements.
Have you seen the mysql function mysql_affected_rows()?
It returns how many rows/entrys were affected by your update query. If this functions returns zero (0) then it "failed" (the user does not exist).

trying to count entries in a database

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,

Using PHP to pull data from MySQL table column randomly

I am using the following (assume I already plan to change these to mysqli at a later date and am aware of the insecurity of the queries used), to pull text strings from rows in one column in a MySQL table and the output in a browser would, ideally, be a randomly selected string from this column:
mysql_connect($host,$username,$password);
mysql_select_db($database) or die(mysql_error ());
$query="SELECT * FROM `tablename` ORDER BY RAND() LIMIT 0,1;";
$result=mysql_query($query);
$rows = array();
while($row = mysql_fetch_array($rs)) {
$rows[] = $row;
}
mysql_close();
$max = count($rows) - 1;
Using the following echo line to achieve the last bit in the browser:
echo $rows[rand(0, $max)][0] . " " . $rows[rand(0, $max)][1] . " " . $rows[rand(0, $max)][2] . " " . $rows[rand(0, $max)][3] . " " . $rows[rand(0, $max)][4]$
?>
I receive the error "PHP Notice: Undefined offset: 0 in script.php on line 19" in reference to this echo line (which, admittedly, was pieced together from other threads and tutorials, so I do not follow completely), however, I've since resolved all other errors logged and observed, so if possible, how can I amend this so the output is just a single row (the text within it) from the column?
Faster and better than using RAND()
$conn = mysqli_connect($host,$username,$password, $database);
if($conn->connect_errno > 0) {
die('Unable to connect to database [' . $conn->connect_error . ']');
}
$total_rows = 20; //Generate Random number. You could get $total_rows with a first query counting all rows.
$selected_row = mt_rand(0, $total_rows);
//$selected_row -= 1; //just in case you randomized 1 - $total_rows and still need first row.
//Use the result in your limit.
$query="SELECT * FROM `tablename` LIMIT $selected_row, 1;";
$result=$conn->query($query);
while($row = $result->fetch_assoc()) {
echo $row["columnname"];
}
Edit it from mysql to mysqli (on the fly). You would not want to use RAND() if your table is very large. Believe me!
In your SELECT-statement, you are telling the database to order the strings randomly. So just get the first one and echo it:
$row = mysql_fetch_array($rs)
echo $row['name_of_field_you_want_to_echo'];
You never define the variable $rs. Other than that...
If you are selecting the first items from a SQL query, you don't need to specify both the limit and top.
$result = mysql_query("SELECT * FROM `tablename` ORDER BY RAND() LIMIT 1");
Since that will ever return one row, you can use mysql_fetch_row
$row = mysql_fetch_row($result);
and then you can get the field from that row with
echo $row["column_name"];

SQL Multiple Update Statements

I need to update 40 rows in a database, starting at the point where the userID is a match. I do not want to have to determine the row number because eventually this database will be huge.
What I would like to do is simply say:
"Update these the next 40 rows with my array where userID = myUserID"
Here is what I have:
<?php
// connect to the database and select the correct database
$con2 = mysql_connect("localhost","Database","Password");
if (!$con2)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ifaves_code", $con2);
$i = 0;
while ($i < 40) {
//cycle through the array
$cycleThrough2 = $updatedUserNames[$i];
//$query = "UPDATE tblUserLinks SET `URLName` = '$cycleThrough2' WHERE userID = '" . $mainUID . "' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
++$i;
}
mysql_close();
?>
The variable $mainUID is being set correctly, the problem I'm having is it appears there are no updates taking place in the database.
How can I alter my existing code to receive my desired behaviour?
I don't suppose it's because you have your query building statement commented out...
//$query = "UPDATE tblUserLinks SET `URLName` = '$cycleThrough2' WHERE userID = '" . $mainUID . "' LIMIT 1";
If this is just the result of debugging and it wasn't working before that, you must call mysql_error() right after mysql_query() to see why it is failing.
$result = mysql_query($query);
if (!$result) echo mysql_error();
Also, you are using LIMIT 1 at the end, but the userID never changes in the WHERE clause. Therefore, you are updating the same row over and over 40 times on each loop. What you need is a way in your WHERE clause to identify rows which have already been modified, and exclude them. Otherwise, the same row (first match) will always be caught by the LIMIT 1 and updated.

selecting row from mysql if id matches

I want to select a row from mysql which matches a specific id. I want to get the result if the ID matches, if the ID does not exists in the database, it should not do anything.
I run sth like this:
$q = "SELECT * FROM entries where id= '1'";
$result = mysql_query($q) or die(mysql_error());
if($result){
$row = mysql_fetch_array($result) or die(mysql_error());
$name = $row['name'];
}
echo "hello".$name;
If the id '1' exists in the db, it should get the name, otherwise nothing or at least it should give the error, but when i use this, it just display no any content of the page which comes after this code. What I'm doing wrong?
If it does not display any code after this code, this is probably due to an error occuring and your error handling being set so the error is not displayed.
Try searching for the php error log file (normaly php_error.log) that should contain the error that you do not see.
Another thing i would try is adding more echo statements to see where exactly php stops interpreting.
Like this:
$q = "SELECT * FROM entries where id= '1'";
$result = mysql_query($q);
echo '<br />Query is send';
if(!$result) {
die('<br/>MySQL Error: ' . mysql_error());
}
else {
echo '<br />Result is true';
$row = mysql_fetch_array($result);
echo '<br />tryed fetching row';
if ($row === FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo '<br />$name now is "' . $name . '"';
}
else {
die('<br/>MySQL Error: ' . mysql_error());
}
}
echo '<br />hello: "' . $name . '"';
That might help to get some more information about your problem.
$id = 1;
$sql = "SELECT `name` FROM `entries` WHERE `id` = $id LIMIT 1" //Since the id is probably an integer type on the DB, the single quotes aren't necessary, and sometimes screw it up. I think MySQL possibly thinks it's a string when in quotes.
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result))
{
$row = mysql_fetch_assoc($result) or die(mysql_error());
$name = $row['name'];
echo 'Hello ' . $name;
}
A SELECT query can return 0 rows if the condition you specified doesn't match any rows, and that isn't an error.
You should rather check the result of mysql_num_rows() after sending the query.
Maybe you should add a else statement to your if.
if($result)
....
else
do something
You might even want to do a try catch statement.

Categories