how can i insert data into two table at a time? - php

I need to execte both querys, but insertion will happen on one table(first query only). If i put query9 first, it will execute, otherwise query3.
$query9 = $con->prepare("INSERT INTO complete_status (ID, hotel_id,
floor_id, room_id, pull_chrdsw_status, emergency_status, nurse_callsw_status, cmr_status, foodsw_status, bedside_cancelsw_status ,nurse_distress_status, bcssw_status ,final_status,date1, Time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)");
$query9->bind_param("iiiiiiiiiiiii", $ID, $HotelID ,$SectorID, $RoomID, $pull_chrdsw_status, $emergency_status, $nurse_callsw_status, $cmr_status, $foodsw_status,$bedside_cancelsw_status, $nurse_distress_status, $bcssw_status,$statuss);
if($value->NurseCallSwStats != $Uploadedpkt->RoomStatus[$key]->NurseCallSwStats)
{
if($DebugMode===TRUE)// Test mode with debugg outputs
{
echo "<br>";
echo "laundry change";
}
$Difference_Flag=TRUE;
$nurse_callsw_status = $Uploadedpkt->RoomStatus[$key]->NurseCallSwStats;
$query3->execute();
$query9->execute();
}
foreach ($Uploadedpkt->RoomStatus as $key => $value)
{
$nurse_callsw_status = $Uploadedpkt->RoomStatus[$key]->NurseCallSwStats;
$query3->execute();
$query9->execute();
}

you can create a stored procedure that contains all your queries and then execute it.

Related

How to change my PHP foreach looped SQL-Insert into a prepared-statement SQL loop?

I have a looped query to do inserts into the MySQL database it works perfectly to do what I need it to do as in it takes all the users inputs in array and then loops them and inputs each into their own row in the database.
$sql_insert_race_history = "INSERT INTO inf_race_history
(`inf_id`,`race_history`, `results`)
VALUES ";
if ($vracehistory != '') {
foreach ($vracehistory as $kay => $value) {
// $sql .= '' | $sql = $sql . '';
$sql_insert_race_history .= "('$inserted_id','{$value}','{$results[$kay]}'),";
}
} else {
$vracehistory = '';
}
// remove last `,` into query;
$sql_insert_race_history = rtrim($sql_insert_race_history, ',');
$countRow = count($_POST['racehist']);
//INSERT INTO THE DATABASE VIA QUERY
$results_racehistory = mysqli_query($vconn, $sql_insert_race_history);
This code works and inserts everything as i need it However i have been told that it is vulnerable to SQL injections attacks, so i have been trying to prevent that by using prepared statements every version I try only so far loops the dont work and it only uploads the very last item in the array
$stmtrace = $conn->prepare("INSERT INTO inf_race_history
(`inf_id`,`race_history`, `results`)
VALUES (?,?,?)");
if ($vracehistory != '') {
foreach ($vracehistory as $kay => $value) {
$stmtrace->bind_param("sss", $inserted_id,$value,$results[$kay]);
}
} else {
$vracehistory = '';
}
// remove last `,` into query;
$sql_insert_race_history = rtrim($stmtrace, ',');
$countRow = count($_POST['racehist']);
//INSERT INTO THE DATABASE VIA QUERY
$stmtrace->execute();
I think it may have something to do with changing it from .= in the foreach loop to just ->bind_param as maybe that is taking away the opportunity to loop it ? tho im not too sure and also how would i echo that i try to echo $stmtrace tho it says method _tostring is not implemented
foreach ($vracehistory as $kay => $value) {
$stmtrace->bind_param("sss", $inserted_id, $value, $results[$kay]);
$stmtrace->execute();
}
You should place execute() inside loop.
bind the params outside the foreach loop, and assign and execute the query when you assign the variables inside the foreach loop. For example
$stmtrace->bind_param("sss", $insertId, $insertValue, $insertKey);
foreach ($vracehistory as $kay => $value) {
$insertId = inserted_id;
$insertValue = $value;
$insertKey = $kay;
$stmtrace->execute();
}
Another note, if you bind an integer, the value of the bind_param method should be 'i'.

How to pass multiple variables in foreach php

I'd like to pass multiple variables in a foreach loop to add the value from $array_sma[] into my database. But so far I can only insert the value from $short_smas, while I'd also like to insert the values from $mid_smas. I have tried nested foreach but it's multiplying the values.
$period = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
$sma = array(6,9);
foreach ($sma as $range) {
$sum = array_sum(array_slice($period, 0, $range));
$result = array($range - 1 => $sum / $range);
for ($i = $range, $n = count($period); $i != $n; ++$i) {
$result[$i] = $result[$i - 1] + ($period[$i] - $period[$i - $range]) / $range;
}
$array_sma[] = $result;
}
list($short_smas,$mid_smas)=$array_sma;
foreach ($short_smas as $short_sma) {
$sql = "INSERT INTO sma (short_sma)
VALUES ('$short_sma') ";
if ($con->query($sql) === TRUE) {
echo "New record created successfully<br><br>";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
}
The code in my question works fine i.e. the value from the first sub array ($short_smas) of $array_sma[] gets inserted into the column short_sma of my msql database. The problem I have is when I try to insert the second sub array $mid_smas (see list()) from $array_sma[] in my second column of my database call mid_sma.
I think this is closed to what I want to achieve but still nothing gets inserted in the DB, source: php+mysql: insert a php array into mysql
I don't have any mysql syntax error.
$array_sma[] = $result;
$sql = "INSERT INTO sma (short_sma, mid_sma) VALUES ";
foreach ($array_sma as $item) {
$sql .= "('".$item[0]."','".$item[1]."'),";
}
$sql = rtrim($sql,",");
Main problem is that $short_smas and $mid_smas have different size. Moreover they are associative arrays so either you pick unique keys from both and will allow for empty values for keys that have only one value available or you pick only keys present in both arrays. Code below provides first solution.
// first lets pick unique keys from both arrays
$uniqe_keys = array_unique(array_merge(array_keys($short_smas), array_keys($mid_smas)));
// alternatively we can only pick those present in both
// $intersect_keys = array_intersect(array_keys($short_smas),array_keys($mid_smas));
// now lets build sql in loop as Marcelo Agimóvel sugested
// firs we need base command:
$sql = "INSERT INTO sma (short_sma, mid_sma) VALUES ";
// now we add value pairs to coma separated list of values to
// insert using keys from prepared keys array
foreach ($uniqe_keys as $key) {
$mid_sma = array_key_exists($key, $mid_smas)?$mid_smas[$key]:"";
$short_sma = array_key_exists($key, $short_smas)?$short_smas[$key]:"";
// here we build coma separated list of value pairs to insert
$sql .= "('$short_sma', '$mid_sma'),";
}
$sql = rtrim($sql, ",");
// with data provided in question $sql should have string:
// INSERT INTO sma (short_sma, mid_sma) VALUES, ('3.5', ''), ('4.5', ''), ('5.5', ''), ('6.5', '5'), ('7.5', '6'), ('8.5', '7'), ('9.5', '8'), ('10.5', '9'), ('11.5', '10'), ('12.5', '11')
// now we execute just one sql command
if ($con->query($sql) === TRUE) {
echo "New records created successfully<br><br>";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
// don't forget to close connection
Marcelo Agimóvel also suggested that instead of multiple inserts like this:
INSERT INTO tbl_name (a,b,c) VALUES (1,2,3);
its better to use single:
INSERT INTO tbl_name
(a,b,c)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
That's why I append value pairs to $sql in foreach loop and execute query outside loop.
Also its worth mentioning that instead of executing straight sql its better to use prepared statements as they are less prone to sql injection.

speed up execution by foreach loop in MySql command

I have a PHP foreach statement, looping through a large number of $icons.
For each icon, the DB-column sequence needs to be updated. As follows:
foreach ($icons as $key => $icon) {
// MySql pseudo-code:
UPDATE `tbl_icon2album`
SET `sequence`= $key +1
WHERE iconID= $icon['id']
}
My problem: this becomes very slow for a large number of icons.
My question: Can I speed this up by executing one MySql command that would somehow include the foreach loop?
Much obliged...
You could put all your updates in another table, and update using a single query, e.g.
UPDATE tbl_icon2album, some_other_table
SET sequence = some_other_table.new_key_value
WHERE iconID = some_other_table.icon_reference
How many keys are you updating? Is it the iteration that is slow, or are you doing this thousands of times?
You could use the "in" clause.
ie:
update table set key=key+1 where blah in ('1','2','3');
and you could iterate through the for loop to construct a variable passed to in:
ie:
$iconlist = "";
foreach ($icons as $key => $icon) {
if (!$iconlist) { $iconlist = "($icon" }
else
{ $iconlist .= ",$icon" }
}
if ($iconlist) {
$iconlist .= ")";
$query = "update table set key=key+1 where icon in $iconlist";
}
If you use prepared statements then you can prepare the query once, bind the parameters, and then execute within the loop. This could be faster as it is usually preparing the query that takes up time. For example:
$stmt = $mysqli->prepare("
UPDATE
`tbl_icon2album`
SET
`sequence` = ?
WHERE
`iconID` = ?
");
$stmt->bind_param('ii', $sequence, $icon_id);
foreach ($icons as $key => $icon)
{
$sequence = $key + 1;
$icon_id = $icon['id'];
$stmt->execute();
}

Insert array into MySQL

I am super confused and have been searching. But as the title suggests I am trying to enter an array.
My question is how do I get this array to import into the database? As of now with the current script, it only imports the first record and not the rest. Here also, I am able to import other values within the same array this is a JSON call by the way and its already being decoded.
foreach ($output as $key => $value) {
if (isset($output[$key]["stats"]["damage_given"]["vehicle"])) {
$damage_given[$key] = $output[$key]["stats"]["damage_given"]["vehicle"];
foreach ($damage_given[$key] as $vehicle_name) {
$vehicle_dmg_id = $vehicle_name['id'];
$vehicle_dmg_name = $vehicle_name['name'];
$vehicle_dmg_value = $vehicle_name['value'];
$vehicle_dmg_faction_nc = $vehicle_name['faction']['nc'];
$vehicle_dmg_faction_tr = $vehicle_name['faction']['tr'];
$vehicle_dmg_faction_vs = $vehicle_name['faction']['vs'];
}
}
}
$add_dmg_veh = "INSERT INTO damage_given(character_number, vehicle_id,
vehicle_name, total_value, vehicle_faction_nc, vehicle_faction_tr,
vehicle_faction_vs) VALUES ('$character_id[$key]', '$vehicle_dmg_id',
'$vehicle_dmg_name','$vehicle_dmg_value', '$vehicle_dmg_faction_nc',
'$vehicle_dmg_faction_tr','$vehicle_dmg_faction_vs')";
Although it is not recommended to store an array in a database, you could serialize() your array to store it in a database. Basically, PHP will convert the array into a specially crafted string, which it can later interpret.
Serialize to store it in the database, and unserialize it to work with it when you pull it out of the database
Note: I say serialization is not recommended, because your database is then not in First Normal Form, specifically because you are storing non-atomic values inside of a particular entry in the database. For this case, I would recommend creating a separate table which can store these values individually, and link the two tables together with a foreign key.
You should be looking about PDO_MySQL and your insert string is outside the loop and should be execute inside it.
You have to iterate through the array and insert every field of the array by it's own.
foreach($array as $value) {
// execute your insert statement here with $value
}
First of all you can't insert array in MySQL as you are doing .. Do as with iterating..
foreach ($output as $key => $value) {
if (isset($output[$key]["stats"]["damage_given"]["vehicle"])) {
$damage_given[$key] = $output[$key]["stats"]["damage_given"]["vehicle"];
foreach ($damage_given[$key] as $vehicle_name) {
$vehicle_dmg_id = $vehicle_name['id'];
$vehicle_dmg_name = $vehicle_name['name'];
$vehicle_dmg_value = $vehicle_name['value'];
$vehicle_dmg_faction_nc = $vehicle_name['faction']['nc'];
$vehicle_dmg_faction_tr = $vehicle_name['faction']['tr'];
$vehicle_dmg_faction_vs = $vehicle_name['faction']['vs'];
// if you wants to use insert query then do here.
$add_dmg_veh = "INSERT INTO damage_given(character_number, vehicle_id,
vehicle_name, total_value, vehicle_faction_nc, vehicle_faction_tr,
vehicle_faction_vs) VALUES ('$character_id[$key]', '$vehicle_dmg_id',
'$vehicle_dmg_name', '$vehicle_dmg_value', '$vehicle_dmg_faction_nc',
'$vehicle_dmg_faction_tr', '$vehicle_dmg_faction_vs')";
}
}
}
try building your insert data in an array and then implode the results into a single query:
<?php
foreach ($output as $key => $value) {
if (isset($output[$key]["stats"]["damage_given"]["vehicle"])) {
$damage_given[$key] = $output[$key]["stats"]["damage_given"]["vehicle"];
foreach ($damage_given[$key] as $vehicle_name) {
$sql[] = "
(
".$vehicle_name['id'].",
".$vehicle_name['name'].",
".$vehicle_name['value'].",
".$vehicle_name['faction']['nc'].",
".$vehicle_name['faction']['tr'].",
".$vehicle_name['faction']['vs']."
)";
}
}
}
$query = "
INSERT INTO damage_given
(
character_number,
vehicle_id,
vehicle_name,
total_value,
vehicle_faction_nc,
vehicle_faction_tr,
vehicle_faction_vs
)
VALUES
".implode(",",$sql)."
";
?>
here is what I got to fix the problem!
$stmt = $dbh->prepare(
"INSERT INTO kills_vehicle (character_number, veh_id, veh_name, veh_total, veh_faction_nc, veh_faction_tr, veh_faction_vs)
VALUES(:char_id, :id, :vehname, :total_value, :faction_nc, :faction_tr, :faction_vs)");
foreach ($output as $key => $value) {
if (isset($output[$key]["stats"]["play_time"]["vehicle"])) {
$character_id[$key] = $output[$key]["id"];
$score_hit_count[$key] = $output[$key]["stats"]["kills"]["vehicle"];
foreach ($score_hit_count[$key] as $row) {
$stmt->bindValue(':char_id', $character_id[$key]);
$stmt->bindValue(':id', $row[id]);
$stmt->bindValue(':vehname', $row[name]);
$stmt->bindValue(':total_value', $row[value]);
$stmt->bindValue(':faction_nc', $row[faction][nc]);
$stmt->bindValue(':faction_tr', $row[faction][tr]);
$stmt->bindValue(':faction_vs', $row[faction][vs]);
$stmt->execute();
}
}
}

How to insert data from database using oops php concepts?

I try to insert one person detail, it's inserted successfully. If i check in DB "same data insert 3 times". Why the data insert 3 times?
I had this data in the Database.
id name dob gen
1 James 12-03-1977 M
2 James 12-03-1977 M
3 James 12-03-1977 M
PHP class
class Detail
{
function savePerson_detail($vars){
foreach($vars as $key => $value){
if(is_numeric($key) && $value >0){
$qry = sprintf("INSERT INTO cca_student_list(per_name, per_dob, per_gen) VALUES('%s', '%s', '%s')",
mysql_real_escape_string($vars['name']),
mysql_real_escape_string($vars['dob']),
mysql_real_escape_string($vars['gen']));
mysql_query($qry) or die(mysql_error());
if($qry)
{
print 'Successfully Insert your details';
}
}
}
Html Page
<?php
$detail = new Detail();
if(isset($_POST['btnSaveDetail'])){
$detail->savePerson_detail($_POST);
}?>
You actually run the query three times, that is why you insert the data three times. Just run the query one time and you should be fine.
To do this you need to change your code: First sanitize the input data in full, then run the query. You are currently picking each element of $vars (which has three elements) and then you run the query each time.
Do one step after the other:
function savePerson_detail($vars)
{
// validate function input
foreach($vars as $key => $value)
{
if(!is_numeric($key) || !$value >0)
return;
}
// build sql query
$qry = sprintf(
"INSERT INTO cca_student_list(per_name, per_dob, per_gen) VALUES('%s', '%s', '%s')",
mysql_real_escape_string($vars['name']),
mysql_real_escape_string($vars['dob']),
mysql_real_escape_string($vars['gen'])
);
// run sql query
$result = mysql_query($qry) or die(mysql_error());
// check query result
if($result)
{
print 'Successfully Insert your details';
}
}
Because you used
foreach($vars as $key => $value){
When $vars or $_POST which was passed to it looks like this.
$_POST['name'] = 'James';
$_POST['dob'] = '12-03-1977';
$_POST['gen'] = 'M';
So it went through each of your $_POST items 3 times.
I think you can remove the validation and do it like this.
function savePerson_detail($vars){
$qry = sprintf("INSERT INTO cca_student_list(per_name, per_dob, per_gen) VALUES('%s', '%s', '%s')", mysql_real_escape_string($vars['name']), mysql_real_escape_string($vars['dob']), mysql_real_escape_string($vars['gen']));
mysql_query($qry) or die(mysql_error());
if($qry)
{ print 'Successfully Insert your details'; }
}
Unless I'm missing something, is this what you're trying to do?
class Detail
{
function savePerson_detail($vars) {
foreach($vars as $key => $value) {
$vars[$key] = mysql_real_escape_string($value);
}
if($qry)
{
print 'Successfully Insert your details';
}
$qry = sprintf("INSERT INTO cca_student_list(per_name, per_dob, per_gen) VALUES('%s', '%s', '%s')";
mysql_query($qry) or die(mysql_error());
}

Categories