Combine the update and insert query in same statement in mysql - php

is it possible to combine the update and insert query in same statement apart from transactions and stored procedure.
For ex:At a time i want to update the records in table1 as well as insert the data in table2.

It is possible using
multi_query
You can fin more about it here
Something like this
$link = mysqli_connect("server", "user", "pass", "db");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$testquery .= "INSERT INTO x (`agent_name`, `job_number`, `job_value`, `points_value`) SELECT agent_name, job_number, job_value, points_value FROM jobs WHERE YEAR(booked_date) = $current_year && WEEKOFYEAR(booked_date) = $weeknum;";
$testquery .= "SELECT agent_name, SUM(job_value), SUM(points_value) FROM leaderboard GROUP BY agent_name ORDER BY SUM(points_value) DESC";
mysqli_multi_query($link, $testquery) or die("MySQL Error: " . mysqli_error($link) . "<hr>\nQuery: $testquery");

You can just type it and automatically mysqli will read it. like
#mysql_query("INSERT INTO x (`name`,`age`) VALUES ('me','21')");
#mysql_query("UPDATE y SET `status`='verified' WHERE `name`='me'");

Related

Getting last group_id from MySQL in PHP

I want to get last added group_id from MySQL to get new $group_id++ for other group.
I tried
$group_id = ("select max(group_id) from posts");
$group_id++;
But when I check it with echo
echo $group_id;
the result is : "select max(group_id) from posts"
You're assigning a query string to a variable..you're not even running the query...?
You need to run the query and assign it to a result ($group_id_)
There's other ways to do this but this is similar to what you're doing.
$result= mysqli_query($conn, "select max(group_id) as max from posts");
$row = $result->fetch_assoc($result);
$group_id = $row['max'];
$group_id++;
This is because you are not executing an SQL query, you are doing an assignment.
The correct syntax is something like this:
$result = mysqli_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
Search how you can execute SQL queries, and if you have trouble, post again.
Edit: Have a look on the link below
https://secure.php.net/manual/en/mysqli.query.php
This is the easiest way to implement it the latest one will have the highest ID so you order them by their id starting from the highest id to the lowest and you just take the first one.
Read about the http://php.net/manual/en/book.mysqli.php it explains everything about querying data from your database using php.
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($result = $mysqli->query("select group_id from posts ORDER BY group_id DESC LIMIT 1")){
// it has returned a result
$group_id = $result->fetch_object();
$group_id++;
}

how to combine query for multiple able to save data

can it be combine into 1 query?
this is the query that im trying to combine? or is there a better way to relate these to table?
$insert_row = $mysqli->query("INSERT INTO orderlist
(TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)
VALUES ('$transactionID','$itemname','$itemnumber', $ItemTotalPrice,'$itemqty')");
$insert_row1 = $mysqli->query("INSERT INTO order
(BuyerName,BuyerEmail,TransactionID)
VALUES ('$buyerName','$buyerEmail','$transactionID')");
when i run these both only one query is functional, so what im trying to do is to make them both works.
im open to any suggestion
The reason why your second query isn't working is because of the use of order and not escaping it; it is a MySQL reserved word:
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
Sidenote: ORDER is used when performing a SELECT... ORDER BY...
https://dev.mysql.com/doc/refman/5.0/en/select.html
Checking for errors would have shown you the syntax error such as:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax near 'order
http://php.net/manual/en/mysqli.error.php
Therefore, wrap it in ticks:
$insert_row1 = $mysqli->query("INSERT INTO `order` ...
or rename your table to something other than a reserved word, say orders for example.
If you wish to combine both queries, you can use multi_query()
http://php.net/manual/en/mysqli.quickstart.multiple-statement.php
Example from the manual:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
do {
if ($res = $mysqli->store_result()) {
var_dump($res->fetch_all(MYSQLI_ASSOC));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
?>
I also need to point out that your present code may be open to SQL injection since I do not know if you are escaping your data.
If not, then use prepared statements, or PDO with prepared statements, they're much safer.
try to add IF statement.
if ($insert_row = $mysqli->query("INSERT INTO orderlist(TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)VALUES ('$transactionID','$itemname','$itemnumber', $ItemTotalPrice,'$itemqty')"));
{
$insert_row1 = $mysqli->query("INSERT INTO order (BuyerName,BuyerEmail,TransactionID) VALUES ('$buyerName','$buyerEmail','$transactionID')");
}

# variable in mysqli statement

I'm now sitting for hours and trying to pass multiple queries through my PHP script.
Basically, I'd like to query for the last inserted index in the address folder, then save the index as a variable "#address", so that I can use it in the next query, etc.
The SQL script works fine, however, as soon as I use it in my PHP script, it doesn't insert any new data.
Also I don't want to split it into multiple single queries, because this script will be used in a web application, where a lot of new registrations will be processed and therefore it is important, that when two customer register at the same time, it is ensured that the foreign keys will be assigned in the right way.
Any suggestions are appreciated.
<?php
$link = mysqli_connect("localhost", "root", "test", "test");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = 'SET #address = (select max(idaddress) from test.address) + 1; SET #customer= (select max(idcustomer) from test.customer) + 1;
SET #contract= (select max(idcontact) from test.contract) + 1;
INSERT INTO `test`.`address` (`idaddress`, `street`, `number`, `zip`) VALUES (#address, "main street", "584", "54545");
INSERT INTO `test`.`customer` (`idcustomer`, `name`, `surname`, `customeraddress`) VALUES (#customer, "Smith", "Michael", #address);
INSERT INTO `test`.`contract` (`idcontract`, `customernumber`) VALUES (#contract, #costumer);
';
echo $query; // for testing purposes
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($link)) {
mysqli_free_result($result);
}
} while (mysqli_next_result($link));
}
mysqli_close($link);
?>
c0mplexity
Use this instead of yours.Hope it will work for you.
$query = "SET #address = (select max(idaddress) from test.address) + 1";
$query = "SET #customer= (select max(idcustomer) from test.customer) + 1";
$query = "SET #contract= (select max(idcontact) from test.contract) + 1";
$query = "INSERT INTO `test`.`address` (`idaddress`, `street`, `number`, `zip`) VALUES (#address, 'main street', "584", "54545")";
$query = "INSERT INTO `test`.`customer` (`idcustomer`, `name`, `surname`, `customeraddress`) VALUES (#customer, 'Smith', 'Michael', #address)";
$query = "INSERT INTO `test`.`contract` (`idcontract`, `customernumber`) VALUES (#contract, #costumer)";

PHP MySQL - Move record to another table, Select, Insert, Delete

I have two tables with the same structure. Iam attempting to move an entire record from one table to another and then delete from the source table. If i execute the two statements seperately it works, i.e. select and Insert 2. Delete.
How could I combine these two sql statments so that both statements are within one, and can be esxecuted one after another. Here is mysql statement so far, Its not executing
$q=" INSERT INTO archived (SELECT * FROM table1 WHERE id='$id') ;
DELETE FROM table1 WHERE id='$id'; ";
You can execute multiple SQL statements using one SQL statement string by seperating them by semi colon and passing the final statement to mysqli_multi_query() function.
$con = new mysqli('localhost', 'user', 'pass', 'demo');
// username is user , password is pass ,connecting to the demo database on the localhost host:
if($con->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = "INSERT INTO archived SELECT * FROM table1 WHERE id='$id';";
$sql .= "DELETE FROM table1 WHERE id='$id'; ";
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
else{
echo "Executed successfully";
}
You can do
function mysql_multiquery($queries,$conn)
{
$queries = explode(";", $queries);
foreach ($queries as $query)
$query = mysql_query(trim($query),$conn);
}
Call function
mysql_multiquery($sql,$conn);
If you are looking to send only one command from php, write a stored procedure with the two queries. Then your php command executes the procedure.

Can't insert into to my Database with PHP

I want to insert some info into a table but it doesn't works. This is the code.
<?php
$con=mysql_connect("localhost","Chew","*****","Birthdays");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Name="Something";
$Desc="Something";
$Lang="En";
$D="1";
$M="1";
echo "<br>";
$sql = "INSERT INTO `Birthdays` (Name, Description, Language, Day, Month) VALUES ('".$Name."', '".$Desc."', '".$Lang."', '".$D."', '".$M."' );";
$qr= mysql_query($con, $sql) or die("Error: " . mysql_error());
mysql_close($con);
?>
MONTH and DAY are names of MySQL functions. If you are going to name columns with those names you must escape them with ticks:
$sql = "INSERT INTO `Birthdays` (Name, Description, Language, `Day`, `Month`) VALUES ('".$Name."', '".$Desc."', '".$Lang."', '".$D."', '".$M."' );";
read mysql_query
$qr= mysql_query($sql, $con) or die("Error: " . mysql_error());
NB: mysql_* is deprecated, use mysqli_* or pdo
If D and M are numbers, your SQL should not use quotes (') in the VALUES-part of your SQL
You should be using Object Oriented mechanism for doing connection with MySQL with the help of MySQLi class
example
// The var's in complete caps means they might be defined as constant variable
// DB_HOST - database hostname
// DB_USER - database user
// DB_PASS - database password
// DB_NAME - database instance name
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($db -> connect_error){
// in case there are errors
die("Connect Error (" . $db -> connect_errno . ") " . $db -> connect_error);
}
$Name= mysql_real_escape_string("Something"); // helps to escape special characters like quotes
$Desc= mysql_real_escape_string("Something");
$Lang="En";
$D="1";
$M="1";
$sql = "INSERT INTO `Birthdays` (Name, Description, Language, `Day`, `Month`) VALUES ('".$Name."', '".$Desc."', '".$Lang."', $D, $M );";
$db -> query($sql) or die("Error: " . $db -> error_msg);
echo "Insert id: " . $db -> insert_id;
EDIT: Code to fetch data from database
C_Chewbacc,
I would recommend you on reading more on PHP-MySQL connection using Object Oriented mechanism
http://in2.php.net/mysqli
Try this code below
$sql = "SELECT * FROM Birthdays";
$result = $db -> query($sql); // SELECT query returns result object here
// We iterate over this result object and fetch each row on every iteration
// When the resultant object has nothing to return, NULL is initialised in $row
// When $row = NULL becomes the exit point of WHILE loop
while($row = $db -> fetch_array($result)){
var_dump($row); // This will display every row of data
}

Categories