Check mysql_query results if DELETE query worked? [duplicate] - php

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 have a DELETE query which deletes a record from a mysql db.
is there any way to make sure if the delete was performed or not?
I mean, for a query to FIND stuff you do
$res=mysql_query($var);
$nr=mysql_num_rows($res);
and you get nr of rows returned.
Is there any similiar method for deletion of records?
Thanks

Use mysql_affected_rows(). It does not require the response as a parameter.
mysql_query('DELETE FROM whatever');
$num = mysql_affected_rows();
Also, I like PDO better than the classic mysql_ functions. Just saying.

mysql_affected_rows() extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead,the MySQLi or PDO_MySQL extension should be used.
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("DO SOMETHING");
$mysqli->affected_rows;

Related

MySQL INSERT statement not executed [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 6 years ago.
I cannot for the love of god figure out why this statement is not executing. When I limit it to
mysql_query("INSERT INTO my_pets() VALUES ()", $con);
it fires just fine, creating an empty row (NULL in every cell), but as soon as I give it columns and values, it refuses. See below.
Can someone point out a mistake or any other reason this (seemingly) correct code isn't firing when columns and values are specified?
Premises:
$h, $un, $pw, and $db are all fine, as I have copied it from documents that work as we speak.
There are no typos or mistakes in upper/lower case characters of column names and such.
The code:
<?php
session_start();
$h="..."; // Host name
$un="..."; // Mysql username
$pw="..."; // Mysql password
$db="..."; // Database name
$con = mysql_connect("$h", "$un", "$pw")or die("cannot connect");
mysql_select_db("$db")or die("cannot select DB");
$name = "Pip";
$gender = "F";
$species = "Dog";
mysql_query("INSERT INTO my_pets (name, gender, species) VALUES ('$name', '$gender', '$species')", $con);
mysql_close($con);
?>
Obtained from PHP Documentation, If you're using PHP 7.0.0, mysql_query will no longer work:
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_query()
PDO::query()
Good / Important note from someone who cares: This function should not be used for any future code and should be replaced for existing code, so I would recommend you change to PDO.

How to update database using PHP variables? [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 3 years ago.
$Createdby=$_SESSION['adminlog'];
$total =$_POST['total'];
$due =$_POST['due'];
$date =$_POST['issedate'];
$invoiceno =$_POST['invno'];
$CmpnyName =$_POST['CmpnyName'];
$itemdetails =$_POST['item_details'];
$itemname =$_POST['itemname'];
$amtpaid =$_POST['paid'];
$query = "UPDATE billdata SET Total='$total' Due='$due' WHERE InvoiceNo=$invoiceno";
$result = mysql_query($query);
This is the code I am using to get HTML values to variable and update particular invoice number with new data.
First off, never use the deprecated mysql_* API.
Switch to either PDO or mysqli, both have prepared statements, which would make your code a tad bit more safe when it comes to SQL-Injections (which your code is very open for).
When a query fails, the mysql_error() global function will return the latest mysql error.
The easiest way to get information about a failing query is by adding or die(mysql_error()); after the query execution.
Example with your code:
$result = mysql_query($query) or die(mysql_error());
This will report your error and stop execute the script.
Your sql code is slightly wrong (as RST mentions), you are missing a comma between the values you are trying to set.
Using mysqli and prepared statements, your code could look something like:
// Using the mysqli object oriented style.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
// Prepare the statement.
$statement = $mysqli->prepare('UPDATE billdata SET Total=?, Due=? WHERE InvoiceNo=?');
// The question marks is placeholders for the input that will be added in a while.
// Bind your parameters (ssi tells mysqli what type of params it is, s = string, i = int).
$statement->bind_param('ssi', $total, $due, $invoceno);
// Execute the statement.
$statement->execute();
// Cleanup.
$statement->close();
$mysqli->close();
$query = "UPDATE billdata SET Total='$total', Due='$due' WHERE InvoiceNo=$invoiceno";
There should be a comma between the sets of values.
It is not a good idea to use the value from $_POST() as they are, better perform some validation checks.

Deprecated: mysql_query() [duplicate]

This question already has an answer here:
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead [duplicate]
(1 answer)
Closed 8 years ago.
i just update my server. it showing an error today
Deprecated: mysql_query(): The mysql extension is deprecated and will be removed in the >future: use mysqli or PDO instead in C:\wamp\www\work\db\dbfields - Copy.php on line 33
my dbfields - Copy.php page is
mysql_query("insert into user(name,address) values('$name','$address')");
i create 2 columns (name&address), need to insert the value of var($name& $address).
mysqli_query is now used instead of mysql_query. You can also use PDO::query or MySQLi::query. You can see the documentation here
Read : The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
It basically means mysql_query() can no longer be used. You will have to switch to using PDO.
For PDO, read: http://php.net/manual/en/book.pdo.php

Getting SQL statment sent to server after script finishes generating it with prepared statments

I'm trying to trouble shoot a problem with a prepared statement using mysqli in PHP. Is there a way to output the query that is actually sent to the server? For example if the WHERE clause to the query is determined from user input, is there a way to see the actual query generated containing the value from the WHERE clause after it's been sanitized? Let me know if the question isn't clear and I'll explain better.
So when mysqli_stmt_execute($finalQuery); callled, I want to see the query.
mysqli_info will return info on the last executed query.
http://php.net/manual/en/mysqli.info.php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
// Stuff to setup query...
$finalQuery = mysqli_prepare($link, $finalQuery);
mysqli_stmt_execute($finalQuery);
var_dump(mysqli_info($link));

Should I use mysqli_real_escape string() or mysql_real_escape_string() for form data? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
mysql_escape_string VS mysql_real_escape_string
I need to get company_name (given by user through a form) entered into my mysql database.
When I use
$company = mysqli_real_escape_string($_POST['company_name'])
I get an error
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in /opt/lampp/htdocs/Abacus-Version-2/admin/Company/insert_company.php on line 58
But everything seems to fine while using
$company = mysql_real_escape_string($_POST['company_name'])
What can I do in such cases?
The one to use depends on whether you are using the MySQLi extension or the MySQL extension
// procedural mysqli
$db = new mysqli;
$sql = sprintf("INSERT INTO table (id,name,email,comment) VALUES (NULL,'%s','%s','%s')",
mysqli_real_escape_string($db,$name),
mysqli_real_escape_string($db,$email),
mysqli_real_escape_string($db,$comment) );
// mysql
$conn = mysql_connect();
$sql = sprintf("INSERT INTO table (id,name,email,comment) VALUES (NULL,'%s','%s','%s')",
mysql_real_escape_string($name,$conn),
mysql_real_escape_string($email,$conn),
mysql_real_escape_string($comment,$conn) );
mysql_real_escape_string() is designed to make data safe for insertion into the database without errors. (IE such as escaping slashes so that it doesn't break your code).
You should use mysql_ or mysqli_ functions to match your connection string. "mysqli" is the object oriented implementation of the mysql set of functions, so the functions are called in the object oriented style. "mysql" is procedural. I'd suggest changing over to "mysqli" because I believe there has been talk of depreciating the "mysql" functions in future versions.
If you connection string is:
mysql_connect()
then use:
mysql_real_escape_string($_POST[''])
If it is:
$mysqli = new mysqli();
then use:
$mysqli->real_escape_string($_POST[''])
Definitely NO
Both functions has nothing to do with form data.
They have to be used to format string literals inserted into SQL query only.
This function belongs to the SQL query, not to whatever form. And even to very limited part of the query - a string literal.
So, every time you're going to insert into query a string literal (frankly, a portion of data enclosed in quotes), this function ought to be used unconditionally.
For the any other case it shouldn't be used at all.
As for the error you're getting - it's pretty self-explanatory: this function expects 2 parameters, not one. Just pass proper parameters as stated in the manual page for this function, and you'll be okay
It should be this if you use Procedural style:
$city = mysqli_real_escape_string($link, $city);
where link is the connection
or this when you use Object oriented style:
$city = $mysqli->real_escape_string($city);
Check out the php manual:
http://php.net/manual/en/mysqli.real-escape-string.php
Since all the MySQL extension is being deprecated, you'd best use the MySQLi methods instead, it's more future proof.
Both variants are fine* (Please look at my Update).
When you are using a mysql_connect then you should stick to mysql_real_escape_string() and also pass the connection handle.
When you are using a mysqli_connect then you should stick to mysqli_real_escape_string().
UPDATE
As pointed out by Jeffrey in the comments, using mysql_ functions is NOT fine. I agree to that. I was just pointing out, that you need to use the function that is used by the MySQL-extension you are using.
It came to me, that it was not the question, which MySQL-extension to use, but which function for escaping data.
If you ask me:
Use mysqli or PDO, because mysql is not recommendable and deprecated.
Pass the Connection Handle to the escape-function or better
use prepared Statements (PDO-Style)

Categories