Just learning PHP and I'm having some trouble understanding mysql_query. My understanding is that mysql_query is supposed to return FALSE if the record is not found. However, it seems that it always returns true because "FOUND!" is always the result:
$q = "SELECT * FROM users WHERE username = 'doesnotexist'";
$r = mysql_query($q);
if (!$q) {
echo "<p>NOT FOUND!</p>";
} else {
echo "<p>FOUND!</p>";
}
mysql_close();
Thanks in advance for any light you can shed.
mysql_query returns false if there is an error, not if there are no results found. From the documentation:
For SELECT, SHOW, DESCRIBE, EXPLAIN
and other statements returning
resultset, mysql_query() returns a
resource on success, or FALSE on
error.
For other type of SQL statements,
INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success
or FALSE on error.
mysql_query() will also fail and
return FALSE if the user does not have
permission to access the table(s)
referenced by the query.
If you want to check to see if there were results returned by your query, use mysql_num_rows(). See the documentation:
Use mysql_num_rows() to find out how
many rows were returned for a SELECT
statement or mysql_affected_rows() to
find out how many rows were affected
by a DELETE, INSERT, REPLACE, or
UPDATE statement.
You are checking the '$q' variable (your sql statement) instead of the '$r' variable (the mysql result)
if (empty($r)) {
echo "<p>NOT FOUND!</p>";
} else {
echo "<p>FOUND!</p>";
}
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Ok i have worked out the answer to this.
This is the version for updating a database that tells you if a record was valid.
$updatequery = "update `mydb` set `userid` = '$arr[0]', `name` = '$arr[1]' where `age` = '$arr[2]'";
$updatequeryresult= mysql_query($updatequery);
$howmanyupdatedrecords = mysql_affected_rows();
if ($howmanyupdatedrecords == 0) {
echo("The update didn't update any records as no one matched an age of " .$arr[2]");
}
This will iterate through the DB updating all people with the specified age, if the age does not exist in the DB a message will be displayed showing you the age that does not exist. Also something to note, even if the mysql query matches a record, it won't update the record if the data already matches what it is being updated to. This causes the script to return "no one matched an age" even though there are people who did match. Can only attribute that to a bug in mysql. I told MySQL to update the information I don't see why it should take it upon itself to not bother doing as i told it. ;)
Your 'if (!$q)' should be 'if (!$r)' I think.
if that dosen't work, try this:
<?php
$q = "SELECT * FROM users WHERE username = 'doesnotexist'";
$r = mysql_query($q);
if (!mysql_num_rows($r) >= 1) {
echo "<p>NOT FOUND!</p>";
} else {
echo "<p>FOUND!</p>";
}
mysql_close();
?>
Related
This is so baffling I MUST be missing something simple. I have a query that checks to see if the transaction I'm inserting already exists in order to prevent duplicates. Here's the code:
function isaDupe($portableDB, $transactArray)
{
$ref = $transactArray["reference"];
$date = $transactArray["qdate"];
$time = $transactArray["time"];
//prints the query so I can run by hand to test
print "SELECT `counter` FROM transactions WHERE (`reference` = '$ref' AND `qdate` = '$date' AND `time` = '$time') ";
if ($dupeSelectStmt = $portableDB->prepare("SELECT `counter` FROM transactions WHERE (`reference` = ? AND `qdate` = ? AND `time` = ?)"))
{
$dupeSelectStmt->bind_param('sss',$ref, $date, $time);
$dupeSelectStmt->bind_result($counter);
$dupeSelectStmt->execute();
while ($dupeSelectStmt->fetch())
{
break;
}
$numRows = $portableDB->affected_rows;
if ($numRows > 0)
return TRUE;
else if ($numRows == -1)
{
print " ERROR: ";
print_r($portableDB->error);
print_r($dupeSelectStmt->error);
return FALSE;
}
else
return FALSE;
}
}
-If I run the query by hand through Workbench on the same server, I get 24 rows returned.
--this is the same if I prepare, set, and execute the statement by hand.
-affected_rows returns -1
--same if I do num_rows on the statement
-there is no error stored on the Statement or MySQLi object.
-if I put a print in the fetch() statement, it prints one row's worth of data
-if I store the fetched rows into an array and count the results, it's 1
-I've tried running it with each variable separately, same thing.
-other queries on the same server (heck, on the same MySQLi object) are working fine. SELECTS, UPDATES, and INSERTS.
The answer is I was forgetting to call mysqlistmt::store_result after mysqlistmt::execute().
Once I added $dupSelectStmt->store_result(); I was able to call $dupSelectStmt->num_rows and $portableDB->affected_rows and they both showed the 24 I knew I should be seeing.
You need you use $dupeSelectStmt->num_rows() to get the number of rows in the result set for a SELECT. You need to call either affected_rows (for INSERT, DELETE, UPDATE) or num_rows() on the mysqli_stmt object not not on the database handle ($portableDB) as you are currently doing.
What I mean is, for example, if I search for something on an SQL table, and it returns 0 / nothing, is that null or empty or does it result in an empty ""?
I'm getting back into php and trying to loop through a db like so:
Pseudo code:
while($row = mysqli_fetch_array($var here that has the query to the db and connection)){
echo $row[//something pulled from table to be read back]
}
But let's say that the search query didn't return any results or that $row doesn't equal to anything because for whatever reason, the value searched for in the db doesn't exist,
How then can I check for the empty-ness of row?
if the searched for item doesn't exist in the db, then $rows value becomes what exactly? null/empty/or empty string or something else?
depending on the value of row, do I test for [isset / !isset] or [empty / !empty] ? Or is the only way to test for empty $row to do a (pseudo) $x =mysqli_num_rows(var here) / if ($x == 0 ) //do something?
If mysqli_fetch_array did not return anything, then the return value is NULL
The line while($row = mysqli_fetch_array is supposed to return the next available record in the record set, so if the query did not give any matching results, then the line echo $row['something'] does not get executed at all.
If there are multiple fields you are fetching, say field1, field2 and supposing field2 doesn't have a value, then what is returned for that field is what the default value for that field will be in MySQL (or whichever DB you are using). However the point to note is that $row will still have two keys defined correctly as $row['field1'] and $row['field2']
If you want to check if $row['field2'] does have any value you can check it using empty($row['field2']).
"", 0, NULL, FALSE, array() are all considered empty() so you should be able to safely determine if the field has any valid value in it using this function. However, if say 0 could be a valid value (for e.g. you are querying no_of_days a person was absent last month and some of them have full attendance), you will need to explicitly check the value in the field and cannot depend on empty().
You can check whether there is result using mysql_num_rows. If there is items exist in that row, the row should have show one or more or TRUE depending on the item you searched, if nothing exist in database when you executed the query means the mysql_now_rows will show you 0/NULL.
You can do like
$query = mysql_query("YOUR QUERY HERE");
$numrow = mysql_num_rows($query);
if ($numrow == 0)
{
ECHO "No result found.";
}
When there's nothing, $row == false
That's the correct test on the while loop!
You can use mysqli_num_rows to fetch the number of results found by a query.
$query = 'SELECT `blah`';
$result = mysqli_query($query);
if(mysqli_num_rows($result) > 0) {
// do stuff here if any rows are found
} else {
// do stuff here if NO rows are found
}
<?php
$uname=$_POST['uname'];
$pwd=$_POST['pwd'];
$result="";
echo($uname.'</br>');
echo($pwd);
$con=mysql_connect("localhost","root","");
mysql_select_db("user_login_test",$con);
$sql="SELECT * FROM userlogin WHERE username='".$uname."'";
if($result=mysql_query($sql))
{
echo($result);
echo("Extracted<br>");
}
else
{
echo("NOT Extracted");
}
while($row = mysql_fetch_array($result))
{
echo $row['username'] . " " . $row['password'];
echo "<br />";
}
?>
I am doing above code for extracting values. If Username matches it show the value but if I give wrong input text it also shows "Extracted" with no value why? Please help me???
As explained in the PHP manual entry for the mysql_query() function:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
Your $result variable therefore holds a MySQL resource irrespective of whether there is a match on the username column: testing such a resource using if will always evaluate to TRUE (unless the query itself threw an error).
The manual goes on to explain:
The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.
Use mysql_num_rows() to find out how many rows were returned for a SELECT statement or mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.
In your case, you could test using mysql_num_rows() to determine whether any records were returned by the query (i.e. whether the WHERE condition was satisfied).
You have write wrong logic for extract username.
I have modify your code check it.
$sql="SELECT * FROM userlogin WHERE username='".$uname."'";
$result=mysql_query($sql)
if(mysql_num_rows($result)>0)
{
echo("Extracted<br>");
}
else
{
echo("NOT Extracted");
}
I am trying to get the number of rows affected in a simple mysql update query. However, when I run this code below, PHP's mysql_affected_rows() always equals 0. No matter if foo=1 already (in which case the function should correctly return 0, since no rows were changed), or if foo currently equals some other integer (in which case the function should return 1).
$updateQuery = "UPDATE myTable SET foo=1 WHERE bar=2";
mysql_query($updateQuery);
if (mysql_affected_rows() > 0) {
echo "affected!";
}
else {
echo "not affected"; // always prints not affected
}
The UPDATE statement itself works. The INT gets changed in my database. I have also double-checked that the database connection isn't being closed beforehand or anything funky. Keep in mind, mysql_affected_rows doesn't necessarily require you to pass a connection link identifier, though I've tried that too.
Details on the function: mysql_affected_rows
Any ideas?
Newer versions of MySQL are clever enough to see if modification is done or not. Lets say you fired up an UPDATE Statement:
UPDATE tb_Employee_Stats SET lazy = 1 WHERE ep_id = 1234
Lets say if the Column's Value is already 1; then no update process occurs thus mysql_affected_rows() will return 0; else if Column lazy had some other value rather than 1, then 1 is returned. There is no other possibilities except for human errors.
The following notes will be helpful for you,
mysql_affected_rows() returns
+0: a row wasn't updated or inserted (likely because the row already existed,
but no field values were actually changed during the UPDATE).
+1: a row was inserted
+2: a row was updated
-1: in case of error.
mysqli affected rows developer notes
Have you tried using the MySQL function ROW_COUNT directly?
mysql_query('UPDATE myTable SET foo = 1 WHERE bar = 2');
if(mysql_result(mysql_query('SELECT ROW_COUNT()'), 0, 0)) {
print "updated";
}
else {
print "no updates made";
}
More information on the use of ROW_COUNT and the other MySQL information functions is at: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_row-count
mysqli_affected_rows requires you to pass the reference to your database connection as the only parameter, instead of the reference to your mysqli query. eg.
$dbref=mysqli_connect("dbserver","dbusername","dbpassword","dbname");
$updateQuery = mysqli_query($dbref,"UPDATE myTable SET foo=1 WHERE bar=2");
echo mysqli_affected_rows($dbref);
NOT
echo mysqli_affected_rows($updateQuery);
Try connecting like this:
$connection = mysql_connect(...,...,...);
and then call like this
if(mysql_affected_rows($connection) > 0)
echo "affected";
} else { ...
I think you need to try something else in update then foo=1. Put something totaly different then you wil see is it updating or not without if loop. then if it does, your if loop should work.
You work this?
$timestamp=mktime();
$updateQuery = "UPDATE myTable SET foo=1, timestamp={$timestamp} WHERE bar=2";
mysql_query($updateQuery);
$updateQuery = "SELECT COUNT(*) FROM myTable WHERE timestamp={$timestamp}";
$res=mysql_query($updateQuery);
$row=mysql_fetch_row($res);
if ($row[0]>0) {
echo "affected!";
}
else {
echo "not affected";
}
This is because mySql is checking whether the field made any change or not,
To over come this, I created a new TINY field 'DIDUPDATE' in the table.
added this to your query 'DIDUPDATE=DIDUPDATE*-1'
it looks like.
$updateQuery = "UPDATE myTable SET foo=1, DIDUPDATE=DIDUPDATE*-1 WHERE bar=2";
mysql_query($updateQuery);
if (mysql_affected_rows() > 0)
{
echo "affected!";
}
else
{
echo "not affected";
}
it works fine!!!
Was My Tought !
I was just about to tell to check if the function's being called many times !
Just a little advice:
try using isset() & POST / GET or something like that;
if ( isset( $_POST['Update'] == 'yes' ) ) :
// your code goes here ...
endif;
Hope it was clear and useful, Ciao :)
Ok so the problem is... i m a newbie and i m trying to understand what is happening.Im sending through an html form this data(name,email) using POST in a database.I understand the logic behind it all but what basically happens is that everytime I enter a name,any name,it echoes the else statement:"there is already a user with that name". and it sends back the first name in the database.when there s nothing,it sends nothing. So here's the chunk:
$query= "SELECT* from users where username='".$_POST['name']."'";
$result = mysql_query($query);
if (!$result){
$query = "INSERT into users (username, email, password) values
('".$_POST["name"]."', '".$_POST["email"]."',
'".$passwords[0]."')";
$result = mysql_query($query);
if ($result){
echo "It's entered!";
} else {
echo "There's been a problem: ".mysql_error();
}
} else {
echo "There is already a user with that name: <br />";
$sqlAll = "select * from users";
$resultsAll = mysql_query($sqlAll);
$row = mysql_fetch_array($resultsAll);
while ($row) {
echo $row["username"]." -- ".$row["email"]."<br />";
$row = mysql_fetch_array($result);
You may want to check mysql_num_rows() rather than checking for !$result, I think that if the query is sucsesfull you'll get a resource back, even though it contains zero rows.
You may also want to read up on: http://php.net/manual/en/security.database.sql-injection.php
ESCAPEEEEE
Firstly, you need to learn about escaping.
Have you never heard of little Johnny DROP TABLES?
http://xkcd.com/327/
Serious business
The reason why it always returns, is because the response in $result is actually a resource data type. And that will always when cast as a boolean be true. (And since your query shouldn't fail).
You should fetch the result. For example. (This isn't the best way, but it is a way to do it).
mysql_fetch_row(result)
Per the manual, mysql_query will return false when there is an error - "For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error."
see no violation in your code. first mysql_query executes with no error and always returns true. try to test returned rows count like this:
if (mysql_num_rows($result) == 0) {
//insert record
} else {
// show alreay exists
}
First of all, you are testing for:
if (!$result)
which will evaluate to true only if the query fails.
You should also sanitize all input before using it in SQL queries.