i have multiple input-fields with the same name as id's and the other fields with other names like
<input name="id[]" value="1" /> <input name="st[]" value="4" />
<input name="id[]" value="5" /> <input name="st[]" value="57" />
<input name="id[]" value="79" /> <input name="st[]" value="43" />
.
.
.
in my sql table i want to change ...maybe id->3 and id->87 or whatever 10 others to update the column "st" with the value from the right side input field. The key values from id and st are the same.
I know the update-sql-syntax of one row. but, if i want more rows i dont know what to do
my reasoning was do it with Jquery Ajax or php Implode like
$id = implode(',', $_POST['id']);
$st = implode(',', $_POST['st']);
$sql = "UPDATE table SET st=('$st') WHERE id=('$id')";
then i found this from user peterm
UPDATE table
SET st = CASE id
WHEN 'id_x' THEN 'st_x'
WHEN 'id_y' THEN 'st_y'
...
ELSE st
END
WHERE id IN('id_x', 'id_y', ...);
How do i get it with spontaneously entrys from my website-user in a loop (foreach?)
I hope it can resolve your problem. You can use the code as below :
if(!isset($_POST['id'] || count($_POST['id']) == 0){
return;
}
foreach($_POST['id'] as $key => $id)){
$sql = "UPDATE table SET st='{$_POST['st'][$key]}' WHERE id='{$id}'";
}
$SizeOfID=sizeof($id);
for($i=0;$i<$SizeOfID;$i++)
{
$IDvalue=$id[$i];
$STvalue=$st[$i];
mysql_query("UPDATE table SET st='$STvalue' WHERE id='$IDvalue'");
}
There is also another quicker way to accomplish it without executing multiple sql because of the loop.
But you must make sure that the query will be constructed in a way that it will "hit" on existing unique key ( for example the primary ) and so it will use the sql's ON DUPLICATE KEY to update its VALUES...
For example:
<?php
$values = [];
foreach( $data as $id => $value ){
$values[] = "( '".$id."', '".$value."' )";
}
if( (bool)$values ){
$sql = "INSERT INTO table ( id, st ) VALUES".implode(',',$values)." ON DUPLICATE KEY UPDATE st = VALUES(st)";
//execute $sql here
}
Of course you need to validate - sanitize data... the usual stuff...
Related
I want to Insert multiple values of input fields one column in separate multiple rows. input is taking multiple values in array as tags. I am using PHP & sql server as database
<input class="col-sm-10 tokenfield" style="width:50%;" type="text" placeholder="Enter ID" class="form-control" name="id[]" id="id" required />
sql query is
$id = $_POST['id'];
foreach( $id as $i){
$sql = insert into [db].[table] (id,name,phone,message) values ($i,$name,$phone,$message)
}
it showing as group values in single row in column of table but i want all values in as different rows values as id
Here is sample code which should work. (Convert datatype as needed if require.)
$postValue = $_POST['id']; // comma separated values
$ids = explode(',', $postValue); // List of ids
//Loop through each id and prepare SQL statement
foreach($ids as $id){
$sql = "insert into [db].[table] (id,name,phone,message) values ('$id','$name',$phone,'$message')";
}
sample screenshot:
I need help to link between three tables by checkboxe:
features table ( id, title, sulg )
posts table (id, title, slug, added )
posts_features ( fea_id, post_id )
<input type="text" name="title" value="$post->title">
<input type="text" name="slug" value="$post->slug">
// importing all features
<input type="checkbox" name="featuresid[]" value="$features->id">
If checked ( insert ) if not exist.
foreach ($_POST['featuresid'] as $choice) {
$sql = $dbh->prepare("INSERT INTO posts_features (fea_id, post_id) VALUES ($choice, $id)");
$sql->execute();
}
and if un-checked ( delete ) from posts_features
$sql = $dbh->prepare("delete form posts_features where ........
Thanks in advance.
A checkbox doesn't $_POST if it's not checked, so you would not have a way to see (from the $_POST, anyway) which features where not checked.
There's several ways to do this, but without more information about your application, it's hard to make the "best" suggestion, but here's one method that will leverage $_POST:
Add an additional "hidden" input, with the corresponding $features->id, to set up the "existing" entries:
Note: I'm following your conventions in your code above to demonstrate this, even though they are clearly pseudo-code, and won't work properly.
<input type="checkbox" name="featuresid[]" value="$features->id">
<input type="hidden" name="existing[]" value="$features->id">
Then, you can leverage your loop like so:
foreach ($_POST['featuresid'] as $choice) {
$sql = $dbh->prepare("INSERT INTO posts_features (fea_id, post_id) VALUES ($choice, $id)");
$sql->execute();
}
// loop through ALL feature ids listed on the page
foreach( $_POST['existing'] AS $features_id ) {
// if the feature id wasn't in the checkboxes, then delete
if ( ! in_array( $features_id, $_POST['featuresid'] ) ) {
$sql = $dbh->prepare("DELETE FROM posts_features WHERE ........");
}
}
Un-checked checkboxes are not sent to PHP. So as you iterate through $_POST['featuresid'], you will only see the checkboxes that were checked. This means that to delete unchecked features really means to delete all features that are not in the checked group.
First, insert the selected features: important don't execute DB queries in a loop; they will really slow down your script. Instead, insert all records at once. You should also use parameterized queries; never insert user-supplied values directly into your DB queries!
After the insert, delete those features that were not selected:
DELETE FROM posts_features WHERE fea_id NOT IN (?, ?, ?, ?)
Each of the ? corresponds to a value in $_POST['featuresid']
An alternative, if you want PHP to receive an explicit selected/unselected value for each feature is to use Yes/No radio buttons or dropdown list for each feature in the HTML.
i have a table like this:
id product_category product_name product_range discount_amt
---------------------------------------------------------------------------
1 Post Card 4x6 5M to 9,999 0.007
2 Post Card 4x6 10M to 14,999 0.01
3 Post Card 4x6 15M to 19,999 0.013
4 Post Card 4x6 20M to 24,999 0.015
5 Post Card 4x6 Over 25M 0.019
i'm calling just the discount_amt column into page like this:
$pricediscountquery = mysql_query("SELECT * FROM pricing_discount") or die(mysql_error());
$i=0;
while($pricingdiscountrow = mysql_fetch_array( $pricediscountquery )) {
$pricingdiscountarray[$i++]=$pricingdiscountrow['discount_amt'];
}
i'm displaying form fields and discount amounts prefilled in the values of the form fields like this:
<p>5M to 9,999: <input type="text" name="pc_4x6_5m_to_9999" value="<?php echo $pricingdiscountarray[0]; ?>" /></p>
<p>10M to 14,999: <input type="text" name="pc_4x6_10m_to_14999" value="<?php echo $pricingdiscountarray[1]; ?>" /></p>
<p>15M to 19,999: <input type="text" name="pc_4x6_15m_to_19999" value="<?php echo $pricingdiscountarray[2]; ?>" /></p>
<p>20M to 24,999: <input type="text" name="pc_4x6_20m_to_24999" value="<?php echo $pricingdiscountarray[3]; ?>" /></p>
<p>Over 25M: <input type="text" name="pc_4x6_over_25m" value="<?php echo $pricingdiscountarray[4]; ?>" /></p>
i'm creating my post variables like this:
$pc_4x6_5m_to_9999 = mysql_real_escape_string(htmlspecialchars($_POST['pc_4x6_5m_to_9999']));
$pc_4x6_10m_to_14999 = mysql_real_escape_string(htmlspecialchars($_POST['pc_4x6_10m_to_14999']));
$pc_4x6_15m_to_19999 = mysql_real_escape_string(htmlspecialchars($_POST['pc_4x6_15m_to_19999']));
$pc_4x6_20m_to_24999 = mysql_real_escape_string(htmlspecialchars($_POST['pc_4x6_20m_to_24999']));
$pc_4x6_over_25m = mysql_real_escape_string(htmlspecialchars($_POST['pc_4x6_over_25m']));
i'm trying to update multiple rows/records at the same time, just in the discount_amt column like this:
mysql_query("INSERT INTO pricing_discount (id,discount_amt) VALUES (1,$pc_4x6_5m_to_9999),(2,$pc_4x6_10m_to_14999),(3,$pc_4x6_15m_to_19999),(4,$pc_4x6_20m_to_24999),(5,$pc_4x6_over_25m) ON DUPLICATE KEY UPDATE discount_amt=VALUES(discount_amt); ") or die(mysql_error());
the one above doesn't create error in code, but it creates error on web page: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '),(2,),(3,),(4,),(5,) ON DUPLICATE KEY UPDATE discount_amt=VALUES(discount_amt)' at line 1
also tried this:
mysql_query("INSERT INTO pricing_discount (id,discount_amt) VALUES (1,'$pc_4x6_5m_to_9999'),(2,'$pc_4x6_10m_to_14999'),(3,'$pc_4x6_15m_to_19999'),(4,'$pc_4x6_20m_to_24999'),(5,'$pc_4x6_over_25m') ON DUPLICATE KEY UPDATE discount_amt=VALUES(discount_amt); ") or die(mysql_error());
this gave an error in code so i didn't even save it and try to run it:
mysql_query("INSERT INTO pricing_discount (id,discount_amt) VALUES (1,"$pc_4x6_5m_to_9999"),(2,"$pc_4x6_10m_to_14999"),(3,"$pc_4x6_15m_to_19999"),(4,"$pc_4x6_20m_to_24999"),(5,"$pc_4x6_over_25m") ON DUPLICATE KEY UPDATE discount_amt=VALUES(discount_amt); ") or die(mysql_error());
this also gave error in code:
mysql_query("INSERT INTO pricing_discount (id,"discount_amt") VALUES (1,"$pc_4x6_5m_to_9999"),(2,"$pc_4x6_10m_to_14999"),(3,"$pc_4x6_15m_to_19999"),(4,"$pc_4x6_20m_to_24999"),(5,"$pc_4x6_over_25m") ON DUPLICATE KEY UPDATE discount_amt=VALUES(discount_amt); ") or die(mysql_error());
if you hard code values like this it works, but i'm doing variables:
mysql_query("INSERT INTO pricing_discount (id,discount_amt) VALUES (1,1),(2,3),(3,3),(4,12),(5,12) ON DUPLICATE KEY UPDATE discount_amt=VALUES(discount_amt); ") or die(mysql_error());
what's the correct way to do this?
if you're wondering why i didn't do UPDATE instead of INSERT when trying to update records, it's because i was following this stackoverflow:
Multiple Updates in MySQL
I am assuming, in your table discount_amt will be float or double datatype. then below sql query qill work. for int, float, decimal or double datatype no need to add value between single quote'.
$query = "
INSERT INTO pricing_discount
(id
,discount_amt
) VALUES
(1,".$pc_4x6_5m_to_9999."),
(2,".$pc_4x6_10m_to_14999."),
(3,".$pc_4x6_15m_to_19999."),
(4,".$pc_4x6_20m_to_24999."),
(5,".$pc_4x6_over_25m.")
ON DUPLICATE KEY UPDATE discount_amt = VALUES(discount_amt);
";
mysql_query($query) or die(mysql_error());
Just to recap, what's wrong with this...
$query = "
INSERT INTO pricing_discount
(id
,discount_amt
) VALUES
(1,'$pc_4x6_5m_to_9999'),
(2,'$pc_4x6_10m_to_14999'),
(3,'$pc_4x6_15m_to_19999'),
(4,'$pc_4x6_20m_to_24999'),
(5,'$pc_4x6_over_25m')
ON DUPLICATE KEY UPDATE discount_amt = VALUES(discount_amt);
";
mysql_query($query) or die(mysql_error());
I have a form where the user inserts data but they can go back to the same page to edit their information. My table structure is:
id (auto int index),
user id (links to other tables),
Doc_Name,
Abstract
I have an insert query:
$user_id = intval($_SESSION['user_id']);
$Doc_Name = mysql_real_escape_string($_POST['Doc_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
$the_query = sprintf("INSERT INTO `document` (`user_id`,`Doc_Name`,`abstract`) VALUES
('%d','%s','%s')", $user_id, $Doc_Name, $abstract);
However, if their is already a row for this user_id then I want the update query instead:
mysql_query("UPDATE document SET `Doc_Name` = '$Doc_Name', 'abstract='$abstract'
WHERE id='$_SESSION[user_id]'") or die(mysql_error());
Also, so the user knows what they entered, I tried to use this echo in the text box but that didn't work either,
<textarea name="Doc_Name" style="width:500px; height:150px" type="text" id="Doc_Name"
value="<? echo $row_settings['Doc_Name']; ?>" size="300"> </textarea>
You can use INSERT ... ON DUPLICATE KEY UPDATE Syntax
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE
c=c+1;
You want the INSERT ... ON DUPLICATE UPDATE syntax
for the textarea you can use
<textarea name="Doc_Name" style="width:500px; height:150px" type="text" id="Doc_Name" size="300"><? echo $row_settings['Doc_Name']; ?></textarea>
everything between the tags is displayed and editable
EDIT: to the other posters: nice, did not know INSERT ON DUPLICATE
the query:
SELECT * FROM document WHERE id='{$SESSION['user_id']}'
php:
if(mysql_num_rows(mysql_query($query)) > 0) {
//code to be executed if id exists
}
I have a form that is populated with mySQL db values upon loading the page. The data in the form can be edited and then a submit button that send the data to mysql to overwrite the values that were preloaded in the form. The fields are displayed in the form correctly but when changed and submitted I receive the following:
Error:Unkown column in 'where clause'.
I'm relatively new to working with mysql query's instead of taking the 'phpmyadmin' route ._.
Here's the query I used to fill the table with the original form data:
INSERT INTO mytable VALUES ("sunday", "name1", "price1"), ("monday", "name2", "$35"), ("tuesday", "name3", "$100"), ("wednesday", "name4", "$65"), ("thursday", "name5", "$5"), ("friday", "name6", "$57"), ("saturday", "name7", "$10");
Here's the sql query used to populate the form and then assigned to a variable by usingfetch_array
$sun_data = mysql_query("SELECT * FROM mytable WHERE day='sunday'")
or die(mysql_error());
... ...
$sun_info = mysql_fetch_array( $sun_data );
Then the form:
<form action="update_form.php">
<input type="text" name="sun_name" value="<?php echo $sun_info['name'] ?>" />
<input type="text" name="sun_price" value="<?php echo $sun_info['price'] ?>" />
Like I said the form updates fine but then when the form data is submitted to update_form.php I receive the error. Here is the form action update.php
$sun_day_change = $_POST['sun_name'];
$sun_price_change = $_POST['sun_price'];
$sunday = 'sunday';
$sql = "UPDATE mytable SET name = '$sun_day_change', price = '$sun_price_change' WHERE day = ".$sunday;
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
header('Location: http://localhost/form.php');
I'm assuming the issue is when I pass the values back to the database but since I have used almost the identical sql query to retrieve the values I'm not sure where I went wrong. Thanks for the help!
You are missing quotation marks in the update query, around $sunday.
$sql = "UPDATE mytable SET name = '$sun_day_change', price = '$sun_price_change' WHERE day = '".$sunday."'";