How to use msqli multi_query fuction inside a transaction - php

I will be running every midnight a cron job (php script) to copy all the records from one table to another and then delete them from the first one table.
Here is what I have for now:
<?php
include('conf/conn.php');
$result = mysqli_query($conn, "SHOW TABLES FROM mydb LIKE '%salon%'");
while($table = mysqli_fetch_array($result)) {
$tableToCopy = $table[0];
mysqli_begin_transaction($conn, MYSQLI_TRANS_START_READ_ONLY);
mysqli_query($conn, "INSERT INTO history SELECT * FROM $tableToCopy");
// Here is where I'm stuck
// $sql = "INSERT INTO history SELECT * FROM $tableToCopy; ";
// $sql.= "DELETE FROM $tableToCopy; ";
// if (!$mysqli->multi_query($sql)) {
// echo "Both executions failed: (" . $mysqli->errno . ") " . $mysqli->error;
// }
mysqli_commit($conn);
mysqli_close($conn);
if (!mysqli_commit($conn)) {
echo 'Failed.';
echo '<br>';
} else {
echo 'Successful';
echo '<br>';
}
}
?>
I can't find how to make more than one query inside a transaction. Can someone please guide me? Thanks in advance.

Related

New to MYSQL/PHP and need help rendering a MYSQL array output in to a PHP numbered list

Code posted below. I currently get the correct results as the code would call for below.
- Fred Jones. Walked to the store.
- Nancy Schmitt. Went to the airport.
- Tom Smith. Mowed the yard.
What i'm trying to do is get output like so. Sometimes there are multiple tasks. A list is generated every day so the number of tasks and customers may change.
1) Fred Jones. Walked to the store.
2) Nancy Schmitt. Went to the airport.
3) Tom Smith. Mowed the yard.
Is there any way to generate a "numbered list" of my output?
$sql = "SELECT * FROM tasks WHERE taskDate = curdate()";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$html .= " \n ". "- " . $row["customer"]. ". " . $row["task"]. " \n ";
}
// Free result set
mysqli_free_result($result);
} else{
echo "<p class='lead'><em>No records were found.</em></p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
Here is the code that ended up working for me. Thanks for the help community.
$sql = "SELECT * FROM tasks WHERE taskDate = curdate()";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
$i = 1;
while($row = mysqli_fetch_array($result)){
$html .= $i++ . ") " . $row["customer"]. ". " . $row["task"]. "." . "<br>";
}
// Free result set
mysqli_free_result($result);
} else{
echo "<p class='lead'><em>No records were found.</em></p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);

multi word values gives error in insert query

i am trying to insert a row in table using query->
INSERT INTO organizers(username, hotel, city, state, address, type, price1, price2, contact) VALUES ('nitin','moxvox','jodhpur','rajasthan','shastri circle','1','500','0','1000');
this query works fine. but when i try to give multi word values like username as 'nitin gehlot' instead of 'nitin': the query fails and returns the error part of response.
i am not much familiar with php: please help me.
php code->
$connect= mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$sqlq=$_GET['query'];
//test
if(mysqli_connect_errno()) {
die("data base connection failed: ".
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
$query = "$sqlq";
$result = mysqli_query($connect,$query);
if(!$result)
{
die("query is faild" . mysql_error);
}
if(strpos($query,'INSERT')!==false)
echo mysqli_insert_id($connect);
else{
echo ' {"result" : 1, "message" : [';$i=1;
while($row = mysqli_fetch_object($result))
{
if($i==1){$i=0;}
else echo',';
$j = json_encode($row);
echo $j;
}
echo ']}';
}
Thanks in advance.

Trying to delete specific row in a list of items from a MySQL database using PHP

I have a list of items that is being output via PHP / MySQL. I also have an Edit button and a Delete button in one column. I am trying to figure out how to delete a list item on a specific row by clicking the Delete button. I have tried the following:
$id = $_GET['id'];
if(isset($_POST["deletelist"])) {
$query = "SELECT * FROM lists";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 1) {
$query = "DELETE FROM lists WHERE id = '$id'";
} else {
echo "Cannot delete";
}
}
This of course does not work. Can anyone help me out with this?
UPDATE
This is the code for the entire page:
https://pastebin.com/raw/qjnZkUU2
UPDATED CODE
$id = $_GET['id'];
if(isset($_POST["deletelist"])) {
$query = "SELECT * FROM lists";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 1) {
$query = "DELETE FROM lists WHERE id = '$id'";
mysqli_query($db, $query);
} else {
echo "Cannot delete";
}
}
What I am confused about is how does the query know which item to delete? Should I be appending the ID to the URL to pass the ID?
UPDATE
Ok I think I get it....In the delete button, I need to echo the ID of that row so when the query runs from clicking the delete button, it knows which ID to delete correct?
RESOLVED
Alright. I got it figured out!
I have a button that references the ID of the list item:
echo "
I then pass that ID to deletelist.php
if (!isset($_GET['id'])) {
echo 'No ID was given...';
exit;
}
if ($db->connect_error) {
die('Connect Error (' . $con->connect_errno . ') ' . $con->connect_error);
}
$sql = "DELETE FROM lists WHERE id = ?";
if (!$result = $db->prepare($sql)) {
die('Query failed: (' . $db->errno . ') ' . $db->error);
}
Item gets deleted.
you have to execute query for any action in database
mysqli_query($db, $query);
so execute a delete query and then try it again
You have to execute the query. There is no query execution code. Try this
$id = $_GET['id'];
if(isset($_POST["deletelist"])) {
$query = "SELECT * FROM lists";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 1) {
$query = "DELETE FROM lists WHERE id = '$id'";
mysqli_query($db, $query);
} else {
echo "Cannot delete";
}
}
In order to delete a specific row what I needed to do was echo the ID within a link/button. This would then pass the ID to the needed PHP to delete the row from the database.
Echoing the row ID in the button
echo "
The PHP to delete the action row
<?php
include("db.php");
if (!isset($_GET['id'])) {
echo 'No ID was given...';
exit;
}
if ($db->connect_error) {
die('Connect Error (' . $con->connect_errno . ') ' . $con->connect_error);
}
$sql = "DELETE FROM lists WHERE id = ?";
if (!$result = $db->prepare($sql)) {
die('Query failed: (' . $db->errno . ') ' . $db->error);
}
if (!$result->bind_param('i', $_GET['id'])) {
die('Binding parameters failed: (' . $result->errno . ') ' . $result->error);
}
if (!$result->execute()) {
die('Execute failed: (' . $result->errno . ') ' . $result->error);
}
if ($result->affected_rows > 0) {
echo "The ID was deleted with success.";
} else {
echo "Couldn't delete the ID."; }
$result->close();
$db->close();
header('Location: ../account.php');
?>
This deletes the item row and then returns the user to account.php. Which in this case, the page never really changes.
Try like below
if(isset($_POST["deletelist"]) && isset($_GET['id']) ) {
$id = $_GET['id'];
$query = "SELECT * FROM lists";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 1) {
$query = "DELETE FROM lists WHERE id = '".mysqli_real_escape_string($db,$id)."'";
mysqli_query($db, $query);
} else {
echo "Cannot delete";
}
}

php mysql issue with printing value on html page

I'm trying to query MySQL DB and print a single result on the page using PHP.
It's always going to be a single result, so I'm not sure if I need to loop
In any case, would anyone mind advising why the below doesn't work?
Thank you!!
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else {
echo "success";
}
$sql = "SELECT sum(Discounted_Value) as id FROM Orders WHERE Year = 2017";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Total 2017 " $row["id"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
If there will be only one result you can simplify code to:
$sql = "SELECT sum(Discounted_Value) as id FROM Orders WHERE Year = 2017";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo "Total 2017 " . $row["id"] . "<br>"; // Don't forget dots for concatenation

PHP move information between SQL Tables

I am trying to move information from Table A to Table B with the following code. in the same time I want to delete the row in table B once information is moved to table A
//Move from table A to table B
$sql = "insert into del_ussd_members SELECT * FROM members WHERE
member_id='$member_id'";
if (mysql_query($sql, $con)) {
$insertSuccessful = true;
} else {
echo $sql;
print_r($_POST);
echo "\n" . mysql_error($con); echo "mysql err no : " .
mysql_errno($con);
}
//Delete from members
$sql2 = "DELETE FROM members WHERE member_id='$member_id'";
if (mysql_query($sql1, $con)) {
$insertSuccessful = true;
} else {
echo $sql1;
echo "\n" . mysql_error($con);
echo "mysql err no : " . mysql_errno($con);
}
The move is happening no problem but the delete function gives me the following error
Query was emptymysql err no : 1065
Even if I run the string on its own I get the same error
Replace
if (mysql_query($sql1, $con)) { //because $sql1 doesn't exist as per your code.
with
if (mysql_query($sql2, $con)) {
You should first change mysql_* functions to mysqli or PDO. Because the whole mysql_* functions will be deprecated in the coming versions.
There is no $sql1 variable in your code so you can't use it. You probably wanted to use $sql2.
Also, think about moving to PDO or mysqli_*, because mysql_* is deprecated and will be removed from PHP.
Next thing is that your first query is incorrect. Split it to two separated queries.
you need to change $sql1 to $sql2 in second query.
//Delete from members
$sql2 = "DELETE FROM members WHERE member_id='$member_id'";
if (mysql_query($sql2, $con)) {
Copy Paste:
//Move from table A to table B
$sql = "insert into del_ussd_members SELECT * FROM members WHERE
member_id='$member_id'";
if (mysql_query($sql, $con)) {
$insertSuccessful = true;
} else {
echo $sql;
print_r($_POST);
echo "\n" . mysql_error($con); echo "mysql err no : " .
mysql_errno($con);
}
//Delete from members
$sql2 = "DELETE FROM members WHERE member_id='$member_id'";
if (mysql_query($sql2, $con)) {
$insertSuccessful = true;
} else {
echo $sql2;
echo "\n" . mysql_error($con);
echo "mysql err no : " . mysql_errno($con);
}

Categories