I am trying to update multiple rows in a database. I have the total number of rows in my table counted and bound to a variable:
$result = '32'
I then attempt to query each row:
for ($x = 0; $x <= $result; $x++)
{
if ($update = $db -> prepare("UPDATE substrates SET substrate_name = ?, substrate_desc = ?, substrate_base = ?, substrate_tax = ? WHERE substrate_id = ?"))
{
$substrate_name = $_POST['substrate_name'];
$substrate_desc = $_POST['substrate_desc'];
$substrate_base = $_POST['substrate_base'];
$substrate_tax = $_POST['substrate_tax'];
$substrate_id = $x;
$update -> bind_param('sssss', $substrate_name, $substrate_desc, $substrate_base, $substrate_tax, $substrate_id);
if ($update -> execute() == true) {
// Success stuff...
}
else {
// Error stuff...
}
$update -> close();
}
}
My problem is when I run this script, each row in the table is filled with the last row edited. For example:
AAA | Aaaaa | 1.00 | 6.35
BBB | Bbbbb | 2.00 | 6.35
CCC | Ccccc | 3.00 | 6.35
Becomes:
CCC | Ccccc | 3.00 | 6.35
CCC | Ccccc | 3.00 | 6.35
CCC | Ccccc | 3.00 | 6.35
How can I fix this script so it will update each row individually?
Try this:
for ($x = 0; $x <= $result; $x++)
{
if ($update = $db -> prepare("UPDATE substrates SET substrate_name = ?, substrate_desc = ?, substrate_base = ?, substrate_tax = ? WHERE substrate_id = ?"))
{
$substrate_name = $_POST['substrate_name'][$x];
$substrate_desc = $_POST['substrate_desc'][$x];
$substrate_base = $_POST['substrate_base'][$x];
$substrate_tax = $_POST['substrate_tax'][$x];
$substrate_id = $x;
$update -> bind_param('sssss', $substrate_name, $substrate_desc, $substrate_base, $substrate_tax, $substrate_id);
if ($update -> execute() == true) {
// Success stuff...
}
else {
// Error stuff...
}
$update -> close();
}
}
I changed the "name" fields in my form to include the substrate's ID:
<input name="substrate_name_'.$substrate_id.'" />
Then did the same for the update query (where the id is defined by the loop, $x):
$substrate_name = $_POST['substrate_name_'.$x];
$substrate_desc = $_POST['substrate_desc_'.$x];
$substrate_base = $_POST['substrate_base_'.$x];
$substrate_tax = $_POST['substrate_tax_'.$x];
$substrate_id = $x;
$update -> bind_param('sssss', $substrate_name, $substrate_desc, $substrate_base, $substrate_tax, $substrate_id);
And this gave me the desired result. Thanks to Rimon Khan for the idea and to everyone who commented.
Related
I have my 3 arrays which I put into these variables:
$title = $_REQUEST['test_bestellte_title'];
$anzahl = $_REQUEST['test_bestellte_anzahl'];
$groesse = $_REQUEST['test_bestellte_groesse'];
I want to insert this array of values into the sql table like
ID | Anzahl | title | groesse
-----------------------------------------
1 | 4 | Schulkind Shirt gelb | S
1 | 5 | Friends Shirt lila | M
1 | 3 | Shirt Sesamstraße | S
1 | 4 | Shirt Sesamstraße | L
But I have no clue how to insert it like shown above
I split them up with for each so far, that's where I'm stuck
foreach ($anzahl as $einzelanzahl) {
echo $einzelanzahl['test_bestellte_anzahl'];
}
foreach ($title as $einzeltitle) {
echo $einzelname['test_bestellte_groesse'];
}
foreach ($groesse as $einzelgroesse) {
echo $einzelgroesse['test_bestellte_artikel'];
}
Thanks in advance!
If all arrays with the same length:
$title = $_REQUEST['test_bestellte_title'];
$anzahl = $_REQUEST['test_bestellte_anzahl'];
$groesse = $_REQUEST['test_bestellte_groesse'];
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
// Check connection
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$stmt = $mysqli->prepare("INSERT INTO MyTable (`Anzahl`, `title`,
`groesse`) VALUES (?, ?, ?)");
for ($i = 0; $i < count($title); $i) {
// prepare and bind
$stmt->bind_param($title[$i], $anzahl[$i], $groesse[$i]);
$stmt->execute();
}
$stmt->close();
$mysqli->close();
Assuming the three arrays are always keyed identically, use a single loop:
$arrayOne = array('a', 'b', 'c', 'd');
$arrayTwo = array('w', 'x', 'y', 'z');
$arrayThree = array('m', 'n', 'o', 'p');
foreach ($arrayOne as $key => $valueOne) {
$valueTwo = $arrayTwo[$key];
$valueThree = $arrayThree[$key];
// save your table row to database...
echo "key: $key one: $valueOne two: $valueTwo three: $valueThree<br/>";
}
/* output:
key: 0 one: a two: w three: m
key: 1 one: b two: x three: n
key: 2 one: c two: y three: o
key: 3 one: d two: z three: p
*/
I mean you can use next peace of code:
<?php
$title = $_REQUEST['test_bestellte_title'];
$anzahl = $_REQUEST['test_bestellte_anzahl'];
$groesse = $_REQUEST['test_bestellte_groesse'];
$query = "INSERT INTO the_table (ID, Anzahl, title, groesse) VALUES (?, ?, ?, ?)";
$stmt = $pdo->prepare($query);
foreach ($title as $id=>$einzelanzahl) {
$stmt->execute([1, $title[$i], $anzahl[$i], $groesse[$i]]);
}
PHP PDO online
Im currently using the json_encode in converting array to strings
which outputs data in a straight pattern in my table
user
-----------
id | name
-------------------------------------------
1 |"name1","name2","name3","name4","name5"
But i want to have an output where the table data will look like this.
user
-----------
id | name
-----------
1 | name1
2 | name2
3 | name3
4 | name4
5 | name5
My PHP code
<?php
$connect = mysqli_connect("localhost", "root", "", "dbsample");
if(isset($_POST["check_val"])){
$check_val = htmlspecialchars(strip_tags("check_val"));
$number = json_encode($_POST["name"]);
for ($i = 0; $i < count($number); $i++) {
if ($number[$i] != "") {
$query = "INSERT INTO tbl_name(name) VALUES (?)";
$stmt = $connect->prepare($query);
$number[$i] = htmlspecialchars(strip_tags($number[$i]));
$stmt->bind_param("s", $number);
if($stmt->execute()) {
echo "SUCCESS";
# code...
}else
{
echo "ERROR";
}
}
else{
echo "Please Enter Name";
}
}
}
?>
I have a dynamic form which have dynamic input of textbox and variable of date,float and time.I want to insert those input dynamically into my sql table.
So here is the part of my code.I'm only able to loop through one variable,When i want to loop through the time and float,it face the conversion problem on float and time.(If any picture needed just let me know )
$ct = 0;
if ($_POST['Dates'] && $_POST['slct']) {
foreach ($_POST['Dates'] as $value) {
$values = $value;
$dates = $_POST['Dates']; // for leave date
$datess = $_POST['datess']; // for created date
$Area = $_COOKIE['cooAreaCode'];
$days = $_POST['slct'];
$time = date("h:i a", strtotime($frtime));
$times = date("h:i a", strtotime($totime));
$frtime = $_POST['frtime'];
$totime = $_POST['totime'];
$link_mssql = odbc_connect(DB_HSATTEND, DB_USER, DB_PASS);
$sql = "SELECT MAX(RefNo) as val from tblLeaveHeader";
$res = odbc_exec($link_mssql, $sql);
while (odbc_fetch_row($res)) {
$count = odbc_result($res, "val");
}
odbc_free_result($res);
$temp = sprintf('%08d', $count + 1);
if (empty($_POST['frtime']) && empty($_POST['totime'])) {
$sql3 = "INSERT INTO tblLeaveDetails (RefNo, LeaveType, Leavedd, Leaveday, LeaveFrmTime, LeaveToTime)
VALUES('$temp','$Leave','$values', '$days[$ct]', NULL, NULL)";
$res = odbc_exec($link_mssql, $sql3);
$ct++;
} else {
$sql2 = "INSERT INTO tblLeaveDetails (RefNo, LeaveType, Leavedd, Leaveday, LeaveFrmTime, LeaveToTime)
VALUES('$temp','$Leave','$values', '$days[$ct]', '$frtime[$ct]', '$totime[$ct]')";
$res = odbc_exec($link_mssql, $sql2);
$ct++;
}
}
}
Example of result in sql table
| ID | Refno | Leavetype | Leaveday | Leavdd |frtime|totime
| 1 | 00001 | Annual Leave | 1 | 2017-07-17 |3.00 | 7.00
| 2 | 00001 | Annual Leave | 1 | 2017-07-18 |4.00 | 6.00
I do have an array something like this:
[cuisines] => Array
(
[0] => 17
[1] => 20
[2] => 23
[3] => 26
)
Now I need to update mysql table with these values. All values belong to one user.
So I tried it like this:
if (isset($_POST['cuisines'])) {
$cuisines = $_POST['cuisines'];
} else {
$error_alert[] = "Please select at least one cuisine";
}
if (empty($error_alert)) { // If everything's OK...
// Make the update query:
$sql = 'UPDATE restaurant_cuisines
SET restaurant_id = ?
, cuisine_id = ?
WHERE restaurant_id = ?';
$stmt = $mysqli->prepare($sql);
// Bind the variables:
$stmt->bind_param('iii', $restaurant_id, $cuisine_id, $restaurant_id);
foreach ($cuisines as $value) {
$cuisine_id = $value;
// Execute the query:
$stmt->execute();
}
// Print a message based upon the result:
if ($stmt->affected_rows >= 1) {
echo 'updated';
}
// Close the statement:
$stmt->close();
unset($stmt);
}
But this query not updating mysql correctly. This is what I get running this script.
mysql> select * from restaurant_cuisines where restaurant_id = 4;
+---------------+------------+
| restaurant_id | cuisine_id |
+---------------+------------+
| 4 | 26 |
| 4 | 26 |
| 4 | 26 |
+---------------+------------+
3 rows in set (0.00 sec)
What would be the problem of this script?
Hope somebody may help me out.
Thank you.
You need to bind your parameters in the loop:
// Delete old entries:
$sqlDelete = 'DELETE FROM restaurant_cuisines WHERE restaurant_id = ?';
$stmtDelete = $mysqli->prepare($sqlDelete);
$stmtDelete->bind_param($restaurant_id);
$stmtDelete->execute();
$stmtDelete->close();
unset($stmtDelete);
// now prepare to insert new values
$sqlInsert = 'INSERT INTO restaurant_cuisines (restaurant_id,cuisine_id)
VALUES (?,?)';
$stmtInsert = $mysqli->prepare($sqlInsert);
foreach ($cuisines as $value) {
// Bind the variables:
$stmtInsert->bind_param($restaurant_id, $value);
// Execute the query:
$stmtInsert->execute();
// Print a message based upon the result:
if ($stmtInsert->affected_rows >= 1) {
echo 'updated';
}
}
// Close the statement:
$stmtInsert->close();
unset($stmtInsert);
I'm trying to fetch the result of a query to my database. I have no problems doing so when the resultset is just 1 row, but when it's multiple rows I only get the first one.
Here is my db:
-----keys-------------------
| id | key_nbr | date |
----------------------------
| 42 | abc123 | xxxx |
| 49 | 789xyz | wxyz |
----------------------------
My function:
function get_key_info($mysqli) {
if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
if ($stmt = $mysqli->query("SELECT id, key_nbr, date FROM keys WHERE id=$user_id")){
$row = $stmt->fetch_array(MYSQLI_ASSOC);
return $row;
}
}
return null;
}
Output when doing print_r($row); is only the first row:
Array ( [id] => 42 [key_nbr] => abc123 [date] => xxxx) How to make it print all rows?
You have to check for total number of rows before fetching the data, if it's not zero then execute the loop and fetch all records.
function get_key_info($mysqli) {
if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
if ($stmt = $mysqli->query("SELECT id, key_nbr, date FROM keys WHERE id=$user_id")){
if($stmt->num_rows != 0) {
$row = array();
while($r = $stmt->fetch_array(MYSQLI_ASSOC)) {
$row[] = $r;
}
return $row;
}
}
}
return null;
}