I'm trying to update one row (= ID) of a mysql table from multiple form fields (text fields and text areas). The table looks like this:
ID | Col 1 | Col 2 | Col 3 ... | Col 50
Everything works fine, if I use $_Post[] variables like this
$Name = $_POST['Name'];
$Name2 = $_POST['Name2'];
$sql= "UPDATE Bilder SET Name = '$Name', Name2 = '$Name2' WHERE id = '$ID'";
<form id="InsertData" action="insert-dataset.php" method="post">
<input type="hidden" name="ID" id="ID" value="'.$row->id.'" />
<input type="text" name="Name" value="'.$row->Name.'" /><br />
<input type="text" name="Name2" value="'.$row->Name.'" /><br />
<input type="submit" name="submit" value="Daten eintragen" class="sendbutton" />
</form>
Since I have hundreds of fields I would rather use an array like so:
<input type="text" name="Name[]" value="'.$row->Name.'" />
I found working examples for updating all cells of one column. But I have to update all colums for one ID.
Any help would be appreciated. Thanks in advance!
This is the final result:
$col_result = mysql_query("SHOW COLUMNS FROM Bilder");
$row_result = mysql_query(sprintf("SELECT * FROM Bilder WHERE id = %s", $ID));
if(!$col_result) {
echo 'Konnte Anfrage nicht ausführen: ' . mysql_error();
exit;
}
if ( !empty($_POST) ) {
$aDataSet = array();
while( list( $field, $value ) = each( $_POST )) {
$aDataSet[] = $field . "='" . $value . "'";
}
$update_sql = "UPDATE Bilder SET " . implode( ',', $aDataSet );
$update_sql .= sprintf("WHERE id = '$ID'");
$result = mysql_query($update_sql, $connection);
if(!$result)
{
die('');
}
echo '';
}
mysql_close($connection)
?>
The update query will only include colums that have corresponding input field (input name = column name). Since I have hundreds of input fields, I can spread them over multiple pages using the same code for the update query.
Thank you all for your help.
Probably something like that:
$str = '';
$id = 0;
foreach($_POST['Name'] as $value)
{
$id ++;
$str .= ($str == '' ? '' : ', ').'Name'.$id.' = \''.addslashes($value).'\'';
}
$sql= "UPDATE Bilder SET ".$str." WHERE id = '$ID'";
Note: on this example, your sql fields are Name1, Name2, Name3...
Note2: you should always at least use an addslashes method when pasting a variable inside a sql query, to protect yourself from hackers.
Here is a couple ideas.
Name your fields something useful. Naming them garbage like Name1, Name2 etc is going to bite you on the ass later down the line. Also be nice to the next guy thats going to have to look at this.
If you have a bunch of Meaningful or Unmeaningful fieldnames and don't want to manually type them all out in your code, maybe use the SQL DESCRIBE (http://dev.mysql.com/doc/refman/5.0/en/explain.html) or SHOW COLUMNS command (http://php.net/manual/en/function.mysql-list-fields.php)
Note: untested
<?php
// Get all of the field names
$col_result = mysql_query("SHOW COLUMNS FROM Bilder");
// make sure we could get the colnames from mysql
if(!$col_result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
// Handle a POST
if(!empty($_POST)){
// start preparing the update statement
$update_sql = "UPDATE Bilder SET ";
if(mysql_num_rows($col_result) > 0) {
// make a key = value statement for each column in the table
while($colrow = mysql_fetch_assoc($col_result)) {
// prepare the key = value statement
$update_sql .= sprintf(" %s = %s, ", $colrow["Field"], mysql_real_escape_string($_POST[$colrow["Field"]]));
}
}
// BTW this is going to have a extra "," in it use substr to clear it
$update_sql = substr_replace($update_sql ,"", -2);
// finish off by limiting this statement to only one row
$update_sql .= sprintf(" WHERE id = %s", mysql_real_escape_string($_POST["id"]));
// ACTUALLY RUN THIS STATEMENT
}
if(!$row_result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
// prepare the sql to fetch the current row we are working on
$row_result = mysql_query(sprintf("SELECT * FROM Bilder WHERE id = %s", $id));
// Get the row item that you are currently working on
$row = mysql_fetch_row($row_result);
// output all the formfields for the above row
if(mysql_num_rows($col_result) > 0) {
// Go through all of the columns and output the colname from $colrow and the value from $row
while ($colrow = mysql_fetch_assoc($col_result)) {
// The HTML (don't be daunted by that variable-variable http://php.net/manual/en/language.variables.variable.php)
echo '<input type="text" name="' . $colrow["Field"] . '" value="' . $row->{$colrow["Field"]} . '" /><br />';
}
}
?>
lastly, you may be better served by an EAV style of DB where the number of fields for a row is variable. (a fair example with php and mysql: http://www.iwilldomybest.com/2008/08/php-mysql-tip-3/)
Ok, I used preg_replace. This is probably not best practices. The code looks like this and works just fine:
// Handle a POST
if(!empty($_POST)){
// start preparing the update statement
$update_sql = "UPDATE Bilder SET ";
if(mysql_num_rows($col_result) > 0) {
// make a key = value statement for each column in the table
while($colrow = mysql_fetch_assoc($col_result)) {
// prepare the key = value statement
$update_sql .= sprintf("%s = '%s',", $colrow["Field"], mysql_real_escape_string($_POST[$colrow["Field"]]));
}
}
// BTW this is going to have a extra "," in it use substr to clear it
// finish off by limiting this statement to only one row
$update_sql .= sprintf("WHERE id = '$ID'");
$update_sql = preg_replace("/,WHERE/", "WHERE", $update_sql);
There are, of course, security issues. I will fix that. However, this is not that important, since this application is for personal use only. It is not publicly accessible.
I'm pretty new at this kind of thing so I Don't know how safe or effiecnt this is, but it does work.
if ($_POST['Submit']=="Update"){
unset($_POST['Submit']);
$refid=$_POST['refid'];
unset($_POST['refid']);
$update=$_POST;
// Update DB with array
foreach ($update as $col => $val) {
$colsvals=$col."='".$val."'";
$mysql = mysqli_query($db, "UPDATE $tbl SET $colsvals WHERE id='$refid'")
or die('Database Connection Error ('.mysqli_errno($db).') '.mysqli_error($db). " on query: UPDATE $tbl SET $colsvals WHERE id='$refid'");
}
}
I start by cleaning out things I don't want to Updated.
Then I really had to take a sec to make sure I have the double/single quotes, equals, and dots right in the colsvals statment.
But for me The Magic came from realizing I could let the Foreach loop run a new query each time it etterates through the update array.
Related
I have Information in the database that shares the same FK but unique PK, and so I looping it to display on the page. And I wanted to build an SQL Update Query to be able to update it. I have now 2 loops but I'm not sure how to fully combine them so that it works in one.
What am I missing or what do I need to do in order to be able to get the results I need so that when I run the code it updates the unique field that should be updated? Should I rather put a for-each loop inside of another for-each loop would that work?
This is the code to connect and get the information from the database and then a loop to display the values and the id fields.
//connect
$sql_awards = "select `awards`, `awardsid` from inf_awards where inf_id = $vId";
$rs_awards = mysqli_query($vconncvnl, $sql_awards);
//display inputs
while ($rs_awards_rows = mysqli_fetch_assoc($rs_awards)) {
echo '<input type="text" name="awardact[]" id="awardact" class="awardactadd" value="' . $rs_awards_rows['awards'] . '">';
echo '<input type="hidden" name="txtaward[]" value="'. $rs_awards_rows['awardsid'] .'">';
}
So now I can get the information to a process page I also have an SQL update statement and a looped
the foreach loop i used to display the awards id and then the foreach loop for the sql Code
//construction of loop for the awardsID field
$awardsId = '';
$award = $_POST['txtaward'];
foreach ($award as $awardid){
$awardsId .= $awardid;
}
//construction of the loop for building the SQL Update Query
$sql_up_award = '';
foreach ($vaccolates as $valuesawards) {
$sql_up_award .= sprintf("UPDATE inf_awards SET awards = %s WHERE inf_id = $vid AND awardsid = $awardsId ; ". "<br>", escapestring($vconncvnl, $valuesawards,'text'));
}
but when I do it like this it gives me
UPDATE inf_awards SET awards = 'john smith honorary' WHERE inf_id = 2 AND awardsid = 23;
UPDATE inf_awards SET awards = 'Best scorer' WHERE inf_id = 2 AND awardsid = 23;
im guessing this is cause of the previous loop now that when i call it in it will just loop every value that meets the requirement which at this point is just '23' however
The Results I would want to be is like
UPDATE inf_awards SET awards = 'john smith honorary' WHERE inf_id = 2 AND awardsid = 2;
UPDATE inf_awards SET awards = 'Best scorer' WHERE inf_id = 2 AND awardid = 3;
Nested loops are not going to solve it, because you'll end up with 4 updates.
You have two arrays, one with the ids, one with the values. You can make a single for loop and get the matching values by index.
However, I think this is not completely safe, since I'm afraid that people could make the texts empty and that way screw up your array, so it's important to at least check beforehand that both arrays contain the same number of items:
if (count($award) != count($valuesawards)) {
echo 'Please fill in all the names';
} else {
$sql_up_award = '';
//construction of the loop for building the SQL Update Query
$sql_up_award = '';
for ($i = 0; $i < count($award); $i++) (
$awardid = $award[$i];
$valuesawards = $vaccolates[$i];
$sql_up_award .= sprintf("UPDATE inf_awards SET awards = %s WHERE inf_id = $vid AND awardsid = $awardsId ; ". "<br>", escapestring($vconncvnl, $valuesawards,'text'));
}
}
I am new to PHP programming, and I am working on my first program.. This is for the beginnings of a warehouse management system, so I am needing to be able to query part numbers, EANs, item names, etc. Occasionally, all info will be known, or an exact match when input by the user, but sometimes the user will only know part of an EAN, or want to check all items with a similar name, so the results need to be LIKE the input given by the user.
Everything works okay when the user inputs info in only one input in the form (ex. ONLY the entire or portion of a part number is added to the 'partnumber' input, and it correctly returns relevant rows with the info query'd), but when there are multiple inputs added by the user to query table (ex. user inputs data into 'partnumber' AND 'EAN' input), then the result ends up being every item from the table.. same as 'SELECT * FROM table;'.
Is there a way to query and output data from multiple inputs over multiple columns? I have searched this everywhere, but have yet to find an answer relevant to my need... (or at least one with my level of understanding). Any help in the right direction would be great!
SQL query's I have used so far:
$query = "
SELECT partNumber
, EAN
, UPC
, itemDescription
, SNFlag
, idClass
, idType
FROM productinfo_table
WHERE partNumber LIKE '$partNumber'
OR EAN LIKE '$EAN'
OR itemDescription LIKE '$itemDescription'
OR SNFlag LIKE '$SNFlag'
";
And:
$query = "
SELECT partNumber
, EAN
, UPC
, itemDescription
, SNFlag
, idClass
, idType
FROM productinfo_table
WHERE (partNumber,EAN,itemDescription,SNFlag) IN LIKE ('$partNumber','$EAN','$itemDescription','$SNFlag')";
Among a few others...
testissue.php
<?php //testissue.php
//establish connection
require_once "login.php";
$db_server = mysqli_connect($db_hostname,$db_username,$db_password,$db_database);
if(!$db_server) printf('Error connecting to database: %s',mysqli_error($db_server));
//if loop to acquire variables
//if all post array elements are NOT empty
if(!empty($_POST['partNumber']) ||
!empty($_POST['EAN']) ||
!empty($_POST['itemDescription']) ||
!empty($_POST['SNFlag'])) {
//if partNumber is not empty
if(!empty($_POST['partNumber'])) {
$partNumber = '%';
$partNumber .= $_POST['partNumber'];
$partNumber .= '%';
} else {
$partNumber = '';
}
//if EAN is not empty
if(!empty($_POST['EAN'])) {
$EAN = '%';
$EAN .= $_POST['EAN'];
$EAN .= '%';
} else {
$EAN = '';
}
// if itemDescription is not empty
if(!empty($_POST['itemDescription'])) {
$itemDescription = '%';
$itemDescription .= $_POST['itemDescription'];
$itemDescription .= '%';
} else {
$itemDescription = '';
}
//if SNFlag is not empty
if(!empty($_POST['SNFlag'])) {
$SNFlag = '%';
$SNFlag .= $_POST['SNFlag'];
$SNFlag .= '%';
} else {
$SNFlag = '';
}
//echo variables to confirm set, for testing
echo "$partNumber<br/>";
echo "$EAN<br/>";
echo "$itemDescription<br/>";
echo "$SNFlag<br/>";
//query to pull data to insert into table rows
//$query = "SELECT partNumber,EAN,UPC,itemDescription,SNFlag,idClass,idType FROM productinfo_table WHERE partNumber LIKE '$partNumber' OR EAN LIKE '$EAN' OR itemDescription LIKE '$itemDescription' OR SNFlag LIKE '$SNFlag'";
$query = "SELECT partNumber,EAN,UPC,itemDescription,SNFlag,idClass,idType FROM productinfo_table WHERE (partNumber,EAN,itemDescription,SNFlag) IN LIKE ('$partNumber','$EAN','$itemDescription','$SNFlag')";
$result = mysqli_query($db_server,$query);
if(!$result) printf("Error querying database: %s",mysqli_error($db_server));
$rows = mysqli_num_rows($result);
}
//if all post array elements ARE empty
else {
echo "empty post array";
$rows = '';
}
//echo form input
echo <<<HERE
<pre>
<form action='testissue.php' method='post'>
Part No. <input type='text' name='partNumber' />
EAN <input type='text' name='EAN' />
Item Desc. <input type='text' name='itemDescription' />
SN Flag <input type='text' name='SNFlag' />
<input type='submit' value='Search' />
</form>
</pre>
HERE;
//print post array to confirm set values, for testing
echo "<br/>";
print_r($_POST);
echo "<br/><br/>";
//echo table for output
echo <<<HERE
<table>
<tr><th>Part No.</th> <th>EAN</th> <th>UPC</th> <th>Item Desc.</th> <th>SN Flag</th> <th>Class ID</th> <th>Type ID</th></tr>
HERE;
// for loop function to populate items in table
for($a=0;$a<$rows;++$a){
echo "<tr>";
$col = mysqli_fetch_row($result);
for($b=0;$b<7;++$b) echo "<td>$col[$b]</td>";
echo "</tr>";
}
echo "</table>";
//close connection
mysqli_close($db_server);
?>
Please let me know if you need anything else to help or offer any improvements.
Thanks a lot!
You need to use AND clause rather than OR.
AND will give you rows that match all conditions in WHERE clause
OR will return rows that match any of the conditions in WHERE clause
$query = "
SELECT partNumber
, EAN
, UPC
, itemDescription
, SNFlag
, idClass
, idType
FROM productinfo_table
WHERE partNumber LIKE '$partNumber'
AND EAN LIKE '$EAN'
AND itemDescription LIKE '$itemDescription'
AND SNFlag LIKE '$SNFlag'
";
Note: Please note the suggestions provided in the comments to prevent SQL injection
$sql="SELECT *FROM table where partNumber = '$partnumber'order by id ASC";
I'm trying to copy title column to keywords column in database, so the keywords will be inserted automatically from the title.
http://store2.up-00.com/2015-06/1435609110941.png
I want to add comma ', ' before each word for example.
" It's my first program "
it will turn into
" It's, my, first, program, "
This the code I wrote.
<?php
// $id =mysql_insert_id;
$select_posts = mysql_query("SELECT * FROM `posts`");
while($row = mysql_fetch_array($select_posts)){
$id = $row['post_id'];
$text = $row['post_title'];
$delim = ' \n\t,.!?:;';
$tok = strtok($text, $delim);
while ( $tok !== false){
echo $tok1 = $tok.',';
mysql_query("UPDATE `posts` SET `post_keywords` = '$tok1' WHERE `post_id` = $id ");
$tok = strtok($delim);
}
}
?>
it insert the last word in each title column , because the words is overwritten by while loop.
Please help me .
Concat the values:
... SET post_keywords = CONCAT(post_keywords, '$tok1')
and note that you're vulnerable to sql injection attacks. Just because that $tok1 value came out of a database doesn't mean it's safe to REUSE in a query...
You can do it with a single query :
UPDATE `posts` SET post_keywords = REPLACE(post_title, ' ', ',');
I recently have been trying to make a way to easily add more fields onto my form without having to go back and add more rows to my database structure. So, to begin working on this, I created a table where the structure is this:
OptionTitle
Option1
Option2
Option3
Option4
Option5
Option6
As you can see, it goes up to 6 options, and OptionTitle is the label name of the form. Then I made another table, one that reflects the users input of the previous table. This table is named usersoption
fid
OptionTitle
Option1
Ok, so FID reflects which form it is referencing to. This way, when displaying the submitted form, it'll pull information from this table where the FID is the same. OptionTitle is the label of the form, and Option1 is the option the user submitted.
Now, onto the form where it actually includes the options to select from. Here is a simplified version of how my code is included:
$query100 = $db->query("SELECT * FROM options WHERE fid='" . $id . "'");
while($row2 = mysqli_fetch_array($query100))
{
echo "
<div class=\"divform\" id=\"optiontitle\">
<label for=\"optiontitle\">$row2[optiontitle]:</label>
<select name=\"option1[]\" id=\"option1\">";
echo "<option value='$row6[option1]'>$row6[option1]</option>";
echo "<option value='$row6[option2]'>$row6[option2]</option>";
echo "<option value='$row6[option3]'>$row6[option3]</option>";
echo "<option value='$row6[option4]'>$row6[option4]</option>";
echo "<option value='$row6[option5]'>$row6[option5]</option>";
echo "<option value='$row6[option6]'>$row6[option6]</option>";
echo "
</select>
</div>
";
}
As you can see, the select name is option1[]. This is so I can have multiple select fields on the same form, and in return this will bring over the multiple difference select fields onto the submitted process. So now onto where my issue is, in the submission process. Here is what I have so far:
foreach($_POST['option1'] as $val){
$val = $db->escape_string($val);
$query30 = $db->query("INSERT `usersoption` SET `gid` = '".$id."', `fid` = '".$fid."', `optiontitle` = 'Where OptionTitle should go', `option1` = '$val'")or die( mysqli_error());
}
As you can see, I can successfully bring the option through a foreach statement. What I can't do, is bring in the OptionTitle. It seems almost unnecessary to bring in the OptionTitle, but it is necessary for the person reading the submitted form to know which option was being submitted. I'm not sure how to carry the OptionTitle over, it seems simple but all my attempts failed miserably. I did some research and one of the suggestions was to create a hidden input with the name and carry it over that way. Here is the addon that would be in the form:
<input type=\"hidden\" name=\"optiontitle[]\" value=\"test\">
This would be added on to the form and then carried over, but the issue is how do I bring it over? I would need to do a multiple foreach statement which does not work. For example, here was what I tried to bring over (it did not work):
foreach($_POST['option1'] as $val) && ($_POST['optiontitle'] as $val2)){
$val = $db->escape_string($val);
$val2 = $db->escape_string($val2);
$query30 = $db->query("INSERT `usersoption` SET `gid` = '".$id."', `fid` = '".$fid."', `optiontitle` = '$val2', `option1` = '$val'")or die( mysqli_error());
}
Have you tried giving your option array a key?
echo "<select name=\"option1[$row2[optiontitle]]\" id=\"option1\">";
Then change your foreach to:
foreach($_POST['option1'] as $title=>$val)
You can use key in foreach to access more array:
Try this code:
foreach($_POST['option1'] as $key=>$val){
$val = $db->escape_string($val);
$val2 = $db->escape_string(isset($_POST['optiontitle'][$key])?$_POST['optiontitle'][$key]:'');
$query30 = $db->query("INSERT `usersoption` SET `gid` = '".$id."', `fid` = '".$fid."', `optiontitle` = '$val2', `option1` = '$val'")or die( mysqli_error());
}
For the hidden input solution: Just do each query as you normally would, but add $_POST['optiontitle']:
foreach($_POST['option1'] as $val){
$val = $db->escape_string($val);
$query30 = $db->query("
INSERT `usersoption` SET
`gid` = '".$id."',
`fid` = '".$fid."',
`optiontitle` = '".$_POST['optiontitle']."',
`option1` = '$val'
")or die(mysqli_error());
}
By the way you should read up on prepared statements. These allow you to sanitise your data before inserting into the database. They are essential to good coding practise.
I have a search script that retrieves an integer from one table and uses it to search through the IDs of a 2nd table. My issue is if the integer in Table1 appears more then once, I get duplicate results when querying Table2.
Does anyone know a way to use SQL or PHP so that if a row is already displayed it will skip it? Thanks
My code is rather convuleted but here it is if it helps:
//TV FILTERS
$sql = 'SELECT * FROM `table1`';
$where = array();
if ($searchlocation !== 'Any') $where[] = '`value` LIKE "%'.$searchlocation.'%"';
if ($searchmake !== 'Any') $where[] = '`value` LIKE "%'.$searchmake.'%"';
if ($searchtype !== 'Any') $where[] = '`value` LIKE "%'.$searchtype.'%"';
if (count($where) > 0) {
$sql .= ' WHERE '.implode(' OR ', $where);
} else {
// Error out; must specify at least one!
}
$tvqresult = mysql_query($sql);
$num_rowstvq = mysql_num_rows($tvqresult);
while ($rowtvq = mysql_fetch_array($tvqresult)) {
$contid = $rowtvq['contentid'];
//MAIN QUERY
$mainsql = 'SELECT * FROM `table2` WHERE `content` LIKE "%' . $searchterm . '%" AND `id` = ' . $rowtvq['contentid'] . ' AND `template` = 12';
$resultmain = mysql_query($mainsql);
$num_rowsmain = mysql_num_rows($resultmain);
if (!$resultmain) {
continue;
}
else {
while ($row = mysql_fetch_array($resultmain )) {
echo "[!Ditto? &parents=`134` &documents=" . $row['id'] . "&tpl=`usedtempchunk`!]";
}//END MAIN LOOP
}//END MAIN ELSE
}//END TV WHILE LOOP
You only seem to use the contentid column from your first query, so you could change it to:
$sql = 'SELECT distinct contentid FROM `table1`'; // rest would be the same
which would mean that no duplicates will be retreived saving you any hassle in changing your second set of code.
If you are using other columns from the first query somewhere else in your code, you can still fetch more columns with this method as long as there are no duplicate IDs:
$sql = 'SELECT distinct contentid, contentTitle, contentThing FROM `table1`';
If you have to have repeated IDs in your original query, I think you will have to store the data in a variable (like an array) and then make sure that the second dataset isn't repeating anything.
It sounds like you're only looking for 1 row, if so, then at the end of your SQL, simply add LIMIT 1. That'll ensure you only return 1 row, thereby ignoring any duplicate matches.