I want to truncate a table via PHP. It has some foreign keys, so I use the little trick where I set my foreign key check to zero:
$query_truncate_extension = "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE extension; SET FOREIGN_KEY_CHECKS = 1;";
When I execute the script, the mysqli_error() gives me the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TRUNCATE TABLE extension; SET FOREIGN_KEY_CHECKS = 1' at line 1
So my table doesn't get truncated at all. But the weird thing is when I put this exact same query in the SQL-query section in phpmyadmin, it doesn't throw an error at all and my table is empty afterwards.
So my question is: why does this code gives an error in PHP, but not in phpmyadmin and how do I solve this?
Thanks in advance!
If you wan to run multiple queries in one call then you need to use
mysqli_multi_query()
This is a function allows to run one or multiple queries which are concatenated by a semicolon.
To retrieve the resultset from the first query you can use mysqli_use_result() or mysqli_store_result(). All subsequent query results can be processed using mysqli_more_results() and mysqli_next_result().
You can read more detail here.
http://php.net/manual/en/mysqli.multi-query.php
--------- Example Program at the link above -------------
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
You can change it according to your requirement.
Use single query in single call like
$query_truncate_extension = "SET FOREIGN_KEY_CHECKS = 0"
Related
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I need a little help again... I get error mysql parameters, I know the problem but I cant find the missing parameters... this is the problem line
**`$result_template = mysqli_query($select_template) or die(mysql_error());`**
I know 1 parameter is missing but I dont know whichone?? Can you pls help me? Thanks
This is part of the codes maybe usefull....
/*function to display the active template*/
function displayTemplate(){
$tableprefix = "";
global $tableprefix,$_SESSION;
$template_array = array();
$select_template = "SELECT vtop_filename,vleft_filename,vbottom_filename,vimages_folder,vcss_name,vtemplate_name
FROM ".$tableprefix."template_master WHERE vactive_status = 'Y'";
1579---->>>> $result_template = mysqli_query($select_template) or die(mysql_error());
$template_row = mysql_fetch_assoc($result_template);
array_push($template_array,$template_row['vtop_filename'],$template_row['vleft_filename'],$template_row['vbottom_filename'],$template_row['vimages_folder'],$template_row['vcss_name'],$template_row['vtemplate_name']);
return $template_array;
}
You need to tell it where to connect to. Here is a simple example of working code to connect to a database from PHP.
<php
//Connect to DB
$conn = new mysqli("Hostname","Username","Password","Database");
//If the connection has errors
if ($conn->connect_error){
//Display the error
die("Connection failed because: " . $conn->connect_error);
}
//Otherwise the connection is good so lets create a sql query
$sql = "SELECT * FROM Database";
//Get the results of the query
$result = $conn->query($sql);
You should refer the php documentation for this here
As you are using the procedural style, so you will have to pass the mysqli_connect resource to your mysqli_query
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Create table doesn't return a resultset */
if (mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
printf("Table myCity successfully created.\n");
}
/* Select queries return a resultset */
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* free result set */
mysqli_free_result($result);
}
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT)) {
/* Note, that we can't execute any functions which interact with the
server until result set was closed. All calls will return an
'out of sync' error */
if (!mysqli_query($link, "SET #a:='this will not work'")) {
printf("Error: %s\n", mysqli_error($link));
}
mysqli_free_result($result);
}
mysqli_close($link);
?>
but as I can see that you are using it in some function so pass an object of db to this function and then use it in your mysqli_query
I have a mysql database with restrict on delete setting.
I have this delete query:
if(isset($_POST['delete_id']))
{
$sqldelete="DELETE FROM tblAcqDetail WHERE ID=".$_POST['delete_id'];
$resultdelete = $conn->query($sqldelete);
}
How can I check if the query does delete anything or is restricted by mysql.
I need to run an update query (see below) only if the delete query works.
I tried:
if ($resultdelete->affected_rows> 0) {
// Escape user inputs for security
$status = mysqli_real_escape_string($link, $_POST['status']);
if(isset($_POST['status']))
{
$setsql="UPDATE tblInvoiceDetail SET TRANSFER = '0' WHERE ID='$status'";
$setresult = $conn->query($setsql);
}
}
I also tried
if ($resultdelete->num_rows > 0) {
And also :
if ($resultdelete) {
All of the above stop the update query from executing.
You can use mysqli_affected_rows().
From the docs:
Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query.
Note this is run on the connection object, not the result. So use $conn->affected_rows instead of $resultdelete->affected_rows.
Rather than passing $resultdelete in to mysqli_affected_rows you actually want to pass the DB link (returned by mysqli_connect) which will give you the number of rows affected by the previous query
$sqldelete="DELETE FROM tblAcqDetail WHERE ID=".$_POST['delete_id'];
$resultdelete = $conn->query($sqldelete);
if ($conn->affected_rows > 0) {// pass db link here
Read http://php.net/manual/en/mysqli.affected-rows.php
Your problem is you're referencing the wrong thing
if ($resultdelete->affected_rows> 0) {
But
$resultdelete = $conn->query($sqldelete);
only returns a boolean(emphasis mine).
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE
You want to reference the connection itself for how many rows were affected
if ($conn->affected_rows> 0) {
If condition should be
if ($conn->affected_rows> 0){}
not
if ($resultdelete->affected_rows> 0){}
You're using it wrong if ($resultdelete->affected_rows> 0) you're using num_rows() syntax with the >0 bit.
The connection is passed to the function and not from the result set.
RTM http://php.net/manual/en/mysqli.affected-rows.php
Object oriented style
int $mysqli->affected_rows;
Procedural style
int mysqli_affected_rows ( mysqli $link )
From the manual:
<?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();
}
/* Insert rows */
$mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", $mysqli->affected_rows);
$mysqli->query("ALTER TABLE Language ADD Status int default 0");
/* update rows */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows);
/* delete rows */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows);
/* select all rows */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows);
$result->close();
/* Delete table Language */
$mysqli->query("DROP TABLE Language");
/* close connection */
$mysqli->close();
?>
Procedural style
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
if (!$link) {
printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
exit();
}
/* Insert rows */
mysqli_query($link, "CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", mysqli_affected_rows($link));
mysqli_query($link, "ALTER TABLE Language ADD Status int default 0");
/* update rows */
mysqli_query($link, "UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link));
/* delete rows */
mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", mysqli_affected_rows($link));
/* select all rows */
$result = mysqli_query($link, "SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", mysqli_affected_rows($link));
mysqli_free_result($result);
/* Delete table Language */
mysqli_query($link, "DROP TABLE Language");
/* close connection */
mysqli_close($link);
?>
I'm running multiple UPDATE SQL queries as:
$queriesRun = mysqli_multi_query($connection, $queries);
Now, how do I loop through the results to know which queries succeeded and which failed? The PHP manual is giving me a headache with so many functions that can be used afterwards.
Thanks!
how do I loop through the results to know which queries succeeded and
which failed?
int mysqli_stmt_affected_rows ( mysqli_stmt $stmt )
and
bool mysqli_next_result ( mysqli $link ) are the 2 functions you're looking for.
<?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();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
From the documentation.
If you wan to use procedural style, check the example in the documentation. You just have to use mysqli_more_results or $mysqli->next_result() to switch between various queries.
Here is a procedural-style mysqli_multi_query solution built to take queries that do not return record sets. It displays each query statement, its affected rows, and a running count of total affected rows from $queries. In the event of an error, mysqli_multi_query() stops and the responsible error is displayed.
$single_queries=explode(';',$queries);
if(mysqli_multi_query($connection,$queries)){
do{
echo "<br>",array_shift($single_queries),"<br>";
$cumulative_rows+=$aff_rows=mysqli_affected_rows($connection);
echo "Affected Rows = $aff_rows, ";
echo "Cumulative Affected Rows = $cumulative_rows<br>";
} while(mysqli_more_results($connection) && mysqli_next_result($connection));
}
if($error_mess=mysqli_error($connection)){
echo "<br>",array_shift($single_queries),"<br>Error = $error_mess";
}
Outputs (assuming 5 rows exist in Test table where Column1=''):
UPDATE Test SET Column1='changed' WHERE Column1=''
Affected Rows = 5, Cumulative Affected Rows = 5
UPDATE Test SET Column1='changed again' WHERE Column1='changed'
Affected Rows = 5, Cumulative Affected Rows = 10
If you want better-identified queries, change $queries to an associated array where the key describes each query, then check out this similar post of mine:
How to identify the query that caused the error using mysqli_multi_query?
I have 2 sql queries to execute, but I want it to execute all or if error in one query then dont execute any. I'm using php. I used to use try and catch in .NET but I'm new to php.
Below is the code which i was trying to do:
function Registration($UserFirstname,$UserLastname){
$sql="INSERT INTO table1 (fieldname1,fieldname2) VALUES ('$UserFirstname','$UserLastname')";
$res=mysql_query($sql) or die(mysql_error());
$sql="INSERT INTO table2 (fieldname1,fieldname2) VALUES ('$UserFirstname','$UserLastname')";
$res=mysql_query($sql) or die(mysql_error());}
The problem you're probably facing with try...catch is that PHP has two different error handling mechanisms: error reporting and exceptions. You cannot catch exceptions unless the underlying code throws them and good old mysql_query() will trigger warnings rather than throwing exceptions. There're several workarounds but, if you are interested in writing good object-oriented code, I suggest you switch to PDO.
In any case, if you want to stick to good old MySQL library, your code should basically work:
$res=mysql_query($sql) or die(mysql_error());
The explanation:
mysql_query() returns FALSE if the query fails (e.g., you get a duplicate key)
The right side of the or expression will only execute if the left side is FALSE
die() aborts the script, thus preventing the next queries to be executed
However, I presume that you don't want to abort in the middle of nowhere. If we add some missing bits (such as proper SQL generation and code indentation) we get this:
function Registration($UserFirstname,$UserLastname){
$sql = sprintf("INSERT INTO table1 (fieldname1,fieldname2) VALUES ('%s','%s')";
mysql_real_escape_string($UserFirstname),
mysql_real_escape_string($UserLastname)
);
$res = mysql_query($sql);
if( !$res ){
return FALSE;
}
$sql = sprintf("INSERT INTO table2 (fieldname1,fieldname2) VALUES ('%s','%s')";
mysql_real_escape_string($UserFirstname),
mysql_real_escape_string($UserLastname)
);
$res = mysql_query($sql);
if( !$res ){
return FALSE;
}
return TRUE;
}
About transactions
Please note that you still need to use transactions if there's a chance that the second query fails. Transactions are not particularly difficult to use, the only requirements are:
Define the involved tables as InnoDB
Run a START TRANSACTION query on top of the function
Run a COMMIT query at the end of the function
You need to be using transactions. These allow you to wrap a set of queries in a block that says "Either all these queries execute successfully or none of them do". This means that no matter what happens in the transaction block, you can be sure that the integrity of your database has been maintained.
NOTE: Transactions don't work with MyISAM tables, you have to use InnoDB tables.
mysql_query ('BEGIN TRANSACTION;', $db);
mysql_query ("INSERT INTO sometable (some, columns) VALUES ($some, $values)", $db);
if ($errMsg = mysql_error ($db))
{
mysql_query ('ROLLBACK;', $db);
die ($errMsg);
}
mysql_query ("INSERT INTO someothertable (some, other, columns) VALUES ($some, $other, $values)", $db);
if ($errMsg = mysql_error ($db))
{
mysql_query ('ROLLBACK;', $db);
die ($errMsg);
}
mysql_query ('COMMIT', $db);
You can try to use mysqli_multi_query
Or you can change your DB schema to InnoDB..
For executing two queries as one, you have to use mysql extension, my below code works well
<?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();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
How do I separate statements in a single MYSQL query?
Is it a semicolon?
I don't think it matters but I am writing the statements to be invoked by PHP functions
Edit: the problem is that I didn't seem to understand the UPDATE syntax, that you can execute multiple fields with one UPDATE statement
Using the mysqli_ functions (docs), you can pass multiple queries in the same string using mysqli_multi_query (docs)
Example from the docs:
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= 'UPDATE City SET name = "Boston" WHERE id = 5';
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
If you're using one PHP call to get data from or send data to the database, it won't work. The MySQL PHP drivers support execution of a query string, not a script. If you want to execute multiple commands with one call, check out stored procedures.
http://dev.mysql.com/doc/refman/5.0/en/stored-routines.html
I think you're trying to do this?
<?php
$query = "SELECT name, subject, message FROM contact;select name from contact;";
$result = mysql_query($query);
?>
It won't work because PHP doesn't know what query you are looking to execute. You can do the following though, but most likely you knew that:
<?php
$query = "SELECT name, subject, message FROM contact";
$query2 = "SELECT name, message FROM contact;select name from contact;";
$result = mysql_query($query);
$result2 = mysql_query($query2);
?>
Hope this helps,
Jeffrey Kevin Pry