How to update multiple mysql rows from a form field - php

Hello i am creating a form where i can update multiple rows in my database
first of all i have a form with a field name "pol", this should carry multiple values as declared below using "[]"
<form action="snooze.php" name="frm" method="post">
<input type="checkbox" name="pol[]" value="<?php echo $row_cert['Policy_Number']; ?>">
</form>
This multiple values, i have been able to display using a for each loop
<?php
if (isset($_POST['pol']))
{
$hobby = $_POST['pol'];
foreach ($hobby as $hobys=>$value) {
echo "".$value."<br /><br />";
}
}
?>
but now i am trying to use this multiple values passed in the for each loop in a where clause to update multiple rows in my database, but it only passes 1 value instead of multiple values as the above code does when echo.
this is what i have tried
<?php
if (isset($_POST['pol']))
{
$db = new mysqli('localhost', '---', '----', '----');
if ($db->connect_error) {
die("Connect Error: " .$db->connect_error); //TODO: better error handling
}
$hobby = $_POST['pol'];
foreach ($hobby as $hobys=>$value) {
$sql = "UPDATE check_niid
SET niid_status = 'Successful'
WHERE Policy_Number = '$hobby[$hobys]'";
}
if (!$db->query($sql)) {
die("Update failed. Error: " .$db->error); //TODO: better error handling
}
}
?>
please what could i be doing wrong here, my aim is to be able to update multiple rows using the where clause

your query execution is in out side the foreach so . $sql variable overwrite by multiple times and final array value only set in $sql . that only executed once in your query so .it should be inside the foreach loop
foreach ($hobby as $hobys=>$value) {
$sql = "UPDATE check_niid
SET niid_status = 'Successful'
WHERE Policy_Number = '$hobby[$hobys]'";
if (!$db->query($sql)) {
die("Update failed. Error: " .$db->error); //TODO: better error handling
}
}

Related

Counting Rows to be added and insert into table

I have a script that allows for multiple rows to be created on the page and then I need to have the rows counted on the post and then each row inserted into the table.
I have the GUI working to where users can add or remove rows as needed yet when I submit no data is being written to the table. I have tried altering the script for the post to be straight '$variables' and it works to write but only writes the first row.
I have attached the action script that I am using from WebLesson that works great for one field but for more than one I am at a loss for what to try.
//includes
include '----';
include '---';
session_start();
$number = count($_POST['name']);
echo $_POST['name'] . "<br>";
echo $number . "<br>";
if($number >= 1)
{
echo $_POST['pasid'];
$conn = mysqli_connect($servername, $username, $password, $dbname);
$id = $_POST['pasid'];
$name = $_POST['name'];
$dose = $_POST['dose'];
$dir = $_POST['directions'];
$time = $_POST['time'];
echo $i;
for($i=0; $i<$number; $i++)
{
if(trim($_POST["name"][$i] != ''))
{
$sql = "INSERT INTO meds (id, name, dose, directions)
VALUES('".mysqli_real_escape_string($_POST["pasid"][$i])."',
'".mysqli_real_escape_string($_POST["name"][$i])."',
'".mysqli_real_escape_string($_POST["dose"][$i])."',
'".mysqli_real_escape_string($_POST["directions"][$i])."',
'".mysqli_real_escape_string($_POST["time"][$i])."') " ;
mysqli_query($conn, $sql);
}
}
echo "Data Inserted";
}
else
{
die("Connection failed: " . mysqli_connect_error());
}
I would like this to count how many rows were posted and then submit each row to the table.
Picture of the UI:
You can generate unique name attributes for each form element and then loop through them in PHP. The easiest way to do that would probably be increment a number at the end of the name attribute each time the user creates a new row. You will have to do that with Javascript.
var suffix = 0;
function addNewRow(){
...
<input type="text" name="pasid_${i}"/> //Add incriminating suffix
...
suffix++; //Increment suffix for next time
}
Then your PHP would look like
$suffix = 0;
while(isset($_POST['pasid' . $suffix])){ //Keep looping until no more POST value
//Process row $suffix, referencing all the data like $_POST['field_name'. $suffix]
$suffix++; //Increment suffix for the next field
}
Make sure the field you are checking for in the while loop is required or else the user might omit an input and the loop would terminate prematurely. You could also check multiple $_POST indexes in the while loop if non of the fields are required.

PHP/Mysqli: Why does this code doubles rows insert?

I need a help with my code; somehow my code creates two rooms (it inserts two rows into a table at once), I don't know why.
(I need to require an id for every insert to know in which house we create a new room. My database contains table 'house' and table 'room'. Table 'room' has a field 'house_id' which is a foreign key with a field 'id' in table 'house'.)
That is my php page:
<?php
// turn autocommit off
mysqli_autocommit($con, FALSE);
// fetch the houses so that we have access to their names and id
$query = "SELECT name, id
FROM house";
$result = mysqli_query($con, $query);
// check query returned a result
if ($result === false) {
echo mysqli_error($con);
} else {
$options = "";
// create an option
while ($row = mysqli_fetch_assoc($result)) {
// $options .= "".$row['name']."";
$options .= "<option value='".$row['id']."'>";
$options .= $row['name'];
$options .= "</option>";
}
}
include('templates/add_room.html');
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$price = mysqli_real_escape_string($con, $_POST["price"]);
$house = mysqli_real_escape_string($con, $_POST["house_id"]);
$query = "INSERT INTO room (price, house_id)
VALUES ('$price', '$house')";
// run the query to insert the data
$result = mysqli_query($con, $query);
// check if the query went ok
if ( $con->query($query) ) {
echo "<script type= 'text/javascript'>alert('New room created successfully with the id of {$con->insert_id}');</script>";
mysqli_commit($con);
} else {
echo "There was a problem:<br />$query<br />{$con->error}";
mysqli_rollback($con);
}
}
//free result set
mysqli_free_result($result);
?>
and that is my html template with form:
<h2>Add new room</h2>
<form action='' method='POST'>
<fieldset>
<label for='price'>Price:</label>
<input type='number' name='price'>
</fieldset>
<fieldset>
<label for='house_id'>House:</label>
<select name='house_id' required>
<option value='' disabled selected>Select house</options>
<?php echo $options; ?>
</select>
</fieldset>
<button type='submit'>Add</button>
</form>
It inserts 2 rows because of your using the query function twice:
$result = mysqli_query($con, $query);
// check if the query went ok
if ( $con->query($query) ) {
So you'll need to change that conditional statement to:
if ($result) {
By the way, use a prepared statement, it's safer than real_escape_string():
https://en.wikipedia.org/wiki/Prepared_statement
You are inserting it twice
first here:
// run the query to insert the data
$result = mysqli_query($con, $query);
then here:
// check if the query went ok
if ( $con->query($query) ) {
Remove the first one and you should be fine, or check on the result of the first one and remove the second one.
Not 100% certain, but it looks like you run INSERT query twice. Once here:
$result = mysqli_query($con, $query);
and once a moment later when you try to check for something. you inadvertently use the OOP style when you are apparently trying to check for something
if ( $con->query($query) ) {

Syntax error or access violation: 1103 Incorrect table name with $_POST array data

I have this form
<form action="table_results.php" method="post">
<?php
foreach (get_table($_POST['table']) as $row) { // Fill $row variable with table fields
?>
<input type="text" name="table[ <?php echo $_POST['table'] ?> ][ <?php echo implode($row) // Create table array ?> ]" size="20" >
<?php
}
?>
<p><input type="submit" /></p> <!-- Post the table array to table_results.php -->
</form>
get_table(); returns the field names of the specific table
When I use the posted data for the following function
function search_db($table, $field, $query) {
$database = new Database();
$database->query( "SELECT * FROM `" . $table . "` WHERE `" . $field . "` = :query" );
$database->bind(":query", $query);
$database->execute();
$result = $database->resultSet();
if (!$result) {
print 'ERROR';
die();
} else {
return $result;
}
}
I get the error: "Syntax error or access violation: 1103 Incorrect table name"
I`ve tried to test if the variable contains the right data
$array = $_POST['table'];
$table = implode(array_keys($array));
print $table;
Outcome: computer
When I input 'computer' in the $table variable of - function search_db('computer', 'id', 1); - it works fine
When I print the $table variable along with 'computer' I get the exact same output.
What could be the cause of my database not recognizing the $table variable?
This is probably your problem:
name="table[ <?php echo $_POST['table'] ?> ]
Note that you are adding spaces before and after the variable in the html array, so when you print the result, it will seem correct, but the real result will be " computer " and not "computer". And the " computer " table does not exist.
You can use var_dump() instead of print() to confirm that; it will probably show a length of 10 instead of the 8 for the word computer.
So you would need this instead:
name="table[<?php echo $_POST['table'] ?>]
Apart from that you should really use white-lists for the table- and column names to avoid sql injection and problems like the one you are having now.

No data displayed from DB in drop down menu

Echo 'Hello programmers' ;
I'm scratching my head about a pair of drop down menus. They are supposed to display all strings from the ename and mid rows. However this isn't happening and the drop down is only displaying one result from each row. There are multiple strings of test data in the actual rows.
I have some code here and perhaps you could lend a hand. Let me explain.
First off these are the methods from class dbme. To keep the clutter down the second function is exactly the same, except the SQL query for getResult() is obviously different (SELECT * from member as opposed to memberevent)
function openDB() {//creating database connection
$conn = mysqli_connect("localhost", "root", "", "mydb");
if (!$conn) {
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
function getResult($sql){
$result = mysqli_query($this->conn , "SELECT * from memberevent" );
if ($result) {
return $result;
} else {
die("SQL Retrieve Error: " . mysqli_error($this->conn));
}
}
Second, this is the web-side data.
$db1 = new dbme();
$db1->openDB();
$sql="select mid from member";
$result=$db1->getResult($sql);// get the ids from the tables for the select
$sql1="select ename from event";
$result1=$db1->getResult($sql1);// get the ids from the tables for the select
if (!$_POST) //page loads for the first time
{
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" onsubmit="return validateForm( );">
Select Member ID: <select name="mid">
<?php
while($row = mysqli_fetch_assoc($result))
echo "<option value='{$row['mid']}'>{$row['mid']} </option>";
?>
</select>
<br />
Select Event name : <select name="ename">
<?php
while($row = mysqli_fetch_assoc($result1))
echo "<option value='{$row['ename']}'>{$row['ename']} </option>";
?>
</select>
<br />
I have a sneaking suspicion that a variable is getting over written, OR an extra loop is needed somewhere. But I'm not really sure, thus I post this question for advice.
Thanks.
You need to iterate through your results inside your getResults() function, otherwise you will always only get one row.
You are passing in the SQL but never using it:
Change
function getResult($sql){
$result = mysqli_query($this->conn , "SELECT * from memberevent" );
To
function getResult($sql){
$result = mysqli_query($this->conn , $sql );

sending multiple records to MySQL from multiple select box

I'm trying to insert multiple rows into a MySQL table depending on the number of options selected from a multiple select box. currently it is inserting one row (regardless of how many options are selected) but the 'strategyname' column is empty each time.
Any ideas on how to insert multiple rows and why the values of the options aren't being sent to the table?
Here is the form:
<form method="POST" action="update4.php">
<input type="hidden" name="id" value="1">
<p class="subheadsmall">Strategies</p>
<p class="sidebargrey">
<?php
$result = mysql_query("SELECT strategyname FROM sslink WHERE study_id = '{$_GET['id']}'");
if (!$result) {
die("Database query failed: " . mysql_error());
}
while($row = mysql_fetch_array($result)) {
$strategyname = $row['strategyname'];
echo $strategyname.'<br />';
}
?>
<p class="subheadsmall">Add a strategy... (hold down command key to select more than one)</p>
<select name="strategylist" multiple="multiple">
<?php
$result = mysql_query("SELECT * FROM strategies");
if (!$result) {
die("Database query failed: " . mysql_error());
}
while($row = mysql_fetch_array($result)) {
$strategylist = $row['name'];
$strategyname = htmlspecialchars($row['name']);
echo '<option value="' . $strategylist . '" >' . $strategyname . '</option>' . '\n';
}
?>
</select>
</p>
<input type="submit" class="box" id="editbutton" value="Update Article">
</form>
And this is what sends it to the database:
<?php
$id=$_POST['id'];
$test=$_POST['strategylist'];
$db="database";
$link = mysql_connect("localhost", "root", "root");
//$link = mysql_connect("localhost",$_POST['username'],$_POST['password']);
if (! $link)
die("Couldn't connect to MySQL");
mysql_select_db($db , $link) or die("Select Error: ".mysql_error());
//for($i=0;$i<sizeof($_POST["test"]);$i++)
//{
//$sql = "insert into tbl_name values ($_POST["test"][$i])"; }
//sql = "INSERT INTO table_name VALUES ('" . join(",",$_POST["test"]) . "')";
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) VALUES ('$id','" . join(",",$_POST["strategylist"]) . "')")or die("Insert Error: ".mysql_error());
mysql_close($link);
print "Record added\n";
?>
Couple of points:
your select needs to be named strategylist[] in order to tell PHP that it will contain an array rather than a single value
Your insert code then needs to iterate over that array, creating a new insert for each element it contains, unless (as it seems) you want all those options to be concatenated into a single row's field.
At the moment, your form only returns a single option (from PHP's perspective), so it's only going to insert a single row.
To iterate over the array, use something like this:
foreach($_POST["strategylist[]"] as $s) {
# do the insert here, but use $s instead of $_POST["strategylist[]"]
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) " .
"VALUES ('$id','" . join(",",$s) . "')")
or die("Insert Error: ".mysql_error());
}
Two things:
If you view the source of page with the multiple select in it, can you see the <option value="something"> lines there? Are the values empty? It seems strange to me that at the top of your file you are using $row['strategyname'] and later you are using $row['name']. I suspect this may be the cause of the empty StrategyName column.
To handle multiple selections, you should specify the select tag as
<select name="strategylist[]" multiple="multiple">
The extra [] tells PHP to form an array with all of the selections in it. You can then loop over the array like:
$strategylist = $_POST['strategylist'];
for ($i = 0; $i < count($strategylist); $i++) {
$strategyname = $strategylist[$i];
// Insert a record...
}
// first you need to define your output as one variable if you don't like the loop
if($_POST){
$sum = implode(", ", $_POST[select2]);
echo $sum.".";
}
// the variable sum is the one you are seeking for you can insert it to the database
// if you want to enter every peiece of the array in a new field you should use
// different select names

Categories