This question already has answers here:
How to test if a MySQL query was successful in modifying database table data?
(5 answers)
Closed 1 year ago.
I use the code to update data in mysql.But it always echo "sucess " whatever $id equal to any integer.
$id=isset($_GET['id'])?$_GET['id']+0:0;
$sql="update user set age=50 where id=".$id;
$result=mysql_query($sql,$con);
if($result)
echo "update sucess<br />";
else
echo "update failed";
You should use mysql_affected_rows() instead.
So that an you'll know that it made changes you want.
Obligatory note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Here's what it will look like in using mysqli:
if(isset($_GET['id'])) {
$con = new mysqli('localhost', 'username', 'password', 'database_name');
$id = $_GET['id'];
$sql = 'UPDATE user SET age = 50 WHERE id = ?';
$update = $con->prepare($sql);
$update->bind_param('i', $id);
$update->execute();
if($update->affected_rows > 0) {
echo 'updated';
} else {
echo 'nothing';
}
}
Related
This question already has answers here:
PHP Mysql delete Query not working properly
(3 answers)
Closed 3 years ago.
I tried to delete user from mysql database with this code
if (isset($_POST['user_delete'])) {
$key = $_POST['keyToDelete'];
$check = "DELETE FROM user WHERE id = ". $key or die(mysqli_error($connection));
$result2 = $connection->query($query);
if($result2->num_rows >0){
$query_delete = "DELETE FROM user WHERE id =". $key or die(mysqli_error($connection));
var_dump($query_delete);
} else {
}
but it don't want to delete my database. but the sql already right and I also got the id because I tried to var_dump it. please help what was wrong with my code
You have a few issues here,
Your or die(mysqli_error($connection)) is to the querystrings, not the actual queries. Besides, instead of manually checking for errors it's much better to configure to throw errors automatically. For this add the following line to the connection code:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
You attempt to delete it twice? Though the second query is never executed, you just define the querystring (and never run it).
num_rows is only usable on select-statements. You want affected_rows to check if the query actually deleted any data.
You're not using a prepared statement.
if (isset($_POST['user_delete'])) {
$key = $_POST['keyToDelete'];
$query = "DELETE FROM user WHERE id = ?";
$stmt = $connection->prepare($query);
$stmt->bind_param("s", $key);
$stmt->execute();
if ($stmt->affected_rows) {
echo "Deleted ".$stmt->affected_rows." rows";
} else {
echo "No rows matched the criteria.";
}
$stmt->close();
}
How do I check insert success in my code?
I tried to test my code below, but it doesn't work. It just returns insert every time.
<?PHP
include("connect.php");
$sql = "INSERT INTO details (name , month , description)
SELECT name , month , description
FROM details_temporary WHERE id = 'xxxxxx'";
$dbQuery = mysql_query($sql);
if($dbQuery) {
echo "insert";
}
else {
echo "not insert";
}
?>
Please, don't use mysql_* functions in new
code.
They are no longer maintained and the deprecation
process has begun on it. See
the red box?
Learn about prepared
statements instead,
and use PDO or
MySQLi - this
article will
help you decide which.
An example using the MySQLi functionality is below:
$mysqli = new mysqli('localhost', 'root', 'password', 'database_name');
$sql = "INSERT INTO details (name, month, description) VALUES ('Alex', 'October', 'My Birthday')";
$result= $mysqli -> query($sql);
$affected = $mysqli -> affected_rows;
if($affected == 1){
echo 'Inserted';
}else{
echo 'Did not insert';
}
Firstly, don't use MySQL functions, they're deprecated and insecure, look in to using MySQLi or PDO.
Secondly, MySQL will only return an error if it failed, so you can just simply run:
if (!$dbQuery) {
die('Invalid query: ' . mysql_error());
}
This will die and print the error if it was unsuccessful.
If you want to check further, you could check mysqli_insert_id() as this will only be set if the query was successful (will only work for inserts, not updates, etc).
You are using INSERT FROM SELECT and if the select has no result then it will insert nothing and still have true in $dbQuery.
Use mysql_affected_rows. : Get number of affected rows in previous MySQL operation
mysql_* functions are deprecated as of php 5.5
If you are working on a new project and NOT changing an old one, it's best to use pdo/mysqli etc.
I was wondering if there is any way to check if the update query has executed successfully or else I will execute insert query.
$record = mysql_query("update table set a='$b', b='$c' where id = '$id' ");
echo $record; // returns always 1;
Thank You.
Use the mysql_affected_rows function to find the number of records affected. Please see following code.
$record = mysql_query("update table set a='$b', b='$c' where id = '$id' ");
$total_rows = mysql_affected_rows($conn);
echo $total_rows;
where $conn is the connection object
It will be like
$records = mysql_query("UPDATE `table` SET a='$b', b='$c' WHERE id = '$id' ");
$affected_rows = mysql_affected_rows($records);
if($affected_rows >= 1) {
echo "Updated ".$affected_rows." rows";
}
Need to remove $ before mysql_query.And consider that table is your table name and also makesure that your connection to the DB is active.
And Try to avoid mysql_* statements due to the entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_*, is officially deprecated as of PHP v5.5.0 and will be removed in the future.
There are two other MySQL extensions that you can better Use: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql.
Try this ... It returns the number of modified rows in the last query run.
$Rows = mysql_affected_rows($record).
example $Rows = 1, 2, 3 etc......
mysql_query(): how to check whether any rows are updated in case of UPDATE SQL
mysql_affected_rows() is what you need.
Docs: http://php.net/manual/en/function.mysql-affected-rows.php
mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
if (mysql_affected_rows() > 0) {
echo 'You updated '.mysql_affected_rows(). 'rows.';
} else {
echo 'Nothing updated';
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php - check record exists db - error show
I am currently trying to add a user to the database. I want to to check if the user exists, and IF SO, then just update a few fields. If IT DOESNT, then it should completely insert a new record.
$result22 = mysql_query("SELECT COUNT(1) FROM newsite WHERE user = '$username'");
if($result22){
$SQL = "UPDATE newsite SET active = '1' WHERE user = '$username'";
$_SESSION['username'] = $_GET['user'];
$result = mysql_query($SQL);
echo("lol."); // TEST
header("Location: ./share.php?user=$username");
}
if(!$result22){
$SQL = "INSERT INTO newsite (user, active) VALUES ('".$username."', '1')";
$_SESSION['username'] = $_GET['user'];
$result = mysql_query($SQL);
echo("NOPE."); //TEST
header("Location: ./share.php?user=$username");
}
}
I'm not really sure why, but no matter what it ALWAYS outputs "lol." (aka, the user exists.) it completely ignores the other if.
$result22 = mysql_query("SELECT COUNT(1) FROM newsite WHERE user = '$username'");
if($result22){
Unless you have error in your SQL code, mysql_query returns resultset that is always resolved to true
Also:
Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You can also use the mysql_num_rows function, which returns the number of row of the last result set
if(mysql_num_rows()>0)
{
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to prevent SQL Injection in PHP
In my website users can submit posts and delete their posts.
To delete a post, they follow the link /posts.php?deletid=X where X is the id of the post in database (for example: 1).
When clicked, it will run the following:
if(isset($_GET['deleteid'])) {
$deleteid = $_GET['deleteid'];
$sql = "DELETE from `posts` WHERE `id`=".mysql_real_escape_string($deleteid).";";
$query = mysql_query($sql);
header('Location: posts.php');
exit();
}
The problem is that it's vulnerable to the 1=1 SQL injection. If they type into the address bar /posts.php?deletid=1 OR 1=1;
it will delete all posts on database.
In this question: How can I prevent SQL injection in PHP?, I realized I need to use mysqli statements, and I tried to make it work but with no success..
Can someone please tell me exactly how I can prevent this with mysqli?
You need to have the value in quotes for mysql_real_escape_string to have any useful effect.
$sql = "DELETE from `posts` WHERE `id`='".mysql_real_escape_string($deleteid)."'";
Alternatively, instead of mysql_real_escape_string, which is intended for strings, try intval.
With MySQLi and prepared statements you do not need to worry about this, as a parameter cannot be replaced by 1 OR 1=1 (or if it is provided as the parameter value, then it’s interpreted as a string).
By using prepared statements, the mysql_* functions are on there way out and soon tobe deprecated, one should not be writing new code with these functions, refactor your code.
PDO
<?php
$db = new PDO("mysql:host=localhost;dbname=yourDB", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** prepare the SQL statement ***/
$query = $db->prepare("DELETE from `posts` WHERE `id`=:id;");
/*** bind the paramaters ***/
$query->bindParam(':id', $deleteid, PDO::PARAM_INT);
/*** execute ***/
$query->execute();
header('Location: posts.php');
exit();
?>
mysqli
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("DELETE from `posts` WHERE `id`=?")) {
/* bind parameters for markers */
$stmt->bind_param("i", $deleteid);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
header('Location: posts.php');
exit();
?>
One thing first: if you can, it would be wise not to use mysql_* but e.g. mysqli_* functions or PDO, since the first are outdated. There you can use placeholders (?) instead of string concats. You don't have to care for quoting yourself there.
The easiest option in your example code would be to run all numbers through integer parsing (use intval).
if(isset($_GET['deleteid'])) {
$deleteid = $_GET['deleteid'];
$sql = "DELETE from `posts` WHERE `id`=".intval($deleteid).";";
$query = mysql_query($sql);
header('Location: posts.php');
exit();
}