Hey hello everyone,i have a slight problem with my small delete function in php,below is my code
function delete()
{
$q = "DELETE FROM example WHERE **author='frank'";**
$r = mysql_query($q) or die (mysql_error());
if($r)
{
echo 'done';
}
else
{
echo 'not done';
}
}
Now i don't have any author with that name Frank so that means it is not deleting anything
from the database but still shows that done msg
I am not sure why????can anyone please help me
That's because there was no error, delete did execute, it just didn't do anything. You want:
if(mysql_affected_rows() > 0) {
echo "done";
}
There is no error in your query. It will complete successfully. If you read the documentation you will see:
"For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error."
As there is no error in your query it will return TRUE even though nothing has actually been deleted. Deleting nothing is not considered an error.
A delete query will always succeed, even if no rows are actually deleted. If you want to determine how many rows were affected by an insert, update or delete operation, use mysql_affected_rows()
Related
How do I tell when a MySQL UPDATE was successful versus actually updated data?
Example:
TABLE
id city_name
1 Union
2 Marthasville
If I run the following:
$data = array('city_name', 'Marthasville');
//update record 2 from Marthasville to the same thing, Marthasville.
$this->db->where('id', 2);
$this->db->update('table', $data);
if($this->db->affected_rows() > 0)
{
//I need it to return TRUE when the MySQL was successful even if nothing was actually updated.
return TRUE;
}else{
return FALSE;
}
This will return TRUE every time the UPDATE statement is successful, but FALSE when no rows were actually updated.
I need it to return TRUE every time the UPDATE statement was successfully executed even if it doesn't actually change any records.
Have a look at mysql_affected_rows()
It should tell you if anything was actually updated as opposed to nothing was successfully updated resulting in a return of true.
php.net says:
mysql_affected_rows()
Returns the number of affected rows on success, and -1 if the last
query failed.
You could use the following to achieve your desired results:
if($this->db->affected_rows() >= 0){ }
Then you would use mysql_query:
SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query()
returns TRUE on success or FALSE on error.
Simple like this:
$result = $this->db->update('table', $data);
if($result)
{
//without error even no row updated
} else {
}
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.
I have two insert statements. The second one will be executed only after successful execution of first one. What I would like to do is:
$sqlone="Insert into .....";
$sqltwo="Insert into.....";
If (mysql_query($sqlone))
{
If (mysql_query($sqltwo))
{
Show message Data inserted in both tables.
}
}
Try this
$query1 = '...';
$query2 = '...';
$query3 = '...';
if(mysql_query($query1)) {
if(mysql_query($query2)) {
if(mysql_query($query3)) {
echo "success";
}
else { echo "error"; }
}
else { echo "error"; }
}
else { echo "error"; }
Sounds like you're looking for transactions.
A bit of googling gave me some info on database transactions in PHP - hope it helps.
That syntax looks like it works, as...
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
http://au2.php.net/mysql_query
From the documentation:
For other type of SQL statements,
INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success
or FALSE on error.
So as far as I can see there is no problem with what you already have.
You can also create the DB transaction as well in which commit of one insert will execute the second insert statement..
$result=mysql_query(" UPDATE xxxxxx_users SET User_Password='$Password' WHERE FstName='$First' AND LstName='$Last'",$db) or die ("Password update successful!");
echo "Update failed, unknown user";
This correctly updates the db when the first and last names match and the db is not affected when they don't. My only issue is I always display the Update failed, unknown user message. what did I do wrong? Thanks.
The mysql_query function returns true when an SQL query is successful:
For other type of SQL statements,
INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success
or FALSE on error.
Your code is assuming that the query returns the number of rows effected. Use the mysql_affected_rows function for this purpose:
$result=mysql_query(" UPDATE xxxxxx_users SET User_Password='$Password' WHERE FstName='$First' AND LstName='$Last'",$db)
if (mysql_affected_rows() > 0)
die ("Password update successful!");
else
echo "Update failed, unknown user";
You probably need to do this the other way round...
$result=mysql_query(" UPDATE xxxxxx_users SET User_Password='$Password' WHERE FstName='$First' AND LstName='$Last'",$db)
or die ("Update failed, unknown user");
echo "Password update successful!";
If the first part (mysql_query) evaluates to true, there is no need to evaluate the second or part (die). You can use and instead.
And, please, read about SQL Injections.
A suggestion to your coding style:
Something like this:
if ($result)
...success
else
...fail
is much more readable.
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();
?>