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);
?>
Related
I am trying to display the number of rows in a table using mysqli_num_rows. When I print the results, it says I only have 1 row, when I really have several rows.
When I tested the SQL in phpMyAdmin, it counts the correct number of rows. But when I display the results on my web page, it counts only one row.
Please help me. What I am doing wrong?
$mysqli = new mysqli("localhost", "myusername", "mypass", "mydatabase");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT COUNT(*) FROM mytable")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
/* close result set */
$result->close();
}
/* close connection */
$mysqli->close();
The above codes prints the following, no matter how many rows I have:
Result set has 1 rows.
The result of a simple COUNT(*) statement is always one row. You want to fetch that row and get the value returned from the first column.
Actually when you use COUNT, the result of the query is the number of rows.
I usually try to write the sql query straight to phpmyadmin to see what happens. It would reveal the mistake ;)
<?php
$mysqli = new mysqli("localhost", "myusername", "mypass", "mydatabase");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql="SELECT * FROM mytable";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("Result set has %d rows.\n",$rowcount);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
Use mysqli_num_rows() method to fetch number of rows in the resultset.
Refer link http://php.net/manual/en/mysqli-result.num-rows.php
You could do like this if the database i small.
if ($result = $mysqli->query("SELECT * FROM mytable")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
/* close result set */
$result->close();
}
With i big database you could be doing like this as mentioned in the comments. I'm not so good with PDO or object oriented requests so this will be procedural.
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT COUNT(*) FROM users";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result)){
$row = mysqli_fetch_row($result);
printf("Result set has %d rows.\n", $row[0]);
}
mysqli_close($conn);
I just want to count the number of rows in a table that already created in a database using php. I used mysqli(). I need the number of rows in the table as the output.
<?php
$mysqli = new mysqli("hostname", "dbusername", "dbpassword", "dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT count(*) cc FROM tablename")) {
/* fetch the first row as result */
$row = $result->fetch_assoc();
printf("Result set has %d rows.\n", $row['cc']);
/* close result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
In fact it's a common question you can find the answer anywhere.
Like, http://php.net/manual/en/mysqli-result.num-rows.php
You could separate this problem in to two
I wanna know how to connect to mysql.
I wanna know how to write that sql instruction.
<?php
$mysqli = new mysqli("hostname", "dbusername", "dbpassword", "dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT columnName from tablename")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
/* close result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
EDIT:
$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];
Try simple query like:
SELECT COUNT(*) AS count
FROM mytable
If you dont want to use COUNT in SQL, you can just select all rows (SELECT id FROM table) and then just use PHP count().
also you simply do this
"SELECT COUNT(*) AS `Rows`, `any column` FROM `tablename` GROUP BY `any column` ORDER BY `any column` "
mysqli_num_rows should do the trick if you want to count the rows in php.
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"
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 the following PHP code:
$sql = new mysqli(/*connection info/db*/);
$query = $sql->$query("SELECT * from users WHERE /* rest of code */);
I was now wondering if there was any way I could retrieve the amount of rows that the above query found...
You should consider using PDO, it's safer and a more object oriented approach:
$database = new PDO(/*connection info/db*/);
$statement = $database->prepare('SELECT FROM fruit WHERE fruit_id = ? AND name = ?');
$statement->bindValue( 1, 'fruit_id_value' );
$statement->bindValue( 2, 'Banana' );
$statement->execute();
$count = $statement->rowCount(); # <-- The row count you are looking for!
--> visit http://php.net/manual/en/pdostatement.rowcount.php for more info
in Mysqli I know you can do
printf("Number of rows: %d.\n", $sql->num_rows);
Here is all the code
<?php
/* Open a connection */
$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 Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {
/* execute query */
$stmt->execute();
/* store result */
$stmt->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
I got that from this php manual http://php.net/manual/en/mysqli-stmt.num-rows.php
There is a modifier for the SELECT query that holds on to the information of the count you need: SQL_CALC_FOUND_ROWS
SELECT SQL_CALC_FOUND_ROWS * from users WHERE /* rest of code */
After running that query, you can run SELECT FOUND_ROWS(); to get the resulting number of rows.
If all you need is the count, you can just do
SELECT count(*) from users WHERE /* rest of code */