Update database with two array parameters - php

I´m trying to update my database with information that is send via a form.
My problem is that i don´t get how I can loop both arrays at the same. I have tried nesting foreach-loops with no success.
I then have this to work with
$display = $_POST["show"] ?? "";
$id = array_keys($_POST["show"]);
if ($action == "submit") {
foreach ($display as $key => $value) {
$stmt = $db->prepare("UPDATE picture SET display = ? WHERE id = ?");
$stmt->bindParam($display, $id)
$stmt->execute();
}
}

You can iterate over array and get keys and values at the same time:
$display = $_POST["show"] ?? [];
// Also you can check if `$display` is not empty
if ($action == "submit" && $display) {
// prepare statement ONCE
$stmt = $db->prepare("UPDATE picture SET display = ? WHERE id = ?");
foreach ($display as $key => $value) {
// execute statement as many times as you want with your params
$stmt->execute([$value, $key]);
}
}

If I saw correctly this is what you want:
<?php
try {
$display = isset($_POST['show']) ? $_POST['show'] : [];
if ($action === 'submit' && !empty($display)) {
$db->beginTransaction();
$stmt = $db->prepare('
UPDATE picture
SET display = :display
WHERE id = :id;
');
foreach ($display as $id => $show) {
$stmt->bindParam(':display', $show);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
}
$db->commit();
}
} catch(PDOException $e) {
echo $e->getMessage();
$db->rollBack();
}

Related

PDO UPDATE query deletes value(s) instead of updating

Can anyone see what is wrong with this script? I have verified that the data is in the $_POST array and the query-string is also formed correctly, but for some reason when this gets executed, the column(s) to be updated get emptied in the database..?
/* Get the ID for the house to be modified by using a hidden-field 'hiddenDescription' */
$stmt = $db->prepare('SELECT id FROM talot WHERE kuvaus = :description');
$stmt->bindParam(':description', $_POST['hiddenDescription'], PDO::PARAM_STR);
$stmt->execute();
if($row = $stmt->fetch(PDO::FETCH_ASSOC)){
// The column names in the database
$col_names = array("kaupunki", "osoite", "pintaAla", "koko", "vuosi", "hinta", "otsikko", "kuvaus", "valittaja");
$comma = ",";
$i = 0;
$unprepared = 'UPDATE talot SET ';
/* Go through the POST -array and add the column name and :$key (for binding) into the query string. Also add comma */
foreach($_POST as $key => $value){
if(!empty($_POST[$key])){
// Skip hiddenDescription
if($key != 'hiddenDescription'){
$unprepared .= "$col_names[$i] = :$key".$comma;
}
// If $key was hiddenDescription decrement $i;
else{
$i--;
}
}
$i++;
}
// chop the last comma.
$prepared = chop($unprepared, ',');
$prepared .= ' WHERE id = :id';
$stmt = $db->prepare($prepared);
$i = 0;
/* Go through the POST -array and bind values that are not empty. Again skip hiddenDescription. */
foreach($_POST as $key => $value){
if(!empty($value)){
if($key != 'hiddenDescription'){
$stmt->bindParam(":$key", $value, PDO::PARAM_STR);
}
else{
$i--;
}
}
$i++;
}
// Bind the ID received in the first database query.
$id = (int)$row['id'];
$stmt->bindParam(":id", $id, PDO::PARAM_INT);
$result = $stmt->execute();
if($result){
echo 1;
}
Thanks!
Alright.. Solved this hehe.
This:
foreach($_POST as $key => $value){
if(!empty($value)){
if($key != 'hiddenDescription'){
$stmt->bindParam(":$key", $value, PDO::PARAM_STR);
}
else{
$i--;
}
}
$i++;
}
Changed to this:
foreach($_POST as $key => &$value){
if(!empty($value)){
if($key != 'hiddenDescription'){
$stmt->bindParam(":$key", $value, PDO::PARAM_STR);
}
else{
$i--;
}
}
$i++;
}
(bindParam needs &$variable):

How to add mysqli_real_escape_string() to dynamic variables?

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$username= $_SESSION['username'];
require "connection.php";
// GET THE DATA FROM POST IF IT EXISTS
$data = isset($_POST['data']) ? $_POST['data'] : false;
// IF IT IS A VALID ARRAY THEN PROCESS IT
if (is_array($data)) {
// LOOP THOUGH EACH SUBMITTED RECORD
foreach($data as $id => $rec) {
// START AN UPDATE STRING
$updatestr = '';
// ADD FIELD / VALUES TO UPDATE STRING
foreach($rec as $fieldname => $value) {
if($fieldname == 'id'){
continue;
}
else{
$updatestr .= "`{$fieldname}` = '{$value}',";
}
}
// REMOVE THE TRAILING ,
trim($updatestr, ',');
$updatestr = rtrim($updatestr, ',');
// CREATE THE UPDATE QUERY USING THE ID OBTAINED FROM
// THE KEY OF THIS data ELEMENT
$query = "UPDATE `call` SET {$updatestr} WHERE id= '$id'";
// SEND IT TO THE DB
$result= mysqli_query($conn, $query);
}
echo "working";
}
else {
echo "not working";
}
?>
I have this code and it works perfectly, however I want to add
mysqli_real_escape_string But how can I do that to each variable since I don't know there exact information? I want it before it gets added to the query incase special characters were added
I also realized that my id never changes, it always stays one, whats the problem with that?
Granted I do not have access to PHP right now I believe this should work and get you on prepared statements.
<?php
foreach($data as $id => $rec) {
// START AN UPDATE STRING
$update_fields = array();
$bind_params_types = ''
$bind_params_values = array();
// ADD FIELD / VALUES TO UPDATE STRING
foreach($rec as $fieldname => $value) {
if($fieldname == 'id'){
continue;
}
else{
$update_fields[] = '{$fieldname} = ?';
$bind_params_types .= 's';
$bind_params_values[] = $value;
}
}
$update_fields = implode(',', $update_fields);
$bind_params_values = implode(',', $value);
// CREATE THE UPDATE QUERY USING THE ID OBTAINED FROM
// THE KEY OF THIS data ELEMENT
$query = "UPDATE `call` SET {$update_fields} WHERE id= '$id'";
if($stmt = mysqli_prepare($conn, $query)){
$stmt->bind_param($bind_params_types,$bind_params_values);
$stmt->execute();
} else {
echo "failed";
}
}
}
I've done addon in your code before updation i've esacpe the string
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$username= $_SESSION['username'];
require "connection.php";
// GET THE DATA FROM POST IF IT EXISTS
$data = isset($_POST['data']) ? $_POST['data'] : false;
// IF IT IS A VALID ARRAY THEN PROCESS IT
if (is_array($data)) {
// LOOP THOUGH EACH SUBMITTED RECORD
foreach($data as $id => $rec) {
// START AN UPDATE STRING
$updatestr = '';
// ADD FIELD / VALUES TO UPDATE STRING
foreach($rec as $fieldname => $value) {
if($fieldname == 'id'){
continue;
}
else{
$updatestr .= "`{$fieldname}` = '{$value}',";
}
}
// REMOVE THE TRAILING ,
trim($updatestr, ',');
$updatestr = rtrim($updatestr, ',');
$updatestr = mysqli_real_escape_string($conn, $updatestr);
// CREATE THE UPDATE QUERY USING THE ID OBTAINED FROM
// THE KEY OF THIS data ELEMENT
$query = "UPDATE `call` SET {$updatestr} WHERE id= '$id'";
// SEND IT TO THE DB
$result= mysqli_query($conn, $query);
}
echo "working";
}
else {
echo "not working";
}
?>

How to call multiple values from array in while loop in php

How to add multiple values in while loop, I can only add two values as per my level, one is id and other one is title, I want to add more fields like I am getting from the server please help anyone
$limitStart = $_POST['limitStart'];
$limitCount = 15;
if(isset($limitStart) || !empty($limitstart)) {
$con = mysqli_connect($hostname, $username, $password, $dbname);
$query = 'SELECT id, title, caption, description, featured_image, logo, category_sku, industry_sku
FROM works ORDER BY title limit '.$limitStart.','.$limitCount .'';
$result = mysqli_query($con, $query);
$res = array();
while ($resultSet = mysqli_fetch_assoc($result)) {
$res[$resultSet['id']] = $resultSet['featured_image'];
}
echo json_encode($res);
}
Maybe something like:
$res = array();
while ($resultSet = mysqli_fetch_assoc($result)) {
foreach($resultSet as $key => $value) {
$res[$key] = $value;
}
}
will do the trick?
Just add them all as the $resultSet is already an associative array:
while ($resultSet = mysqli_fetch_assoc($result)) {
$id = $resultSet['id'];
unset($resultSet['id']); // <-- add this is if you don't want the id in the final set as it's now the key.
$res[$id] = $resultSet;
}
Or to pick an choose certain fields, just do some basic PHP, add the additinonal fields as a new associative array.
Here's an example with adding caption and featured_image:
while ($resultSet = mysqli_fetch_assoc($result)) {
$res[$resultSet['id']] = ['featured_image'=>$resultSet['featured_image'],
'caption' => $resultSet['caption']];
}
If your $limitStart is 14 and your $limitCount is 15 it should return one id.
$limitStart = $_POST['limitStart']; // What is this number?
$limitCount = 15;
There is a typo in your if statement, see below.
Also your code is vulnerable for SQL-injection because you don't prepare your statements.
if( isset( $limitStart ) || !empty( $limitStart ) ) { // Typo here. (small s)
$mysqli = mysqli_connect($hostname, $username, $password, $dbname);
$sql = "SELECT id, title, caption, description, featured_image, logo, category_sku, industry_sku
FROM works ORDER BY title limit ".$limitStart.",".$limitCount."";
$stmt = $mysqli->prepare($sql); // Prepare the statement
$stmt->bind_param("ii", $limitStart, $limitCount); // Bind the parameters
$stmt->execute(); // Execute the query
// Bind the result
$stmt->bind_result($id, $title, $caption, $description, $featured_image, $logo, $category_sku, $industry_sku);
$result = $stmt->get_result();
$res = array();
while ($resultSet = $result->fetch_assoc()) {
$res[$resultSet['id']] = $id;
}
$stmt->close(); // Close the statement
$mysqli->close();
echo json_encode($res);
}

execute foreach loop in PDO query

I'm trying to store serialize form data into mysql using PDO. DB table column name, field name everything is dynamic.
update.php
$data = $_POST['data'];
parse_str($_POST['data'], $searcharray);
foreach($searcharray['column_name'] as $key=>$value) {
echo $value;
}
foreach($searcharray['data_name'] as $k=>$v) {
echo $v;
}
Here this below foreach loop returns colname_1colname_2colname_3 (without comma)
foreach($searcharray['column_name'] as $key=>$value) {
echo $value;
}
and another foreach loop returns biketvssuzuki (without comma)
foreach($searcharray['data_name'] as $k=>$v) {
echo $v;
}
I want to update bike in colname_1 and tvs in colname_2 and suzuki in colname_2. How do I execute those above two foreach loops in PDO query?
try
{
$update_query = $dbh->prepare("UPDATE ".REQUIREMENTS_DB." SET colname_1 = ?, colname_2 = ?, colname_3 = ? WHERE id = :id");
$update_query->bindParam(':id', $id);
$update_query->execute();
echo "Updated Successfully";
}
catch (PDOException $e)
{
die('Error ' . $e->getMessage());
}
Are you looking for something like this?
$sql = "UPDATE ".REQUIREMENTS_DB." SET ";
for ($i = 0; $i < count($searcharray['column_name']); $i++) {
$sql .= $searcharray['column_name'][$i]." = ".$searcharray['data_name'][$i];
if ($i < (count($searcharray['column_name'])-1)) $sql .= ", "
}
$sql .= "WHERE id = :id";
$update_query = $dbh->prepare($sql);
...
This is very basic code and could/should be improved a lot.

PHP MySQLi function get user data can't work

i am using This code for showing user data record but this code is not work on my side
I want to echo out specific user data. I created a function where I insert multiple arguments (each argument represents a column in the database) and then echo whichever column I want with a simple line of code.
Index.php
include('function.php');
$conn = new MySQLi(localhost, root, password, database);
$user_id = $_SESSION['login_user']; // like 1
$user = user_data($conn, $user_id, 'login', 'pass', 'nikename', 'email');
if(empty($user)){
echo 'error'; // always showing this error
}else{
echo $user['nickename'];
}
Always Showing echo 'error';
function user_data($conn, $user_id){
$data = array();
$user_id = (int)$user_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1) {
unset($func_get_args[0]);
unset($func_get_args[1]);
$valid = array('login', 'pass', 'nikename', 'email');
$fields = array();
foreach($func_get_args as $arg) {
if(in_array($arg, $valid)) $fields[] = $arg;
}
$fields = '`' . implode ('`, `', $fields) . '`';
if($stmt = $conn->prepare("SELECT $fields FROM `users` WHERE `user_id` = ?")) {
$stmt->bind_param('si', $fields, $user_id);
$stmt->execute();
//here I am trying to convert the result into an array
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
return $results;
$stmt->close();
}
}
}
Seeing and analyzing your code several times, I think the below will solve your issue.
Add this before your while/fetch loop
$row = array();
stmt_bind_assoc($stmt, $row);
so your code will look like this
$row = array();
stmt_bind_assoc($stmt, $row);
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
Also make sure you read the full documentation of bind_param on php.net here
Thanks and Best Regards
I guess, instead of
if($stmt = $conn->prepare("SELECT $fields FROM `users` WHERE `user_id` = ?")) {
$stmt->bind_param('si', $fields, $user_id);
you should go with
if($stmt = $conn->prepare("SELECT $fields FROM `users` WHERE `user_id` = ?")) {
$stmt->bind_param('i', $fields, $user_id);
Bind parameters. Types: s = string, i = integer, d = double, b = blob
As far as you have one argument with type INT you need to pass 'i' as a first parameters.
Try debugging over line by line in that function where you will get exact flaw by var_dump().

Categories