multiple row update with php into mysql database - php

I am trying to update multiple rows here.However I fail to point the right ID of the row.
<?php
$table = 'DynamicPage';
$query = mysql_query(Query::SelectAllFrom($table));
// Count table rows
$count = mysql_num_rows($query);
while ($row = mysql_fetch_array($query)) {
$id[] = $row['ID'];
echo '
<h3>Column name: </h3><input type="text" name="name" maxlength="30" value="' . $row['Name'] . '" />
<h3>Tekst: </h3><textarea type="text" name="fulltext[]" maxlength="2000">' . $row['FullText'] . '</textarea>';
}
echo '<input name="Submit" type="submit" value="Submit" />
</form>';
// Check if button name "Submit" is active, do this
if (isset($_POST['Submit'])) {
for ($i = 0; $i < $count; $i++) {
$queryUP = mysql_query("UPDATE $table SET Name='" . $_POST['name'] . "' WHERE id='??????????????'");
$result = mysql_query($queryUP);
}
if ($result) {
header("location:index.php");
}
}
?>
So far I can update the first row (if id='1') from the last <h3>Column name: </h3><input type="text" name="name"... I know that I am not passing the ID's in the right way, but I have to idea about the syntax. If anyone has an idea, please let me know :)
Thanks

Perhaps you should add a hidden input field with IDs:
HTML part
<input type="hidden" name="id[]" value="'.$row['ID'].'" />
<h3>Column name: </h3><input type="text" name="name[]" maxlength="30" value="'.$row['Name'].'" />
<h3>Tekst: </h3><textarea name="fulltext[]" maxlength="2000">'.$row['FullText'].'</textarea>';
PHP
for($i=0; $i<count($_POST['ID']); ++$i){
//query goes here
}
SQL QUERY
UPDATE $table SET Name='{$_POST['name'][$i]}', Tekst='{$_POST['fulltext'][$i]}' WHERE id='{$_POST['id'][$i]}'
This is from top off my head, not tested, but should give you an idea.
And of course, escape all the input fields.

Try this after your $_POST['Submit'] isset test:
for($i=0;$i<sizeof($id);$i++) {
$queryUP = mysql_query("UPDATE $table SET Name='".$_POST['name']."' WHERE id = " . $id[$i]);
$result = mysql_query($queryUP);
}

input type="text" ids="id[]" maxlength="30" value="'.$row['id'].'"
//then submit part
for($i=0; $i<count($_POST['id'];$i++) {
$queryUP = mysql_query("UPDATE $table SET Name='".$_POST['name']."' WHERE id='$_POST['id'][$i]'");
$result = mysql_query($queryUP);
}

You may concatenate $row['ID'] and $row['Name'] to create a name you can parse later
<h3>Column name: </h3><input type="text" name="name" maxlength="30"
value="' . $row['ID'] . '_' . $row['Name'] . '" />
then you can use something like:
list($name, $id) = explode($_POST['name'], '_');
** also note you have a security risk using user input directly inside SQL statement

Related

foreach loop in a form with database table data, change the data and update the database in a wordpress plugin

I'm building a wordpress plugin for fun, and I want something crazy, I think.
make a form with a foreach loop with an entire database table.
change the data of the whole database table
update the database data of this table
I've got this until now, but I'm stuck when I want to update the records.
<form method="post">
<input type="hidden" name="form_hidden" value="Y">
<table>
<tbody>
<?php
global $wpdb;
$post_id = $wpdb->get_results("SELECT * FROM tbl_name ORDER BY id ASC");
foreach($post_id as $row){
echo '<tr><td>' . $row->id . '</td><td><input type="text" name="' . $row->name . '" value="' . $row->name . '" /></td></tr>';
}
?>
</tbody>
</table>
<input type="submit" name="Submit" value="Update Options" />
</form>
<?php
if($_POST['form_hidden'] == 'Y') {
//update database
global $wpdb;
foreach($_POST['name'] as $item){
$wpdb->replace( 'tbl_name', ); // <- some kind of array here
}
}
There are multiple issues, I guess.
wpdb::replace(...) replaces the columns of all rows with ONE value;
that is not what you want, correct?
To update the correct row in your table, you should refer to the corresponding primary key. I guess "id" in your case.
To store multiple values in your form as an "array", you have to use field names like "name[]".
Lets put it all together:
// in your form creation loop...
foreach($post_id as $row){
echo '<tr><td><input type="text" name="id[]" value="' . $row->id . '" /></td><td><input type="text" name="name[]" value="' . $row->name . '" /></td></tr>';
}
// processing the new values
foreach($_POST['id'] as $I => $id) {
$sql = $wpdb->prepare("UPDATE tbl_name SET name=%s where id=%d"
, $_POST['name'][$I]
, $id
);
$wpdb->query($sql);
}
These are only the interesting parts - just combine it with your existing code. See
Useful links:
https://developer.wordpress.org/reference/classes/wpdb/prepare/
https://developer.wordpress.org/reference/classes/wpdb/query/
https://www.php.net/manual/en/faq.html.php
Good luck!

sql - update only changed values in form to multiple tables

This question is relevant with this question here
Lets say I have fetched values from multiple tables to a form, and want to change one or more inputs ie. phone number or address.
So here is my select query:
SELECT c.*, u.username
FROM client c
JOIN users u ON u.id = c.credid
WHERE credid = :id
Considering the linked question (and answer) above, how could I make prepared update query for values that have CHANGED?
My tables are InnoDB.
EDIT: I need to put username to users table and all else to clients table. (clients table field credid is foreign key to users table primary key id)
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<?php
echo 'Username: <input type="text" name="1" value="' . $getuserinfo['username'] . '" /><br>';
echo 'Client: <input type="text" name="2" value="' . $getuserinfo['company'] . '" /><br>';
echo 'Address: <input type="text" name="3" value="' . $getuserinfo['address1'] . '" /><br>';
echo 'Address 2: <input type="text" name="4" value="' . $getuserinfo['address2'] . '" /><br>';
echo 'ZIP: <input type="text" name="5" value="' . $getuserinfo['zip'] . '" /><br>';
echo 'City: <input type="text" name="6" value="' . $getuserinfo['city'] . '" /><br>';
echo 'Country: <input type="text" name="7" value="' . $getuserinfo['country'] . '" /><br>';
echo 'E-mail: <input type="text" name="8" value="' . $getuserinfo['email'] . '" /><br>';
echo 'Phone number: <input type="text" name="9" value="' . $getuserinfo['phone'] . '" /><br>';
?>
<input type="submit" name="submit" value="Save " /><br>
</form>
EDIT:
I would like to construct the sql somewhat like this.
UPDATE c.(name, address, zip, email, phone, etc.),u.username
VALUES (:1, :2, :3, :etc)
FROM client c
JOIN users u ON u.id = c.credid
WHERE credid = :id
Is this anywhere near?
Or maybe something like this:
UPDATE users,client
SET users.username = :username,
client.value1 = :value1,
client.value2 = :value2,
etc...
WHERE client.credid=users.id
What you'll need to do to start with is rename you inputs to the name of the table columns e.g.
foreach ($getuserinfo as $key => $val) {
echo ucfist($key).': <input type="text" name="'.$key.'" value="' . $val . '" /><br>';
}
The above won't give you the exact labels but it's easy enough to add an if statement in to change that.
After you initially get the information add it to the session array to check if anything has changed
$_SESSION = $getuserinfo;
Then after the form is posted back (remember this doesn't contain any validtion apart from checking if the index already exists in the $_SESSION)
if ($_POST['username'] != $_SESSION['user_edit_info']['username']) {
//run validation and query to update username
}
$posted = $_POST;
unset($posted['username']);
$sql_array = array();
$params = array();
foreach ($posted as $key => $val) {
//This should prevent extra fields being posted
if (isset($_SESSION['user_edit_info'][$key]) && $_SESSION['user_edit_info'][$key] != $val) {
$sql_array[] = "$key=:$key";
$params[$key] = $val;
}
}
if (!empty($sql_array)) {
$params['id'] = $_SESSION['user_id']; //or whatever you set it to in your session
//I don't know exactly how you're running your PDOs but below should at least show
//what you need to do
('UPDATE client SET '.implode(',', $sql_array).' WHERE credid=:id', $params);
}
//finally you don't need this anymore so just unset it
unset($_SESSION['user_edit_info']);
Hope this helps!

edit row from mysql

Ok, I'm not very good at php but trying to learn as much as possible. So I've made website with admin panel. In admin panel I show all rows from database with 2 buttons - 'Delete' and 'Edit'. Delete button is working but I have trouble with Edit. So here is how I show results with the buttons
for ($i = $start; $i < $end; $i++)
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// echo out the contents of each row into a table
echo "<tr>";
echo '<td><p>' . mysql_result($result, $i, 'id') . '</p></td>';
echo '<td>' . mysql_result($result, $i, 'caption') . '</td>';
echo '<td>' . mysql_result($result, $i, 'name') . '</td>';
echo '<td>' . mysql_result($result, $i, 'alt') . '</td>';
echo '<td>' . mysql_result($result, $i, 'title') . '</td>';
echo '<td>Delete</td>';
echo '<td>Edit</td>';
echo "</tr>";
}
When I click on Edit page goes to edit.php and url is with ID of choosen image. For ex (/edit.php?id=68). Here is edit.php
<form action="" method="post" enctype="multipart/form-data">
Choose category
<select name="img_category">
<option value="1">Cars</option>
<option value="2">Animals</option>
<option value="3" >PC's</option>
<option value="4" >Sport</option>
</select><br/><br />
Caption
<input type="text" name="caption" /><br /><br />
Alt
<input type="text" name="alt" /><br /><br />
Title
<input type="text" name="title" /><br /><br />
<input type="submit" name="submit" id="submit" value="Edit" /><br /><br />
</form>
<?php
if (isset($_POST['submit']))
{
require_once("../include/db.php");
$id =$_POST['id'];
$caption = $_POST['caption'];
$title = $_POST['title'];
$query = "UPDATE images SET caption = '$caption', title = '$title' WHERE id = '$id'";
$result = mysqli_query($con, $query) or die("Error in query: ".mysqli_error($con));
}
?>
I want to be able to edit caption, alt and title of the image. Now when I press 'Edit' nothing happen. I'm sure is not so hard but for me is kind of.
In your sql-statement, you don't seem to add in your id.
$query = "UPDATE images SET caption = '$caption', title = '$title' WHERE id = 'id'";
You should add the $
$query = "UPDATE images SET caption = '$caption', title = '$title' WHERE id = '$id'";
Update:
There doesn't seem to be an ID field in your form. You try to retrieve it in POST, but there is no such field to retrieve data from. You should pass the id to the query through the form or an other way.
Update2:
As others have said, easiest way to do this is gonna be to get your ID from GET instead of POST.
Change your
$id =$_POST['id'];
to
$id =$_GET['id'];
use GET method to catch id from url
just change
$id =$_POST['id'];
to
$id =$_GET['id'];
You are trying to retrieve a $_GET value with a $_POST, which would leave the $id variable empty.
Change the $id =$_POST['id']; to $id = $_GET['id'];
Also change your query to
$query = "UPDATE images SET caption = '$caption', title = '$title' WHERE id = '$id'";
Add an
<input type="hidden" name="id" value='<?=(int)$_GET['id'] ?>'/>
somewhere in the form.
Have to add: there are a couple of security issues with your code. Remember your code is not production ready! But that is not your question so i wont go into that.
try this
<?php
if (isset($_POST['submit']))
{
require_once("../include/db.php");
$id =$_GET['id'];
$caption = $_POST['caption'];
$title = $_POST['title'];
$query = "UPDATE images SET caption = '$caption', title = '$title' WHERE id = '$id'";
$result = mysqli_query($con, $query) or die("Error in query: ".mysqli_error($con));
}
?>

PHP trouble using $_POST in a loop

edit - I solved my "add friend" button issue, now I'm trying to get the userid from the loop below. I want to be able to get the userid of the name that the user looks up (the name that gets submitted to findUsers function, $friend). So basically I want to be able to use result['userid'] and be able to submit that into a database.
I commented in the code where I'm having trouble getting the value for the userid to set.
<input type="hidden" name="userId" value="' . $result['userid'] . '" />
Is there a certain way to use hidden inputs, or is the value just not being set correctly?
<?php
include_once 'config.php';
class Friends{
function addFriend($userId) {
return $userId; //this is supposed to return the value of the user's id selected in the loop below via the if statements towards the bottom.
}
function findUsers($friend){
$search = mysql_query("SELECT * from users where username='$friend'");
if (mysql_num_rows($search) > 0){
// $this->addFriend($friend);
$userLocation = mysql_query("select * from userinfo where username='$friend'");
$locationResult = mysql_fetch_array($userLocation);
$locationResultArray = $locationResult['userlocation'];
$locationExplode = explode("~","$locationResultArray");
if (mysql_num_rows($search)) {
// Table column names
echo '<table><tr><td>Username</td><td>Location</td></tr>';
while($result = mysql_fetch_array($search)) {
echo '<tr>
<td>'. $result['username'] . '</td>
<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>
<td>
<form method="post" name="friendRequest" action="">
<input type="hidden" name="userId" value="' . $result['userid'] . '" />
<input type="submit" name="addFriend" value="Add Friend" />
</form>
</td></tr>';
}
}
}
}
}
$friends = new Friends();
if (isset($_POST['userId'], $_POST['addFriend'])) {
echo "friend button pressed"; //this message is displayed
if ($friends->addFriend($_POST['userId'])) {
echo "userID set"; //this message is displayed
echo $_POST['userID']; //this is not displayed
} else {
// some error code here
}
}
// Edit this to test here
// $friends->findUsers('<username>');
?>
That way to add friend is incorrect way, because when you click the "Add friend" button, that will send a $_POST['addFriend'] and then in the loop the check are going to add all users as friend.
The correct code is here:
<?php
function addFriend($userId){
// check is 'userId' exist, if not, then return 0;
}
if (isset($_POST['userId'], $_POST['addFriend'])) {
if (addFriend($_POST['userId'])) {
// some display code here
} else {
// some error code here
}
}
while($result = mysql_fetch_array($search)) {
?>
<tr><td>
<form method="post" name="friendRequest" action="">
<input type="hidden" name="userId" value="<?php echo $result['userid']; ?>" />
<input type="submit" name="addFriend" value="Add Friend" />
</form>
</td></tr>
<?php } ?>
EDIT1:
You can't use the code above into a function. I fixed a lot of bug that I can see in your code, but still look strange.
I don't get what you want to do with your code, but I made this:
<?php
function addFriend($userId) {
return 1; //using 1 for testing purposes
}
function findUsers($friend) {
$search = mysql_query('SELECT `userid`, `username`, `userlocation` FROM `users` JOIN `userinfo` ON `users`.`username` = `userinfo`.`username` WHERE `user`.`username` = ' . $friend);
if (mysql_num_rows($search)) {
// Table column names
echo '<table><tr><td>Username</td><td>Location</td></tr>';
while($result = mysql_fetch_array($search)) {
$locationExplode = explode('~', $result['userlocation']);
echo '<tr>
<td>'. $result['username'] . '</td>
<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>
<td>
<form method="post" name="friendRequest" action="">
<input type="hidden" name="userId" value="' . $result['userid'] . '" />
<input type="submit" name="addFriend" value="Add Friend" />
</form>
</td></tr>';
}
}
}
if (isset($_POST['userId'], $_POST['addFriend'])) {
if (addFriend($_POST['userId'])) {
echo "test"; //I'm simply trying to get the input to work, can't get it to post. Just using this for a test.
} else {
// some error code here
}
}
// Edit this to test here
// findUsers('<username>');
?>
EDIT2:
Well, you just need to put my functions code into the class and then use the other code outside the class, like this:
<?php
include_once 'config.php';
class Friends{
function addFriend($userId) {
return 1; //using 1 for testing purposes
}
function findUsers($friend) {
$search = mysql_query('SELECT `userid`, `username`, `userlocation` FROM `users` JOIN `userinfo` ON `users`.`username` = `userinfo`.`username` WHERE `user`.`username` = ' . $friend);
if (mysql_num_rows($search)) {
// Table column names
echo '<table><tr><td>Username</td><td>Location</td></tr>';
while($result = mysql_fetch_array($search)) {
$locationExplode = explode('~', $result['userlocation']);
echo '<tr>
<td>'. $result['username'] . '</td>
<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>
<td>
<form method="post" name="friendRequest" action="">
<input type="hidden" name="userId" value="' . $result['userid'] . '" />
<input type="submit" name="addFriend" value="Add Friend" />
</form>
</td></tr>';
}
}
}
}
$friends = new Friends();
if (isset($_POST['userId'], $_POST['addFriend'])) {
if ($friends->addFriend($_POST['userId'])) {
echo "test";
} else {
// some error code here
}
}
// Edit this to test here
// $friends->findUsers('<username>');
?>
EDIT3:
That's because the function addFriend is incorrect... You need to pass the user ID value as argument and then display it like this:
function addFriend($userId) {
return $userId; //this is supposed to return the value of the user's id selected in the loop below via the if statements towards the bottom.
}

Using PHP to posting mutiple HTML form fields

I am making an ordering form and all of the products' data are stored in a MySQL database.
There is a menu page with 10 items, each item has its own drop-down list for quantity (qty).
I am using PHP to generate HTML form elements (eg. input textfields) and display items.
Database has been redesigned: Table1= User_Orders, Table2= Product_Data
All code to display product information and to connect to MySQL, is
working correctly
My display code:
form action="process.php" method="POST" name="menu"
//PHP
$system = 'SELECT * FROM products ORDER BY id ASC';
if(!$result2=mysql_query($system)){
die('Error encountered. MySQL said: '.mysql_error());
}
while ($rows2 = mysql_fetch_array($result2))
{
$id=$rows2['id'];
$gitem=$rows2['item'];
$gdesc=$rows2['description'];
$menu='<input name="qty1" type="text" class="textfield" id="qty1" value="'. $gitem .'" size="25"/>
<textarea name="desc1" cols="10" rows="3" class="textfield" id="desc1" style="width: 222px; height: 51px;">'.$gdesc .'</textarea>';
echo $menu; }
//END PHP, restart HTML
</form >
My Submit Code
//PHP
$submit=$_POST['submit'];
$sitem=$_POST['qty1'];
$sdesc=$_POST['desc1'];
$sql = "UPDATE products SET item='$sitem' ,description='$sdesc' , WHERE `id`='".mysql_escape_string($id)."'";
if($submit) //submit button is pressed
{
mysql_query($sql);
}
Problem:
When I submit the form, only the newest/lastest row is updated (the one with the highest ID). The other fields are unaffected.
My idea to why it is happening:
I notice the textfields all share the same name's. This is because of the PHP generated HTML.
Question:
How do I make each textfield have its own unique name using generated PHP? (eg. qty1, qty2).
My Research
I thought about using an array: qty[]
Something like this:
How to get multiple selected values of select box in php?
http://www.shotdev.com/php/php-form/php-input-multiple-textbox/comment-page-1/#comment-42091
Please help me, I am stuck.
Lee
Either you can use name[] and get the parameters as an array in php
while ($rows2 = mysql_fetch_array($result2))
{
$id=$rows2['id'];
$gitem=$rows2['item'];
$gdesc=$rows2['description'];
$menu='<input name="qty[]" type="text" class="textfield" id="qty1" value="'. $gitem .'" size="25"/> <textarea name="desc[]" cols="10" rows="3" class="textfield" id="desc1" style="width: 222px; height: 51px;">'.$gdesc .'</textarea>';
echo $menu;
}
Or you can append a count to name.
$count = 1;
while ($rows2 = mysql_fetch_array($result2))
{
$id=$rows2['id'];
$gitem=$rows2['item'];
$gdesc=$rows2['description'];
$menu='<input name="qty' . $count . '" type="text" class="textfield" id="qty1" value="'. $gitem .'" size="25"/> <textarea name="desc' . $count . '" cols="10" rows="3" class="textfield" id="desc1" style="width: 222px; height: 51px;">'.$gdesc .'</textarea>';
echo $menu;
$count++;
}
Ok, first off, you're not passing the item id into the form so it knows what item to actually update.
Let me see what I can do here:
while ($rows2 = mysql_fetch_array($result2))
{
$id=$rows2['id'];
$gitem=$rows2['item'];
$gdesc=$rows2['description'];
$menu='<input name="qty[' . $id . ']" type="text" class="textfield" id="qty1" value="'. $gitem .'" size="25"/>
<textarea name="desc[' . $id . ']" cols="10" rows="3" class="textfield" id="desc1" style="width: 222px; height: 51px;">'.$gdesc .'</textarea>';
echo $menu;
}
This should return 2 arrays when submitted, qty and desc, with the keys of each entry equal to the id from the DB.
Then when checking the submission:
if($_POST['submit']) //Wanna check this first off, checks whether or not form has been submitted, don't want to do anything at all concerning processing the submission if the form hasn't been sumbitted, probably better to do if(isset($_POST['submit'])) rather than checking directly.
{
$qty = $_POST['qty']; //These two variable declarations assign the two form field arrays into easier to type/identify variable names, might want a little additional error checking to at least make sure that these are arrays with is_array() before going into the foreach loop.
$desc = $_POST['desc'];
//Loop through each entry from the form, UPDATE entries in database that correspond to array keys
foreach($qty as $key => $value) //Set up a loop on the $qty array from the form as array $key and $value and iterate through each entry in the array, the array keys should be the same item id from the DB that corresponds to both qty and desc value entries
{
$sitem = mysql_real_escape_string($value); //Escape $qty[$key] ($value) textfield input from form, put it in an easy to type variable. Note also, mysql_real_escape_string requires an active mysql connection to have been previously established elsewhere. mysql_escape_string() which you were using is depreciated, mysql_real_escape_string() is better.
$sdesc = mysql_real_escape_string($desc[$key]); //Escape $desc[$key] textarea input from form, put it in an easy to type variable. Since the keys should match, you can reach outside the foreach into $desc for it.
$id = mysql_real_escape_string($key); //Escape $key (id) from form, in case of malicious live html editing, might be best to cast to (int) instead like $id = (int)$key since id should always be an int.
$sql = "UPDATE `products` SET `item` = '$sitem', `description` = '$sdesc' WHERE `id` = $id LIMIT 1"; //Construct SQL query from escaped variables. Backticks around field and table names are pretty standard formal syntax. LIMIT 1 speeds up the query and reduces db server load because it will stop when it finds a matching WHERE condition rather than continuing to look for more, and there should only be a single matching id field, so no reason to continue to look for more.
mysql_query($sql); //Execute Query
}
}
Oh, here's the code for doing it with PDO for extra security:
if($_POST['submit']) //Wanna check this first off
{
$qty = $_POST['qty'];
$desc = $_POST['desc'];
$dsn="mysql:dbname=whateveryourdbisnamed;host=localhost"; //Of course change values to appropriate ones
$dbh = new PDO($dsn,"mysqlusername","mysqlpassword"); //Connect to DB. Might want some error checking to make sure it connected.
foreach($qty as $key => $value)
{
$sql = "UPDATE `products` SET `item` = :item, `description` = :desc WHERE `id` = :id LIMIT 1";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(":item",$value,PDO::PARAM_INT); //Note: Not sure if item is a number of not. If a string of any length, change it to next line
//$stmt->bindParam(":item",$value,PDO::PARAM_STR,128); //Note, change last parameter to set max length of string
$stmt->bindParam(":desc",$desc[$key],PDO::PARAM_STR,256); //Change last parameter to set max length of desc, or remove if no max length
$stmt->bindParam(":id",$key,PDO::PARAM_INT);
$stmt->execute(); //Execute query
}
}
Try...
$i = 0;
while ($rows2 = mysql_fetch_array($result2))
{
++$i;
$id=$rows2['id'];
$gitem=$rows2['item'];
$gdesc=$rows2['description'];
$menu='<input name="qty' . $i . '" type="text" class="textfield" id="qty' . $i . '" value="'. $gitem .'" size="25"/>
<textarea name="desc' . $i . '" cols="10" rows="3" class="textfield" id="desc' . $i . '" style="width: 222px; height: 51px;">'.$gdesc .'</textarea>';
echo $menu;
}

Categories