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.
Related
I have a table and i'm trying to extract the maximum value of a column called order_num, which has 33 intries of integers 1 through 33. I want the value "33" in this instance as its the highest number.
$userid is an integer derived from a one row table with a field id that I am trying to retrieve
//get the currentUser ID so we know whos deck to ammend
$userIDSQL = "SELECT id FROM currentUser";
$userIdResult = mysqli_query($db, $userIDSQL) or die("SQL Error on fetching user ID: " . mysqli_error($db));
$result_array = array();
while ($row = mysqli_fetch_assoc($userIdResult)) {
$result_array[] = $row['id'];
}
//the actual user id
$userId = $row['id'];
echo "user id is " . $userId;
Doing a print_r on $userId shows the array to be empty, that's why the code below doesn't work.. :(
...
$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId'";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));
$result_array = array();
while ($row = mysqli_fetch_array($reOrderDeckResult)) {
$result_array[] = $row['MAX(order_num)'];
echo "the result is" . $result_array['order_num'];
echo "the result is" . $row['order_num'];
echo "the result is" . $result_array['MAX(order_num)']; //tried different methods to get the output.
}
The output I get is
the result is the result is the result is
Does anyone know why i'm not able to get the result from the table?
Edit:
Okay, try this:
while ($row = mysqli_fetch_array($reOrderDeckResult)) {
print_r($row);
}
What do you get?
Your first code to get the userId doesn't work because of your usage of the array, change to:
$userId = 0;
while ($row = mysqli_fetch_assoc($userIdResult)) {
$userId = $row['id'];
}
As I've shown below, if you only expect a single row then remove the while loop and just call fetch_assoc a single time.
Given you only want the single row you don't need the while loop:
$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId' LIMIT 1";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));
if($reOrderDeckResult && mysqli_num_rows($reOrderDeckResult) == 1)
{
$row = mysqli_fetch_assoc($reOrderDeckResult);
echo 'result: ' . $row['order_num'];
}
else
{
echo 'No rows found!!';
}
I also added LIMIT 1 to the query, and a check to see if there are any rows.
You have renamed your MAX(order_num) AS order_num so you should try to get value using order_num only as echo $result_array['order_num']
and in while you should check whether you are getting value or not by placing below code in while loop
echo '<PRE>';
print_r($row);
echo '</PRE>';
This may helps you..,
<?php
$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId'";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));
$result_array = array();
while ($row = mysqli_fetch_array($reOrderDeckResult)) {
//you have to use the alias name not aggregate function title
$result_array[] = $row['order_num'];
echo "the result is" . $result_array['order_num'];
echo "the result is" . $row['order_num'];
//you have to use the alias name not aggregate function title
echo "the result is" . $result_array['order_num']; //tried different methods to get the output.
}
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';
}
I've got this code:
$query = 'SELECT * FROM users WHERE username = "' . $user . '" AND password = MD5("' . $pass . '") LIMIT 1';
echo $query;
$result = $mysqli->query($query);
echo "<br>Here: " . $result->num_rows;
Using the output from $query I put it into phpmyadmin and it returns 1 row but when trying to get the number of rows using num_rows it doesn't return anything at all - not even 0;
Any ideas?
http://ru2.php.net/manual/en/mysqli.query.php
Returns FALSE on failure.
Have you established a connectection to your DB?
Looks like the SQL query is messed up. As far as I know there is no MD5 function built into MySQL nor the SQL standard. Therefore if it does exist then it is probably proprietary to the particular DB.
That said you can use PHP to check it. Try this to see what is going on.
$encrypted_pass = md5($pass);
$query = "SELECT * FROM users WHERE username = '$user' AND password = '$encrypted_pass' LIMIT 1";
echo $query;
$result = $mysqli->query($query);
if ($result !== FALSE) {
echo "<br>Here: " . $result->num_rows;
}
else {
echo "Something is broken.";
}
Ref:
http://us2.php.net/manual/en/mysqli-result.num-rows.php
I feel like I'm missing something really simple here. Here's my sql query:
$getpages = "SELECT id FROM pages WHERE account = 2 ORDER BY page_order";
$showpages = #mysqli_query ($dbc, $getpages);
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
I then print the first result:
echo $row[0];
And get a correct value, the id of the first page (by page order):
10
So I submit a form which simply turns that $row[0] into $row[1].
And nothing prints. I don't understand.
You have to do this:
while ($row = mysqli_fetch_array($showpages, MYSQLI_NUM)) {
$id = $row[id];
// do something with the id
echo $id . "<br/>"; // Echo every id
}
This will iterate through all of the results
mysqli_fetch_array is a special function as each time you call it, it outputs the NEXT row.
So:
while ($row = mysqli_fetch_array(stuff)){
$var = $row['sql column'];
// In your case "$var = $row[0];" to get the id for the first row found.
}
is how you use it.
This will keep running the function until mysqli_fetch_array() eventually returns false. These each time it will output a new row. And the $row array is the array of one row in the sql table.
Use :
print_r($row);
in the while loop to see exactly what's being returned for use.
$getpages = "SELECT id FROM pages WHERE account = 2 ORDER BY page_order";
$showpages = #mysqli_query ($dbc, $getpages);
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
Question how many rows are fetched in this query in this case id, So MYSQL will result to 1 row affected, But since you are using
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
This code you used will not output anything try
$row[n] as n-1
$result->fetch_assoc() or mysqli_fetch_assoc($result)
catch one line at a time, from a mysqli_result:
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
source: http://www.w3schools.com/php/php_mysql_select.asp
I have the code below which is supposed to check the database for entries with a certain username which is working but when I try to add some code to check if the rows returned is greater than 10 and then run some code to limit the number of rows to 10 and then if not run another piece of code which will display all the rows.
Code:
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$checkres = mysql_query("SELECT COUNT link, notes, titles, color FROM links WHERE username='" . $username . "';");
if ($checkres>10)
{
$resultsmall = mysql_query("SELECT link, notes, titles, color FROM links WHERE username='" . $username . "' LIMIT 10;");
while ($rowsmall = mysql_fetch_array($resultsmall)) { //loop
extract($rowsmall);
$htmlsmall .= "
//code goes here to format results
";
echo $htmlsmall; //display results...
}
}
else {
$result = mysql_query("SELECT link, notes, titles, color FROM links WHERE username='" . $username . "';");
while ($row = mysql_fetch_array($result)) { //loop
extract($row);
$html .= "
//code goes here to format results
";
echo $html; //display results...
}
}
mysql_close($con); //close db..
But it just displays two times the number of rows in the database instead of either limiting it or displaying them all. How would I fix this? The //code goes here for formatting isn't important it just formats the code so that it looks nice and displays it in a box...
Thanks!
EDIT:
I now have this code but it now doesn't display anything at all? Can someone help:
Code:
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$sql = "SELECT SQL_CALC_FOUND_ROWS link, notes, titles, color FROM links WHERE username='" . $username . "' LIMIT 10";
$result = mysql_query($sql) or die("MySQL error: " . mysql_error());
$subsql = "SELECT found_rows() AS foundrows;";
$subresult = mysql_query($subsql) or die("MySQL error: " . mysql_error());
$found_rows = $subresult['foundrows'];
if($found_rows > 10)
{
while($row = mysql_fetch_array($result))
{
extract ($row);
$html .= "
//getting values from columns and then formatting them goes here
";
echo "Only 10 is allowed.";
}
}
else
{
while($row = mysql_fetch_array($result))
{
extract($row);
$html .= "
//getting values from columns and then formatting them goes here
";
}
}
mysql_close($con); //close db..
Thanks!
EDIT 2 (12 April 14:03 2011 GMT):
I now have this code which has been kindly helped by Col. Shrapnel but it doesn't display anything for me and I don't know why, please could some help.
Code:
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$sql = "SELECT link, notes, titles, color FROM links WHERE username='$username' LIMIT 10";
$res = mysql_query($sql);
if (mysql_num_rows() == 10) {
while ($row = mysql_fetch_array($res)) {
extract($row);
$htmlsmall .= "
=
";
$htmlfree .= "Only 10 is allowed.";
echo $htmlsmall;
echo $htmlfree;
}
}
else {
while ($row = mysql_fetch_array($res)) {
extract($rowsmall);
$htmlsmall .= "
";
echo $htmlsmall;
}
}
Now if I view the page source I can see these 2 errors:
<b>Warning</b>: Wrong parameter count for mysql_num_rows() in <b>//url was here</b> on line <b>109</b><br />
<b>Warning</b>: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>//url to file goes here</b> on line <b>125</b><br />
Line 109 is this: if (mysql_num_rows() == 10) {
Line 125 is this: while ($row = mysql_fetch_array($res)) {
(Those lines are in the code above)
Please could someone help me with this?
Thanks!
mysql_query() returns either a result statement handle, or boolean FALSE if the query failed. Your outer query is invalid:
SELECT COUNT ...
does not work, so the query fails, returns false, which jumps to the lower "unlimited" query.
However, you're going about the process of limiting things in a roundabout fashion that forces the query to run at least twice.
What you want is
$sql = "SELECT SQL_CALC_FOUND_ROWS link, notes, etc.... LIMIT 10";
$result = mysql_query($sql) or die("MySQL error: " . mysql_error());
$subsql = "SELECT found_rows() AS foundrows;";
$subresult = mysql_query($subsql) or die("MySQL error: " . mysql_error());
$found_rows = $subresult['foundrows'];
if ($found_rows > 10) {
... there's more than 10 rows available, though we're fetching only 10 because of the LIMIT
} else {
... 10 rows or less
}
The SQL_CALC_FOUND_ROWS is a MySQL extension that forces MySQL to calculate how many rows would have been fetched, if the LIMIT clause had not been present. You can get the results of this calculation with the found_rows() query function.
This way, you only run the main query once, do the very very quick found_rows() query, and off you go.
Given that you don't seem to be formatting your output any differently between the "more than 10" and "10 or less" version, except for the "only 10 allowed" line, how about this:
$sql = "...";
$result = mysql_query($sql) or die(mysql_error());
$rowcount = 0;
while ($row = mysql_fetch_assoc($result)) {
$rowcount++;
... output a row ...
if ($rowcount > 10) {
echo "Only 10 allowed";
break;
}
}
There's no need for duplicated code, excess logic, etc... when something simple will do.
I try to add some code to check if the rows returned is greater than 10 and then run some code to limit the number of rows to 10
It makes no sense.
Just run your query with LIMIT 10 and you will get your data.
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$sql = "SELECT * FROM links WHERE username='$username' LIMIT 10";
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
while ($row = mysql_fetch_array($res)) {
extract($rowsmall);
$htmlsmall .= ""; //code goes here to format results
}
echo $htmlsmall;
That's all.
If you still want to echo "Only 10 is allowed." (dunno why though) you can add these 3 lines below
if (mysql_num_rows($res) == 10) {
echo "Only 10 is allowed.";
}
However I see not much point in it.
Also note that your program design is probably wrong, as you're apparently copying this file for the every user in your system
To get number of rows returned in result you must use mysql_num_rows.
if (mysql_num_rows($checkres)>10)