Update Multiple Rows at once MySQL - php

I have a table which includes a row for each day of the week.
Each row contains 2 input fields.
I am wanting to click one save button which will update all rows from the table into seperate MySQL rows.
I have the below code to insert new rows (which works fine) but wondering how this can be changed to an UPDATE statement?
$insertArr = array();
for ($i=0; $i<$cnt; $i++) {
$insertArr[] = "('"
. mysql_real_escape_string($_GET['Actual'][$i]) .
"', '"
. mysql_real_escape_string($_GET['Period'][$i]) .
"', '"
. mysql_real_escape_string($_GET['AddedBy'][$i]) .
"', '"
. mysql_real_escape_string($_GET['Date'][$i]) .
"', '"
. mysql_real_escape_string($_GET['Employee'][$i]) .
"', '"
. mysql_real_escape_string($_GET['Rotered'][$i]) . "')";
}
$query = "INSERT INTO hr_employee_rostered_hours (Actual, PeriodID, AddedBy, DateOfHours, EmployeeUniqueID, Rotered) VALUES " . implode(", ", $insertArr);
mysql_query($query) or trigger_error("Insert failed: " . mysql_error());
}

The mysql extension has been deprecated in PHP, and I strongly advice against using it.
Assuming that you're still getting the values that you want to update using the array,
Here is a link about PDO (not official docummentation) that helped me out when I first started with PHP and PDO
Here's an example using PDO
$updateq = "UPDATE hr_employee_rostered_hours SET (Actual = :actualvalue, PeriodID = :periodid, AddedBy = :addedby,DateOfHours = :dateofhrs, Rotered = :rotered ) WHERE EmployeeUniqueID = :employeeid";
$updatex = $dbh->prepare($updateq);
$updatex->bindValue(":actualvalue",$insertArr[0]);
$updatex->bindValue(":periodid",$insertArr[1]);
$updatex->bindValue(":addedby",$insertArr[2]);
$updatex->bindValue(":dateofhrs",$insertArr[3]);
$updatex->bindValue(":periodid",$insertArr[5]);
$updatex->bindValue(":employeeid",$insertArr[4]);
$updatex->execute();

You can use this code to update in MySQL.
for ($i = 0; $i < count($insertArr); $i++){
$var_to_update = implode(", ", $insertArr[$i]);
$actual = $var_to_update[0];
$periodID = $var_to_update[1];
$addedby = $var_to_update[2];
$dateofhour = $var_to_update[3];
$employeeUniqueID = $var_to_update[4];
$rotered = $var_to_update[5];
$query = "UPDATE hr_employee_rostered_hours SET (Actual = $actual , PeriodID = $periodID, AddedBy = $addedby, DateOfHours = $dateofhour, EmployeeUniqueID = $employeeUniqueID, Rotered = $rotered) WHERE EmployeeUniqueID = $employeeUniqueID";
$result = mysql_query($sql);
if ($result === FALSE)
{
die(mysql_error());
}
}

Related

Variable gets lost between two html post methods or php functions

I am quite new in php and trying to write my first scripts. I put values in a database. If a record has to be changed, the user can choose the id of the record that has to be changed. Some datas will remain, only read and some f.e. remarks can be changed. I have no problem with getting the datas from the database, but with storing the changed values.
User can choose the record to be changed:
public function bejelentesKivalasztas(){
$this->kapcsolodas();
$sqlHibabejelentesekTablabol = "SELECT bejelentesID FROM hibarogzites";
$this->hibabejelentesekTablabol = mysqli_query($this->kapcs, $sqlHibabejelentesekTablabol);
$sorokSzama = mysqli_num_rows($this->hibabejelentesekTablabol);
global $adat;
global $i;
$adat = [];
print("<select class='textarea' name='bejelentes_ID' id='bejelentes_ID' style='width: 220px'>");
for ($i=0; $i<$sorokSzama; $i++){
$adat[$i] = mysqli_fetch_array($this->hibabejelentesekTablabol);
print("<option value='" . $adat[$i]['bejelentesID'] . "'> " . $adat[$i]['bejelentesID'] . " </option>");
}
}
Necessary datas will be recalled and printed with the possibility to change some of them:
<?php
if(isset($_POST['bejelentesKivalasztas'])){
$bejelentesID = $_POST['bejelentes_ID'];
$boltCimBeolvasas = new adatlekerdezes($bejelentesID);
$boltCimBeolvasas ->boltCimBeolvasas($bejelentesID);
}
?>
public function boltCimBeolvasas(){
if(isset($_POST['bejelentesKivalasztas'])){
$bejelentesID = $_POST['bejelentes_ID'];
$this->kapcsolodas();
global $boltSzam, $boltVaros, $boltIrsz, $boltUtca, $bejelentesID;
$this->bejelentesID = $bejelentesID;
$this->egyBoltkivalasztas();
$sqlReadBoltAddressFromTable= "SELECT * FROM boltok WHERE boltID = '" . $this->boltID ."'";
$boltCimBeolvasas = mysqli_query($this->kapcs,$sqlReadBoltAddressFromTable);
$this->adat2 = mysqli_fetch_array($boltCimBeolvasas);
$this->boltSzam = $this->adat2[1];
$boltSzam = $this->boltSzam;
$boltIrsz = $this->adat2[2];
$boltVaros = $this->adat2[3];
$boltUtca = $this->adat2[4];
$this->bejelentesLehivas($this->bejelentesID);
$this->megjegyzesBeolvasas($this->bejelentesID);
}
}
public function megjegyzesBeolvasas(){
$this->kapcsolodas();
global $bejelMegjegyz;
$hibabejelentesekTablabol = [];
$this->sqlHibabejelentesekTablabol = "SELECT megjegyzesSzoveg FROM hibarogzites where bejelentesID = '" . $this->bejelentesID . "'";
$hibabejelentesekTablabol = mysqli_fetch_array(mysqli_query($this->kapcs, $this->sqlHibabejelentesekTablabol));
global $adat3;
$adat3 = [];
$this->adat3 = $hibabejelentesekTablabol;
$bejelMegjegyz = $this->adat3[0];
return $bejelMegjegyz;
}
But when restoring should follow, the ID (bejelentesID) gets lost and as this, data will not change.
public function bejelentesMod($intezkedes, $megjegyzes, $szerelo, $bejelentesID){
$this->kapcsolodas();
$sqlSzereloAdat = "SELECT *
FROM szerelo
WHERE szerelo_nev = '" . $szerelo . "'";
$szereloAdat = mysqli_fetch_array(mysqli_query($this->kapcs, $sqlSzereloAdat));
print("Szerelőadat: " . $szereloAdat['szereloID'] . " eddig / ");
$this->szereloID = $szereloAdat['szereloID'];
$this->intezkedesID = $intezkedes;
$this->bejelentesID = $bejelentesID;
print("intID: " . $this->intezkedesID);
print(" / bejelID: " . $this->bejelentesID);
$sqlHibabejelentesFrissites = "UPDATE hibarogzites SET megjegyzesSzoveg = '" . $megjegyzes . "', intezkedesID = '" . $this->intezkedesID . "', szereloID = '" . $this->szereloID . "', felhasznaloID = '" . $this->felhasznaloID . "' WHERE bejelentesID = '" . $this->bejelentesID . "'";
$hibabejelentesFrissites = mysqli_query($this->kapcs, $sqlHibabejelentesFrissites);
print(', $sqlhibabejelentesFrissítés értéke: ' . $sqlHibabejelentesFrissites);
if(!mysqli_connect_errno()){
$this->message = "A bejegyzés módosítva";
}
else{
$this->message = "A bejegyzés módosítása nem sikerült";
}
// header('Location: hibabejelentesek.php');
}
From that point that the id gets lost, the update cannot happen. I tried the mysql command at it worked in the sql programm directly. I inserted the
print("intID: " . $this->intezkedesID);
print(" / bejelID: " . $this->bejelentesID);
in function bejelentesMod to see what was the problem.
Maybe session can be the solution - but the id must be changed when another record must be changed. Can I use this session variable despite of that?
I suppose there are several problems with this code, but as I wrote - this is my first one. Even though I hope someone can me help how to get it work.
Thanks in advance for any help.

how to insert multiple record in databse using php

$link = mysqli_connect("localhost", "root", "", "jeetu") or die("Error " . mysqli_error($link));
if (isset($_POST['ok'])) {
$n = $_POST['name[]'];
$c = $_POST['contact[]'];
$a = $_POST['address[]'];
$count = count($n);
for ($i = 0; $i <= $count; $i++) {
print_r($n[$i]);
print_r($c[$i]);
print_r($a[$i]); die();
$query = "insert into add (name, contact, value) values ('" . $_POST['name[$i]'] . "'," . $_POST['contact[$i]'] . ",'" . $_POST['address[$i]'] . "')";
mysqli_query($link, "$query");
}
}
If you're using a form to input this data into a database there is no way your code will work since you're getting data from one form and not from many forms.
$count = count($n); will always return 1 because you are getting one name from the form. It only works if you're reading the data from the database.

Create and insert variables into mysql from for loop using php

I want to create an array or variables that can be inserted into the sql query instead of do it manually like in my code below.
Is this possible with the simple php, not using PDO, just some kind of trick that will solve this issue.
You can see that I manually inserted 10 columns and 10 values, can I do it shorter?
So, I want to have a variable/array that will consist pt1-pt10 and another that will be consisted of a[1]-a[10].
for($j=1;$j<11;$j++) {
$a[$j] = "";
}
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'my_db';
$table = 'jos_answers';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("INSERT into ".$table."(id, title, pt1, pt2, pt3, pt4, pt5, pt6, pt7, pt8, pt9, pt10) VALUES ((select id from jos_content where title='$title'),'$title','$a[1]','$a[2]','$a[3]','$a[4]','$a[5]','$a[6]','$a[7]','$a[8]','$a[9]','$a[10]')");
?>
for($j=1;$j<11;$j++) {
$a["pt".$j] = $j;
}
"INSERT into ".$table. "(id, title,".implode(",", array_keys(a)).") VALUES ((select id from jos_content where title='$title'),'$title',".implode(",", array_values(a)).")";
Try this:
$insert = "INSERT INTO" . $table . "(id, title,";
$value = " VALUES((select id from jos_content where title='$title'),'$title',";
for($x = 1; $x < 11; $x++){
$insert .= " pt" . $x . ",";
$value .= " '$a[" . $x . "]'," //this line is iffy....
}
$insert = substr($insert, 0, -1);//to remove last comma
$value = substr($value, 0, -1);//to remove last comma
$insert .= ")";//final paren
$value .= ")";//final paren
$sql = $insert . $value; //combine parts
$result = mysql_query($sql);
The reason I think that line is iffy is becuase the ' ' surronding the varibles kinda confuses me. Do you want the varibles value to be inserted to the DB? If so I would go with this line instead:
$values .= " " . $a[$x] . ",";
If you want the ' and the values go with this:
$values .= " '" . $a[$x] . "',";
Here is a working example of the code edited a bit obviously because it is not in your SQL environment and you did not give us all the variable values: http://viper-7.com/cDAcRl
Good Luck!

how to access fetch value from database using mysql and this value use in same form any were

use query for access the $current_rank this value want to access in different query but this value can not access any where in different query so how to access $current_rank......
$query = "select * from menu_master where menu_id =
$row_id and hotel_id='" . $_REQUEST['hotel_id'] . "'";
$result = mysql_query($query)."<br/>";
while($row=mysql_fetch_array($result))
{
$rank = $row['set_rank'];
}
$current_rank = $rank;
//echo $current_id = $row_id."<br/>";
//echo $new_rank =$_REQUEST['set_rank']."<br/>";
$sql = "select * from menu_master where set_rank = '$new_rank ' and hotel_id='".$_REQUEST['hotel_id']."'" ;
// echo $sql."<br/>";
$rs = mysql_query($sql)."<br/>";
while($row = mysql_fetch_array($rs))
{
$menu_id = $row['menu_id'];
$sql="update menu_master
set set_rank=$current_rank where menu_id= $menu_id and hotel_id='".$_REQUEST['hotel_id']."'";
//echo $sql."<br/>";
mysql_query($sql)."<br/>";
}
$sql="update menu_master set menu_name = '" . mysql_real_escape_string($_REQUEST['menu_name']) . "',
menu_name_ar = '" . mysql_real_escape_string($_REQUEST['menu_name_ar']) . "',
is_active = '" . $is_active . "',
set_rank = $new_rank where menu_id = '$current_id' and hotel_id='".$_REQUEST['hotel_id']."'";
//echo $sql."<br/>";
//exit;
mysql_query($sql);
Your current_rank seems to be an array. If you have single value in current_rank, then do not use while loop for it.
Just use $row=mysql_fetch_array($result);
$current_rank = $row['set_rank'];
Also you have commented out this line.
//echo $new_rank =$_REQUEST['set_rank']."";
So you have no value for $new_rank

How to save in multiple table when I click save button?

I need to save the values from my dynamic textbox in different tables at the same time. Can someone help me do this? I have 4 tables that needs to be filled. This is my tables and its fields:
table1
- desk_id
- desk_user
- desk_report
- desk_action
table2
- print_id
- print_brand
- print_model
- print_report
- print_action
table3
- tel_id
- tel_local
- tel_user
- tel_report
- tel_action
table4
- remarks_id
- remarks
My PHP code:
<?php
$con = mysql_connect ("localhost","root","nasi") or die
('cannot connect to database error: '.mysql_error());
if (isset($_POST['desk_user']) &&
isset($_POST['desk_report']) &&
isset($_POST['desk_action']) &&
isset($_POST['print_brand']) &&
isset($_POST['print_model']) &&
isset($_POST['print_report']) &&
isset($_POST['print_action']) &&
isset($_POST['tel_local']) &&
isset($_POST['tel_user']) &&
isset($_POST['tel_report']) &&
isset($_POST['tel_action']) &&
isset($_POST['remarks']))
{
$desk_user = $_POST['desk_user'];
$desk_report = $_POST['desk_report'];
$desk_action = $_POST['desk_action'];
$print_brand = $_POST['print_brand'];
$print_model = $_POST['print_model'];
$print_report = $_POST['print_report'];
$print_action = $_POST['print_action'];
$tel_local = $_POST['tel_local'];
$tel_user = $_POST['tel_user'];
$tel_report = $_POST['tel_report'];
$tel_action = $_POST['tel_action'];
$remarks = $_POST['remarks'];
if (!empty($desk_user)&& !empty($desk_report)&& !empty($desk_action) && !empty($print_brand) && !empty($print_model) && !empty($print_report) && !empty($print_action) && !empty($tel_local) && !empty($tel_user) && !empty($tel_report) && !empty($tel_action) && !empty($remarks)) {
mysql_select_db("csr", $con);
$queries = array();
for($i=0; $i<count($desk_user || $print_brand || $tel_local || $remarks); $i++)
{
$queries [] = "('" .$desk_user [$i ] . "', '" .$desk_report [$i ] . "', '" .$desk_action [$i ] . "')" ;
$queries1 [] = "( '" .$print_brand [$i ] . "', '" .$print_model [$i ] . "', '" .$print_report [$i ] . "', '" .$print_action [$i ] . "')" ;
$queries2 [] = "('" .$tel_local [$i ] . "', '" .$tel_user [$i ] . "', '" .$tel_report [$i ] . "', '" .$tel_action [$i ] . "')" ;
$queries3 [] = "('" .$remarks [$i ] . "')" ;
}
if(count($queries) == 0)
{
# Nothing passed
# exit
}
$query = "insert into desktoplaptop (desk_user, desk_report, desk_action tel_local) values " . implode(", ", $queries) ;
$query1 = "insert into printer (print_brand, print_model, print_report, print_action) values " . implode(", ", $queries1) ;
$query2 = "insert into tel (tel_user, tel_report, tel_action) values " . implode(", ", $queries2) ;
$query3 = "insert into remarks (remarks) values " . implode(", ", $queries3) ;
if ($sql_run = mysql_query($query) || $sql_run = mysql_query($query1) || $sql_run = mysql_query($query2) || $sql_run = mysql_query($query3)) {
echo 'ok.';
}
else {
echo '*Sorry, we couldn\'t register you at this time. Try again later.';
}
}
}
?>
If there are four tables, there needs to be a unique INSERT statement for each one. With the code you provided, you only name one table: desktoplaptop
If there actually are four unique tables as suggested by your list above, you will need to write a unique INSERT statement which refers to each table's schema.
For example:
$queries = array();
if(!empty($desk_user)) {
$queries[] = "INSERT into desktop (desk_user, desk_report, desk_action) VALUES ('" . $desk_user . "', '" .$desk_report . "', '" . $desk_action . "')'";
}
repeat for other 3 tables
foreach($queries as $query) {
if ($sql_run = mysql_query($query)) {
echo 'ok.';
} else {
echo '*Sorry, we couldn\'t register you at this time. Try again later.';
}
}
Note that if you are taking input from a web form, you will also want to mysql_escape_string() each $_POST variable to prevent injection. In addition, it seems you are using the count() function incorrectly-- you are passing it a Boolean expression when it expects an array. Overall I would suggest taking another look over exactly how your code operates.
Do four INSERT as a loop?
$query[0] = "INSERT INTO TABLE1 (...) VALUES (...)";
$query[1] = "INSERT INTO TABLE2 (...) VALUES (...)";
//etc...
foreach ($query as $x)
{
if ($sql_run = mysql_query($x)) {
echo 'ok.';
} else {
echo '*Sorry, we couldn\'t register you at this time. Try again later.';
}
}

Categories