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!
Related
I have a form with multiple checkboxes and hidden inputs, which I'm passing to a second page using GET.
I'm then trying to retrieve the value of each checkbox and the input in a loop and echo out the combined value.
HTML:
<form action="criteria.php" method="GET">
<input name="id[]" type="hidden" value="<? echo $criteria_id; ?>" />
<input type="checkbox" name="checked[]" class="checkbox-md" id="<? echo $criteria_id; ?>" value="Y">
<button type="submit" class="btn btn-lilac" role="button">Complete</button>
</form>
PHP:
$criteria_id = $_GET['id']; //get all criteria id
$criteria_checked = $_GET['checked']; //get checked criteria id
foreach($criteria_id as $id) //get id of all checkboxes {
echo "<BR>Criteria = ".$id."Checked = ".$criteria_checked; //returns id + array?
if ($checked='Y')//check if checked {
echo "<BR>Criteria =".$id." Checked = Y";
} else {
echo "<BR>Criteria =".$id." Checked = N";
}
}
You will need to make sure that the inputs have matching array keys:
<input name="id[0]" type="hidden" . . .
<input name="checked[0]" type="checkbox" . . .
<input name="id[1]" type="hidden" . . .
<input name="checked[1]" type="checkbox" . . .
Depending on how you create these you could use the $criteria_id:
<input name="id[<? echo $criteria_id; ?>]" type="hidden" . . .
<input name="checked[<? echo $criteria_id; ?>]" type="checkbox" . . .
This way the id and checked array keys will match. All hidden inputs will be passed from the form but only the checked checkboxes, so check if the key of the id is set in the checked array:
foreach($_GET['id'] as $key => $id) {
if (isset($_GET['checked'][$key])) {
echo "<BR>Criteria =".$id." Checked = Y";
} else {
echo "<BR>Criteria =".$id." Checked = N";
}
}
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!
I have displayed check box values(ugroup field) from group table.now what i want to do is,when user select multiple check boxes and submit it should be insert into relavent column in one row.now it's insert check boxes values.but not in relevant column .this is my code.Please help me.
//select ugroup's from group table.
<?php
$result = "SELECT id,ugroup FROM group";
$res_result = db::getInstance()->query($result);
?>
<form action="db_sql/db_add_page.php" method="get">
Tittle :<input type="text" size="100" name="tittle" />
Description :<textarea cols="80" id="editor1" name="description" rows="10"></textarea>
//Display ugroups in textboxes and checkboxes
<?php
while( $line=$res_result->fetch(PDO::FETCH_ASSOC)) {
echo '<input type="checkbox" name="group[]" value=" '. $line['ugroup'] .'" />';
echo'<input type="text" name="ugroup" disabled="disabled" value=" '. $line['ugroup'] .'" size="7" "/>';
echo ' ';
}
?><input type="submit" value="Submit">
</form>
db_add_page.php
if(isset($_POST))
{
$tittle = $_POST['tittle'];
$description = $_POST['description'];
$ugroup = $_POST['group'];
$acc_status = "INSERT INTO add_services (id,tittle,description,g1,g2,g3,g4,g5,g6,g7,g8)
VALUES(NULL,'".$tittle."','".$description."','".$ugroup[0]."','".$ugroup[1]."','".$ugroup[2]."','
".$ugroup[3]."','".$ugroup[4]."','".$ugroup[5]."','".$ugroup[6]."','".$ugroup[7]."')";
$rate = db::getInstance()->exec($acc_status);
if(!$rate){
echo '<script type="text/javascript">alert("Update Error !");</script>';
}else{
header('Location:../add_page.php');
echo '<script type="text/javascript">alert("Successfuly Updated User Group !");</script>';
}
}
i click on checkbox2,checkbox8 and submit.it's insert to g1 and g2.when i click on checkbox 1, checkbox3 its also added to g1 and g2.like below
Change line
echo '<input type="checkbox" name="group[]" value=" '. $line['ugroup'] .'" />';
To
echo '<input type="checkbox" name="group['.$line['id'].']" value=" '. $line['ugroup'] .'" />';
And yes start array index using 1
Normally, when we use $_POST values in checkboxes, those that are not checked will not be included in POST.
[group] => Array
(
[G1] => G1 // those the one you did not picked will not be included
[G3] => G3 // so that means your input is jagged
[G5] => G5 // you cannot hardcode each index (0 - 7)
[G7] => G7 // or they will be undefined (the ones that are missing)
)
So what you do is create a default value (an array) which will hold the defaults.
Then you combine those inputs, to the ones you have in default so that in return you will have a complete structure of insertion, instead of jagged inputs.
So in your form, do something like this:
while($line = $res_result->fetch(PDO::FETCH_ASSOC)) {
echo '<input type="checkbox" name="group['.$line['ugroup'].']" value=" '. $line['ugroup'] .'" />';
// assign G1, G2, indices
echo'<input type="text" name="ugroup" disabled="disabled" value=" '. $line['ugroup'] .'" size="7" "/>';
echo ' ';
}
Then on your processing form:
$default_values = array(); //create a default value
while($line = $res_result->fetch(PDO::FETCH_ASSOC)) {
$default_values[':' . $line['ugroup']] = '';
}
if(isset($_POST)) { // if submitted
$ugroup = array();
$temp = $_POST['group'];
foreach($temp as $val) {
$ugroup[':' . $val] = $val;
}
$combined_input = array_merge($default_values, $ugroup); // combine them so you have a complete structure
$sql = 'INSERT INTO add_services (tittle, description,g1,g2,g3,g4,g5,g6,g7,g8) VALUES (:title, :description, :G1, :G2, :G3, :G4, :G5, :G6, :G7, :G8)';
$acc_status = $db->prepare($sql);
$insert = array(':title' => $title, ':description' => $description,);
$insert = array_merge($insert, $combined_input);
$acc_status->execute($insert);
}
I am having the hardest time figuring out something that I think should be simple. I need to update multiple rows in my database with one submit button. I have it working with a submit for each row now, but I need to combine it. Here's what I'm trying. Where have I gone wrong? (I've been going off of multiple tutorials I found online and I think I have things all mixed up).
Here's the form:
<?php foreach ($teams as $team):
$id[]=$team['id'];?>
<form action="?update" method="post">
<div class="team-box">
<h2><?php echo $team['name'] ?></h2>
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo $team['name'] ?>" />
<label for="name">Match Wins:</label>
<input type="text" name="mwins" value="<?php echo $team['mwins'] ?>" />
<label for="name">Match Losses:</label>
<input type="text" name="mlosses" value="<?php echo $team['mlosses'] ?>" />
<label for="name">Match Ties:</label>
<input type="text" name="mties" value="<?php echo $team['mties'] ?>" />
<label for="name">Game Wins:</label>
<input type="text" name="gwins" value="<?php echo $team['gwins'] ?>" />
<label for="name">Game Losses:</label>
<input type="text" name="glosses" value="<?php echo $team['glosses'] ?>" />
<input type="hidden" name="id" value="<?php echo $team['id'] ?>" />
</div>
Here's the PHP to handle the UPDATE:
try
{
foreach($_POST['id'] as $id) {
$sql = 'UPDATE teams SET
name = "' . $_POST['name'.$id] . '",
mwins = "' . $_POST['mwins'.$id] . '",
mlosses = "' . $_POST['mlosses'.$id] . '",
mties = "' . $_POST['mties'.$id] . '",
gwins = "' . $_POST['gwins'.$id] . '",
glosses = "' . $_POST['glosses'.$id] . '"
WHERE id = "' . $_POST['id'.$id] . '"';
$pdo->exec($sql);
}
}
catch (PDOException $e)
{
$error = 'Error adding submitted team: ' . $e->getMessage();
include 'error.html.php';
exit();
}
header('Location: .');
exit();
Thanks in advance!
There are a couple of things that need fixing.
The FORM must be outside the foreach.
The '...name="name" value="...', to agree with the _POST code, should read instead:
... name="name" value="...
This way, a single POST will submit, say,
name123="Rangers"
mwins174="123"
Then you need all IDs. You can do that by issuing, in the foreach, this:
<input type="hidden" name="id[]" value="<?php print $team['id']; ?>" />
This will result in HTML:
<input type="hidden" name="id[]" value="123" />
...
<input type="hidden" name="id[]" value="456" />
and in $_POST['id'] being an array containing 123, 456 and so on.
You could also put in HTML:
<input type="text" name="name[<?php print $team['id']; ?>]" value="...
so that $_POST['name'] would be a vector with the same keys as the values of id, and therefore:
foreach($id as $team_id)
{
// Pseudocode
UPDATE... SET name=$name[$team_id]... WHERE id = $team_id;
}
This way you have one SUBMIT, and multiple UPDATEs.
Since all your field names change for each UPDATE query, you will need to execute separate queries as you already do. I don't think you would be able to perform a single UPDATE query.
I don't understand, what's wrong with executing several update queries?
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