How can I update a database with the values from an array? For example, let’s say we got a database with three tables:
Meals:
mealnr(PK), name, sort
Ingredients: ingredientnr(PK), name, stock
Structure: mealnr(FK), ingredientnr(FK), amount
I filled the database with some meals and ingredients. Every meal consists of multiple ingredients. The chef decides you only need 75g of ingredient x instead of 100g for meal y, so it needs to be changed in the database. Of course it can be done with SQL-commands, but I want to do it using a form in PHP.
First I made a page where all the meals are displayed. A meal can be edited using the edit-button next to it and based on the mealnr, you can change the amount of one or multiple ingredients for that particular meal. On the edit-page all the ingredient names and amounts are displayed in a table. The amount fields are textfields, those can be edited.
I made this script, but I don’t know exactly how I can update my database with the values of an array. I tried it with a foreach-loop, but it doesn't work.. yet. Can somebody help me?
<?php
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db("eatit", $conn);
$id = $_REQUEST['mealnr'];
$result = mysql_query("SELECT meals.name AS mealname, structure.amount, ingredients.name AS ingredientname
FROM Meals, Structure, Ingredients
WHERE meals.mealnr = structure.mealnr
AND structure.ingredientnr = ingredients.ingredientnr
AND meals.mealnr = '$id'");
if(isset($_POST['save']))
{
$new_amount = $_POST['amount[]'];
foreach ($new_amount as $value) {
mysql_query("UPDATE structure SET amount ='$value', WHERE mealnr = '$id'")
or die(mysql_error());
}
}
mysql_close($conn);
?>
<p><strong>Ingredients:</strong></p>
<?php
echo "<table>";
echo "<tr>";
echo "<th>Ingredient</th>";
echo "<th>Amount (gr)</th>";
echo "</tr>";
while($ingredient = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>";
echo $ingredient['ingredientname'];
echo "</td>";
echo "<td>";
echo '<input type="text" formmethod="post" name ="amount[]" value="' . $ingredient['amount'] . '" />';
echo "</td>";
echo "</tr>";
}
?>
<input type="submit" name="save" value="save" />
In your HTML markup you have declared the elements holding the name amount as an array by using amount[].
So, in your php code that receives the data it's enough to just refer to the amounts this way:
$new_amount = $_POST['amount'];
instead of:
$new_amount = $_POST['amount[]']; // in fact, this is wrong
Your foreach is fine, you should add some checks so that the $value actually contains a value that you expect, for example an int, float or not less than zero (or whatever checks you find necessary).
foreach($new_amount as $value){
if($value != '' && $value >= 1){
//sql statements goes here.
}
}
Receiving form data this way and then directly injecting the result to your SQL statement is always dangerous:
$id = $_REQUEST['mealnr'];
If you declare that you expect an integer (as the id's should be) before you directly inject the code to your SQL statement you have already written safer code.
$id = (int)$_REQUEST['mealnr'];
Also, just for the record - the mysql_* library is deprecated. As pointed out in the comments, try using PDO or mysqli instead - really!
Related
I have a bootstrap table which has a form in it, with each row containing a column where the value can be changed from a drop-down box. On clicking the 'Save changes' button, all the rows will be updated with the new values.
The form/table works as intended in normal cases. But if I use the search functionality of the bootstrap table to filter out a few of the rows and then try to update rows with the values, the wrong rows are getting affected.
So from the example in the above image, if I filter out to view just the second row like in the picture below, then the changes, or the 'Update' query is executed on the actual first row, that is to the row which had 'Bob' as the 'technician'.
I'd like to know how to solve this issue.
Here is the relevant code:
foreach($tickets as $tickets)
{
$users = $app['database']->selectAll('users');
echo ("<input type='text' style = 'display:none' value = '$tickets->id' name = 'ticketid[]'>");
echo "<td class = '$technician->color'>$technician->name</td>";
echo "<td>";
echo '<select name = "user[]" id="user" class="form-control">';
echo "<option value = $technician->id>$technician->name</option>";
foreach($users as $users)
{
echo "<option value = $users->id>$users->name</option>";
}
echo "</select>";
echo "</td>";
echo "</tr>";
}
For the database part, I am calling a function transferTask which accepts first the table name, then two arrays, one array containing updated usernames from the dropdown fields and one containing corresponding ids.
transferTask('tickets', $user[$i], $ticketid[$i])
The above function is executed for each row in the table. I think it's an issue wit the name array being passed from the form to this function but I'm not sure. Help is appreciated!
So lately i have been working on a way to post values from a database through checkbox selecting. Thanks to a previous question: How to use checkboxes to retrieve specific data in a database, i managed to get it working!
Although i got it working, i wanted to make my queries a bit more effective when multiple checkboxes are selected instead of writing queries with if/else for every checkbox possibility.
Through some research on stack overflow, this topic in particular: Run a query based on multiple checkboxes, i created the code for my own project. Though, for some reason it just wont output the data correctly, it even wont output anything at all.
So i looked in my code to see where stuff goes wrong. I passed in several echo's to get array information etc, but it all seems ok EXCEPT the last echo where i am echoing the query results (which returns 0).
So i am kinda stuck now since i cant figure out what goes wrong.
NOTE: It is for wordpress so that explains the little difference in querying.*
The code is as follows:
The HTML Code to display the checkboxes
<form method="post">
<div id="list1" class="dropdown-check-list">
<span class="anchor">Select Authors</span>
<ul class="items">
<li><input type="checkbox" name="columns[]" value="Barry" />Barry</li>
<li><input type="checkbox" name="columns[]" value="Henk" />Henk</li>
<li><input type="checkbox" name="columns[]" value="Nicolas" />Nicolas</li>
</ul>
</div>
<input type="submit" name="go" value="Submit"/>
</form>
The ID is for a Jquery dropdown effect.
The PHP code is as follows:
*The code below defines the column titles that are being displayed/echo'd in a table
$column_names = array(
"Authorss" => "Authorss",
"Research_Source" => "Research_Source",
"Research_Title" => "Research_Title"
);
$sql_columns = array();
foreach($column_names as $i) {
$sql_columns[] = $column_names[$i];
}
The next lines of code checks the checked checkbox values and queries the selected values:
if(!empty($_POST['columns'])) { // empty() checks if the value is set before checking if it's empty.
foreach($_POST['columns'] as $key=>$value){
// Runs mysql_real_escape_string() on every value encountered.
$clean_criteria = array_map('mysql_real_escape_string', $_REQUEST['columns']);
// Convert the array into a string.
$criteria = implode("','", $clean_criteria);
}
$tmp = $wpdb->get_results("
SELECT"
.implode(",", $sql_columns)."
FROM
wp_participants_database
WHERE
authorss IN ($criteria)
ORDER BY
authorss ASC
");
}
If non is selected the query selects all possible results (this still has to be created tho since i want the specific select query to work first):
else {
echo 'still needs to be edit to show everything here';
//$tmp = $wpdb->get_results( "SELECT ".implode(",", $sql_columns)." FROM wp_participants_database;");
}
Now comes the part where the queried data is being showed/put in tables:
echo "<table>
<tr>";
foreach($column_names as $k => $v) {
echo "<th>$v</th>";
}
echo "</tr>";
if(count($tmp)>0){
for($i=0;$i<count($tmp);$i++){
echo "<tr>";
foreach($tmp[$i] as $key=>$value){
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
}
echo '</table>';
*****UPDATE*****
Got it fixed myself! First i deleted:
$column_names = array(
"Authorss" => "Authorss",
"Research_Source" => "Research_Source",
"Research_Title" => "Research_Title"
);
$sql_columns = array();
foreach($column_names as $i) {
$sql_columns[] = $column_names[$i];
}
This above code was unnecessary as the columns were all preset, so i just echo'd them by typing them out.
The problem was the following:
$tmp = $wpdb->get_results("
SELECT"
.implode(",", $sql_columns)."
FROM
wp_participants_database
WHERE
authorss IN ($criteria)
ORDER BY
authorss ASC
");
The $criteria variable should give a string to the IN, though in my code it was parsed as an literal (so no string). It seemed very easy, i just had to add the '' so it would be parsed as a string. Result: WHERE authorss IN ('$criteria')
<div>
<?php
$corpServicesValue = $row['corp_services'];
$value= explode(",",$corpServicesValue);
if(in_array("1",$value))echo '<input type="checkbox" name="corporationServices[]" value="1" checked >Management<br>';
?>
</div>
I have a HTML form that retrieves a varying number product types that the user inputs stock figures. This data then needs to be INSERTED to a new table.
Here is the PHP query that populates the form.
require_once 'config.php';
$i = 1;
$sql = "SELECT * FROM dealer_product WHERE customer_code='$custcode' ORDER BY prod_code";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
$prodcode = $row['prod_code'];
echo "<tr><td><input type='text' name='prod".($i++)."' value='" . $prodcode . "'/></td><td><input type='number' name='openstock".($i++)."'/></td><td><input type='number' name='sold".($i++)."'/></td></tr>";
}
mysql_close($con);
?>
I know how to INSERT a set number of multiple records, but how do I INSERT a varying number of records?
Thanks in advance. Sorry for my basic knowledge, I'm a network admin not PHP MYSQL.
Name your input fields as if they were arrays, e.g.:
<input name="prods[0]" />
You can then output a variable number of inputs in your HTML, even add more with JavaScript. PHP will convert the input to an array over which you can iterate:
<?php
foreach ($_POST['prods'] as $prod) {
/* Process $prod */
}
?>
I recommend that you go in the same way but using
while ($row = mysql_fetch_assoc($result))
And now you have not numbers as index that is more complicated way to see things, better see associative way that's the column name from your table in mysql.
And you're doing a lot of increments there doing $i++ a lot of times. I don't know if you're doing that intentionally but if not just increment $i once.
Also the number of row can be reached using this:
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
Look inside the manual
http://us1.php.net/mysql_fetch_assoc
So as said in title I'm trying to use the query variable given from the page which directs to this one and the form data from THIS page to manipulate the database. I can't seem to get it right and I have no idea what I'm doing wrong. The code snippet looks like this:
<?php
$ware_number = $_GET['id'];
Echo "<form action='usernamecheck.php' method='post'>";
Echo 'Username:<br>';
Echo '<input type="text" name="usernamecheck" size="14"><br>';
Echo 'Password:<br>';
Echo '<input type="password" name="passwordcheck" size="14"><br>';
Echo '<input type="submit" value="Send">';
Echo '</form>';
if (isset($_POST['usernamecheck'])) {
$sql2 = "SELECT * FROM `storedata`.`users` WHERE `username` LIKE '$_POST[usernamecheck]'";
$found_user_id = mysql_query($sql2, $conn);
print $found_user_id;
}
if (isset($_POST['usernamecheck'])) {
$sql3 = "INSERT INTO `storedata`.`basket` (user_id, ware_id, number, complete)
VALUES
('$found_user_id', '$ware_number', 1, 0)";
$derp = mysql_query($sql3, $conn);
print $derp;
}
?>
The document itself is usernamecheck.php, and I was just printing to try and locate the error. When i check the basket table nothing has happened, even though no error is displayed. Right now the variable $ware_number is causing errors. What am I doing wrong?
I have also made user_id and ware_id foreign keys in the storedata.basket table, since they are primary keys in their own respective table. This means they can only be specific values, but I'm testing with these values, primarily 1's and 0's...
What if $_GET['id'] is not set? it will fail. Also please read up into correct usage of SQL in PHP. Your code is vulnerable to SQL injection attacks and whatnot.
EDIT:
updated piece of code
if(isset$_GET['id'] && is_numeric($_GET['id']))
{
$ware_number = $_GET['id'];
Echo "<form action='usernamecheck.php?id=" . $_GET['id'] . "' method='post'>";
.....
First of I apologize if this is a dumb question - I'm just starting to pick up my php/mysql skills. I'm making a dropdown form with 3 dropdowns. I want to be able to trigger a query from the form. You select Part Type, Make, Model hit submit and a table of results is displayed.
I have my form populated with 3 arrays and when you hit submit, I can echo the key of each selected item to the page:
echo '<form action="dbBrowse.php" method="post">';
$mak = array (0 => 'Make', 'Ford', 'Freightliner', 'Peterbilt', 'Sterling', 'Mack', 'International', 'Kenworth', 'Volvo');
$mod = array (0 => 'Model', 'Argosy', 'Midliner');
$p = array (0 => 'Part', 'Radiator', 'Charge Air Cooler', 'AC');
echo '<select name="drop1">';
foreach ($p as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '</select>';
echo '<select name="drop2">';
foreach ($mak as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '<select/>';
echo '<select name="drop3">';
foreach ($mod as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '<select/>';
echo '</form>';
//echo keys of selection
echo $_POST['drop1'];
echo "<br />";
echo $_POST['drop2'];
echo "<br />";
echo $_POST['drop3'];
//these echo something like 1, 1, 3 etc. to my page
Where I'm getting lost is I'm looking to take the selected options and insert them into a query something like this:
$dropSearch = mysql_query('SELECT * FROM parts WHERE part= "$partTypeVar" . AND WHERE make = "$makeTypeVar" . AND WHERE model = "$modelTypeVar"');
$partTypeVar being the corresponding value to the key that is being returned from the array.
I'm driving myself crazy trying to figure out how to make that happen. Eventually I want to expand this further but just being able to create a mysql statement with the values selected would make my day right now. I understand the concept of what needs to happen but I'm unsure of how to accomplish it. Any help or pushes in the right direction would be greatly appreciated.
First of all, you have to delete the . char in your SQL query, there's no need to use it for now and of course assign the correct values to the variables.
$partTypeVar = mysql_real_escape_string($_POST['$drop1']);
$makeTypeVar = mysql_real_escape_string($_POST['$drop2']);
$modelTypeVar = mysql_real_escape_string($_POST['$drop3']);
$dropSearch = mysql_query('SELECT * FROM parts WHERE part= "$partTypeVar" AND WHERE make = "$makeTypeVar" AND WHERE model = "$modelTypeVar"');
I am assuming that's the correct order of your variables.
I hope this help!
If I've understood your question, when the form is submitted, you want to query the database with the selected values.
Example using AND:
// Prepare the Query
$query = sprintf(
"SELECT * FROM parts WHERE part='%s' AND make='%s' AND model='%s'",
mysql_real_escape_string($_POST['drop1']),
mysql_real_escape_string($_POST['drop2']),
mysql_real_escape_string($_POST['drop3'])
);
// Execute the Query
mysql_query($query);
This will select all rows from the table parts that match those three values.
Example using OR:
// Prepare the Query
$query = sprintf(
"SELECT * FROM parts WHERE part='%s' OR make='%s' OR model='%s'",
mysql_real_escape_string($_POST['drop1']),
mysql_real_escape_string($_POST['drop2']),
mysql_real_escape_string($_POST['drop3'])
);
// Execute the Query
mysql_query($query);
This will select all rows from the table parts that match any of those three values.
You can read more about this:
mysql_query
mysql_real_escape_string
MySQL 5.6 Reference Manual :: 12 Functions and Operators :: 12.3 Operators
<select name="myFilter">
<option value="Chooseafilter" name="default">Choose a filter...</option>
<option value ="Lastname" name="opLastName">Last Name</option>
<option value="Firstname" name="opFirstName">First Name</option>
<select>
<li><!--TEXT SEARCH INPUT--><input type="text" name="search_filter" /></li>
...
dbconnection();#assume that all connection data is here
...
$filter = $_POST['myFilter']; #
...
switch($filter)
{
case "Lastname":
$selectedoption = "profile_name";
break;
case "Firstname":
$selectedoption="profile_first_name";
break;
case "Chooseafilter":
$selectedoption = "";
break;
}
$result = pg_query($db_con, "SELECT * FROM profile WHERE ".$selectedoption." LIKE'%$_POST[search_filter]%'");
$row = pg_fetch_assoc($result);
if (isset($_POST['submit']))
{
while($row = pg_fetch_assoc($result))
{
echo"<ul>
<form name='update' action='' method='POST'>
<li>Guest Last Name:</li>
<li><input type='text' name='profile_name_result' value='$row[profile_name]' /></li>
<li>Guest First Name:</li>
<li><input type='text' name='profile_first_name_result' value='$row[profile_first_name]' /></li>
<li><input type='submit' value='Update' name='update'></input></li>
...