inserting values from a loop - php

$sql1 = "SELECT SIDno FROM class WHERE SubjID='$SubjName' and SecID='$SecName'";
$result1 = mysql_query($sql1);
while ($row1 = mysql_fetch_assoc($result1)){
$IDno = $row1["SIDno"];
$sql2="INSERT INTO registered ( ServiceID, IDno, Stype)VALUES('$RecCode','$IDno','$Stype')";
}
this is my code. its working but it only insert one data into the database. How can make it away to insert all the possible data from the loop. Can anyone help me?

You’re probably executing the query after the loop so only the last record is being inserted.
Try to execute the insertion query at the end of the loop:
while ($row1 = mysql_fetch_assoc($result1)) {
$IDno = $row1["SIDno"];
$sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ('".mysql_real_escape_string($RecCode)."', '".mysql_real_escape_string($IDno)."', '".mysql_real_escape_string($Stype)."')";
mysql_query($sql2);
}
Or you first collect all data and then do one query to insert all records:
$values = array();
while ($row1 = mysql_fetch_assoc($result1)) {
$IDno = $row1["SIDno"];
$values[] = "('".mysql_real_escape_string($RecCode)."', '".mysql_real_escape_string($IDno)."', '".mysql_real_escape_string($Stype)."')";
}
if (!empty($values)) {
$sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ".implode(',', $values);
mysql_query($sql2);
}
But don’t forget to prepare the values for the query (see mysql_real_escape_string function).

If you are not planing to do anything with the fetched data, you could use INSERT .. SELECT .. statement.
Example:
INSERT INTO registered (ServiceID, IDno, Stype)
SELECT field1, field2, field3
FROM class
WHERE SubjID='$SubjName' and SecID='$SecName'"
And like written before me, escape your variables...

Note: make sure you're escaping your variables with mysql_real_escape_string.
$sql1 = "SELECT SIDno FROM class WHERE SubjID='$SubjName' and SecID='$SecName'";
$result1 = mysql_query($sql1);
$sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ";
$addComma = false;
while ($row1 = mysql_fetch_assoc($result1)){
$IDno = $row1["SIDno"];
$sql2 .= ($addComma ? ", " : "") . "('$RecCode','$IDno','$Stype')";
$addComma = true;
}

Change this line:
$sql2="INSERT INTO registered..."
to this:
$sql2 .= "INSERT INTO registered..."
inside the loop. You are accidentally overwriting the insert statement each time. If you use .= you will append the next statement to the previous one, creating a batch of insert scripts, one for each record.

Related

Need to execute a sql query with variables from a foreach loop

So I need to run my sql query in a foreach loop, but, say there are two variables in the foreach loop, the query only executes the iteration with the first variable twice, instead of executing both the first and the second variable.
My code
$sql = "SELECT * FROM users WHERE idUsers = '$selected';";
$result = mysqli_query($conn, $sql);
if($row = mysqli_fetch_assoc($result))
{
foreach($_POST['order-check'] as $check)
{
$sql2 = "UPDATE order_table SET order_status = 'Processing', assigned_vendor = '$selectedvendor' WHERE order_id = '$check';";
$result2 = mysqli_query($conn, $sql2);
exit();
}
}
else{
echo "failed";
exit();
}
Here, $selected is a POST variable from another page
As Qirel mentioned, remove the "exit()" from your foreach statement.
Also, please ensure you sanitize any POST or GET variables before inserting into the database :)
Your statement should look like this if you want to loop through all $_POST variables
foreach($_POST['order-check'] as $check)
{
$sql2 = "UPDATE order_table SET order_status = 'Processing', assigned_vendor = '$selectedvendor' WHERE order_id = '$check';";
$result2 = mysqli_query($conn, $sql2);
//exit();
}

how to select id from one table and insert into other table

$select = "SELECT MAX(order_id) FROM `order`";
mysql_query($select);
foreach ($_COOKIE['item'] as $key12 => $value) {
$value22 = explode("__", $value);
$query1 = "INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$value22[3]','$value22[4]')";
$result2 = mysql_query($query1);
The output of this is SELECT MAX(order_id) FROM order, so what is the solution of this selection and insertion of the id
$select="SELECT MAX(order_id) FROM `order`";
$row = mysqli_query($con,$select);
if(mysqli_num_rows($row)>0)
{
while($data = mysqli_fetch_assoc($row))
{
$order_id = $data['order_id'];
}
}
//This way you can fetch data
Then use this while inserting value for order_id in your query as in
$query1="INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$order_id','$value22[4]')";
one another way to find last inserted id from the db connection:
mysql_query('INSERT INTO order(a) VALUES('b'));
$id = mysql_insert_id();
then $id will be last inserted id
Recommendation:
Use only one batch INSERT query. It gives you the opportunity to insert multiple rows at once, e.g. by running only one query. And is a lot faster.
Used method:
Extract maximum of order_id from order and assign to $maxOrderId.
Iterate through cookie items and build corresponding rows
part of the INSERT sql statement. Then add it to the array $insertRowValues.
In the end implode the $insertRowValues array into the batch INSERT statement.
Run the batch INSERT query - only once.
<?php
$select = "SELECT MAX(order_id) FROM `order`";
$maxOrderId = mysql_query($select);
$insertRowValues = array();
foreach ($_COOKIE['item'] as $key12 => $value) {
$value22 = explode("__", $value);
$insertRowValues[] = "('', " . $value22[5] . ", '" . $maxOrderId . "', '" . $value22[3] . "', '" . $value22[4] . "')";
}
$query1 = "INSERT INTO `cart`
(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`)
VALUES " . implode(', ', $insertRowValues);
$result2 = mysql_query($query1);
Other recommendations:
Use mysqli or PDO instead of mysql, because mysql is already removed as of PHP 5.5.0 (see MySQL Library - Introduction);
Use exception handling;
Use prepared statements to avoid MySQL injection.
P.S: I couldn't test anything.
Good luck!

Is it possible to concatenate this INSERT query in and out of a if statment?

I'm having a few issues with this silly query, was wondering is it possible to concatenate the following INSERT query inside the IF statement and outside it as well to complete the rest of the query. So I want the $orderid to be insert within the if statement and the rest of the last 3 variables outside the IF
if(isset($_POST['Submit'])){
$orderid=mysql_insert_id();
$sql = mysql_query("SELECT * FROM course WHERE serial='$serial'") or die(mysql_error());
$fetch = mysql_fetch_assoc($sql);
$serial = $fetch['serial'];
$price = $fetch['price'];
mysql_query("INSERT into course_order_detail values ('$orderid','$serial','1','$price')") or die(mysql_error());
}
Oh and $orderid is from the previous insert query written in my code.
Try Like this
if(isset($_POST['Submit'])){
$orderid=mysql_insert_id();
$sql = mysql_query("SELECT * FROM course WHERE serial='$serial'") or die(mysql_error());
$fetch = mysql_fetch_assoc($sql);
$serial = $fetch['serial'];
$price = $fetch['price'];
$in = mysql_query("INSERT into course_order_detail values ('$orderid')") or die(mysql_error());
$new_id = mysql_insert_id();
}
$up = mysql_query("UPDATE course_order_detail SET serial='$serial',quantity='1',price='$price' WHERE orderid = ".$new_id);
You can use a nested insert with select
INSERT `into course_order_detail` SELECT '$orderid', serial, '1', price FROM course WHERE serial='$serial'
BTW sanitize your queries

Query does not work when i fetch data and insert it into a table

I am trying to insert to another table the results of a select statement from another table. The select statement works but the insert statement does not work. Please help me.
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
}
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
header("Location:homeclient.php");
?>
You asked for how to do these two as one query.
This is how:
$query = mysql_query("INSERT INTO `client` ( `client_csub_code`, `client_csub_name`, `client_csub_day`, `client_csub_time` ) SELECT `sub_code`, `sub_name`, `sub_day`, `sub_time` FROM `subject` WHERE `code` = '$enrol'");
// I would also add error checking
if ( mysql_errno() )
echo mysql_error();
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
}
header("Location:homeclient.php");
?>
Try changing to this. Currently your query is outside of your while, it will only run once and the values of $csubject etc are always going to be the last values of your fetched results.

PHP Variable in Select Statement

I've written this PHP-Script which is working, and now I want to change the row name into a variable to (not sure if row is correct), I mean the "name" from the select name...
I've tried nearly everything, but nothing gave me the right result.
I know that the normal thing how I can use variables in a statement like ("'. $var .'") won't work.
<?php
require_once 'config.php';
$id = $_GET["id"]; //ID OF THE CURRENT CONTACT
$user = $_GET["user"]; //ID OF THE CURRENT USERS
$query = mysql_query("SELECT name FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
$retval = mysql_fetch_object($query)->name;
$retval = trim($retval);
echo $retval;
?>
This is much easier isn't it?
$sql_insert =
"INSERT INTO customers (
`name`,
`address`,
`email`,
`phone`
)
VALUES (
'$name',
'$address',
'$email',
'$phone'
)";
Is it this you're looking for? Even your question in German isn't that clear to me :
$field = 'name';
$query = mysql_query("SELECT $field FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
$retval = mysql_fetch_object($query)->$field;
You can usi it something like this. Currently i assume you get only one row back and want to use only one field.
<?php
require_once 'config.php';
$id = $_GET["id"]; //ID DES DERZEITIGEN KONTAKTES
$user = $_GET["user"]; //ID DES DERZEITIGEN USERS
//Use variable inside closures `` and just in case escape it, depends how you get variable
$query = mysql_query("SELECT `".mysql_real_escape_string($variable)."` FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
if (!$query) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($query); //Retriev first row, with multiple rows use mysql_fetch_assoc
$retval = $row['0']; //Retriev first field
$retval = trim($retval);
echo $retval;
?>
Please post in English. Everyone else does.
Try using a different fetch method - fetch an associative array, then use the dynamic parameter to retrieve whatever column it is you need.
Have you considered using PDO?
I believe you are confusing matters (unintentionally) due to your use of the word 'row'. Judging by your example you mean field/column. It sounds like you wish to specify the fields to select using a variable which can be done by any of these methods...
$fields = "name, age";
$sql = "SELECT $fields FROM table";
$sql = "SELECT {$fields} FROM table";
$sql = "SELECT ".$fields." FROM table";
NB it is important that you have secure date in the $fields element, I would suggest using a whitelist of allowed values i.e.
// assuming $_POST['fields'] looks something like array('name','age','hack');
$allowed = array('name', 'age');
$fields = array();
foreach ($_POST['fields'] as $field) {
if (in_array($field, $allowed)) {
$fields[] = $field;
}
$fields = implode(', ', $fields);
Wouldn't this work?
$result = mysql_fetch_array($query);
echo trim($result['name']);
You should never put a variable into field list.
If want a variable field name, select *
and then use your variable to fetch particular field
<?php
require_once 'config.php';
$id = mysql_real_escape_string($_GET["id"]); //ID DES DERZEITIGEN KONTAKTES
$user = $_GET["user"]; //ID DES DERZEITIGEN USERS
$query = "SELECT * FROM contacts WHERE contact_id='$id' and user_id='1'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_array($result);
//and finally
$fieldname = "name";
$retval = $row[$fieldname];
echo $retval;
?>

Categories