Inserting multiple entries into table from the same form - php

This is my form, a pretty simple one. I have 3 text fields in which questions will be entered and i want to put each of these in a database.
questFormtest.php:
<html>
<head><title> Test Quest</title></head>
<body>
<form id= "qform" method="post" action="quest.php">
<h3>Enter Questions</h3><br><br>
<h3>Question 1: Five marks each.<br></h3>
a) <input type="text" name="field1[][field1]" size=45>* <br><br>
b) <input type="text" name="field1[][field1]" size=45>* <br><br>
c) <input type="text" name="field1[][field1]" size=45>* <br><br>
<p><input type="submit" name="submit" value="Submit" align="center" />
<input type='reset' name='Cancel' value='Cancel' /></p>
</form>
</body>
</html>
My php file is as follows:
quest.php:
<?php
include('connectionfile.php');
$cnt = count($_POST['field1']);
if ($cnt > 0) {
$insertArr = array();
for ($i=0; $i<$cnt; $i++) {
$insertArr[] = "('" .$_POST['field1'][$i]. "')";
}
$query = "INSERT INTO paper (field1) VALUES " . implode(", ", $insertArr);
mysql_query($query) or trigger_error("Insert failed: " . mysql_error());
}
mysql_close($id_link);
?>
When i run the file, it gives me the following error:
Insert failed: Unknown column 'field1' in 'field list' in quest.php on line 15
Can somebody tell me if there's an error in the query and how i can solve it? Any help is appreciated :)

The posted value is in this index: $_POST['field1'][$i]['field1']. So you use this code : $insertArr[] = "('" .$_POST['field1'][$i]['field1']. "')" in you for loop;

Related

How to insert multi text box values into sql using php?

<?php
$conn=mysqli_connect("localhost","root","","fesdb");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
if (isset($_POST['Insert']))
{
$txt = $_POST['text1'];
}
{
$query = "insert into table (Mytext) VALUES ('$txt')";
$result = mysqli_query($conn,$query);
if($result)
{
echo '<script>alert("record inserted")</script>';
}
else
{
echo ' Please Check Your Query ';
}
}
?>
<html>
<body>
<form action="" id="myForm" >
<input type='text' name="text1"><br>
<input type='text' name="text2"><br>
<input type='text' name="text3"><br>
<input type='text' name="text4"><br>
<input type='text' name="text5"><br>
<input type='text' name="text6"><br>
<input type='text' name="text7"><br>
<input type='text' name="text8"><br>
<input type='text' name="text9"><br>
<input type='text' name="text10"><br>
<input type='submit' name="Insert">
</form>
</body>
</html>
I am a beginner in PHP .. I have sql database with one Table , this table have one column .... I have 10 textboxes in my page with one button ... I want to insert each textbox into the table as separated record ... I know I should use loop (for each ...) to solve this problem ... but I dont know how do that ...
if possible help me with a sample

Inserting an array of checkbox values into a database including unchecked

In the form below, students are selected from student table in my DB. For each student selected a checkbox is checked if the student is absent and left unchecked if the student is present. The form is later on submitted for it to be inserted in the exam_status table in my DB.
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
while($row= $result->fetch_assoc())
{
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="matricule[]" value="<?php echo "$studentmatricule)"; ?>" readonly>
<label>Name</label>
<input type="text" name="name[]" value="<?php echo "{$studentname} {$studentsurname}"; ?>" readonly>
<label > Absent
<input type="checkbox" name="absent[]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
</form>
and my action page "action.php" is as follows
$matricule = $_POST['matricule'];
$absent=$_POST['absent'];
for ($i=0; $i<sizeof($matricule); $i++)
{
if($absent[$i]=='absent')
{
$status='absent';
}else{
$status='present';
}
$query = "INSERT INTO exam_status (student_matricule,status) VALUES ('". $matricule[$i] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
Now the issue is it doesn't just work as i want. the result always gives the first student absent and the rest present. I have tried all i can and have really researched too but with no success at all. Please anyone around to help me out?
Thanks in advance!
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
$index = 0;
while($row= $result->fetch_assoc())
{
$index++;
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][matriculate]" value="<?php echo $studentmatricule; ?>" readonly>
<label>Name</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][name]" value="<?php echo $studentname." ".$studentsurname; ?>" readonly>
<label > Absent
<input type="checkbox" name="studenInfo[<?php echo $index; ?>][status]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
Update your mail file like this. I have changed the form names into a single array. The reason is the checkbox values won't post to the page when the values are not checked. So its not possible to track which one was checked and which is not if you have same name.
And update your action.php like this,
<?php
$conn = mysqli_connect("localhost","username","password","db_name"); // update this values as per your configuration
$studenInfo = (!empty($_POST['studenInfo'])) ? $_POST['studenInfo'] : [];
foreach($studenInfo as $value ) {
$status = (isset($value['status'])) ? 'absent' : 'present';
$query = "INSERT INTO exam_status (student_name, student_matricule,status) VALUES ('". $value['name'] . "','". $value['matriculate'] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
?>
I have used my own table schema where i have added student_name in exam_status table for better tracking. Now you can see the values updating correctly. Also we can use bulk insert if we need to insert multiple data (Note : I haved used the bulk insert in this answer, i just followed the way you used)

search for a specific row in MySQL using PHP

I'm trying to verify my search box (html) using php code
but in all times it gives all rows I dont know where is the problem
html code:
<form action="searchHotel.php" method="post">
<input value="Hotel's Name" type="text" name="Hotels_Name" id="dropdownlist" style="width:150px; hight:10px;">
</form>
</br>
<br/>
<button style = " margin-top:2%; position:relative;" type="button" onClick="location.href='searchHotel.php'" method="post" action="searchHotel.php">GO</button>
<br/><br/>
a peice of php code:
//code
echo $_POST['Hotels_Name'];
$n = (string) $_POST['Hotels_Name'];
$variable = (string)$n;
$query = "SELECT * FROM facility WHERE name LIKE '%$variable%'";
$result = mysql_query($query) or die('Query failed: ' . mysql_error() . "<br />\n$sqlquery");
$number = mysql_num_rows($result);
echo $number;
$row = mysql_fetch_assoc($result);
print_r($row);
I have already connected the database
Correct your html code use below code. In your code there is no proper form action onto form. So try below html code. Also try mysqli for database operations in php code.
<form action="searchHotel.php" method="post">
<input type="text" name="Hotels_Name" id="dropdownlist" style="width:150px; hight:10px;">
<input style = " margin-top:2%; position:relative;" type="submit" value="GO" >
</form>

Can $_POST differentiate between two elements with the same name?

New to PHP and reading through Robin Nixon's PHP, MySQL, Javascript book. I am having trouble with an example of inserting and deleting data using a PHP script, specifically with how the author uses $_POST.
The example is a pretty simple add records/delete records of books with multiple inputs. Here's the code:
if (isset($_POST['delete']) && isset($_POST['isbn']))
{
$isbn = get_post('isbn');
$query = "DELETE FROM classics WHERE isbn='$isbn'";
if (!mysql_query($query, $db_server))
echo "DELETE failed: $query<br />" .
mysql_error() . "<br /><br />";
}
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$category = get_post('category');
$year = get_post('year');
$isbn = get_post('isbn');
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$category', '$year', '$isbn')";
if (!mysql_query($query, $db_server))
echo "INSERT failed: $query<br />" .
mysql_error() . "<br /><br />";
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Category <input type="text" name="category" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="isbn" value="$row[4]" />
<input type="submit" value="DELETE RECORD" /></form>
_END;
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
When you refer to an element in $_POST with if (isset($_POST['delete']) && isset($_POST['isbn'])), where delete and isbn are used as names multiple times, how does $_POST know which element to reference to delete? I assume that since you can only delete one record at a time, the element in the array will automatically point to the one that's already set. However, how does the second condition of isset($_POST['isbn']) know which "isbn" element to check for? Does the && make the $_POST['isbn'] "inherit" the correct row?
Thanks for the help! And apologies for any possible misuse of the vocab. Still getting used to everything.
Your question is actually well thought out. And the example given in the book seems quite sloppy to me. I am assuming in later chapters he will delve into the use of arrays in $_POST values. But anyway, here is the key to the functionality of the whole script:
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="isbn" value="$row[4]" />
<input type="submit" value="DELETE RECORD" /></form>
_END;
}
See that <form action="sqltest.php" method="post">? And see that closing </form>? And note that they are being rendered each time the for ($j = 0 ; $j < $rows ; ++$j) loop happens? There is one individual form element for each line. That is messy code, but it works. When one clicks submit on each individual listing, the wrapping form responds & parses the variables nested inside it.
Like I said, sloppy code. But works. And it’s because if you have 30 ISBNs listed this program will spit out 30 individually wrapped <form> items. Uggh! Seriously if the book does not address arrays later on in a way that addresses this face-palm of a coding mess find a new book.
Since there are multiple forms, the input elements of only one form are submitted.
So basically, sqltest.php receives only one array of $_POST containing ['delete'] and ['isbn'] with the corresponding values only once.
You can check this out by using print_r($_POST) in sqltest.php.

PHP Form that updates multiple form element to different columns

I am trying to build a simple form that will update my mySql database.
I can succeed if I only have 1 form element (input) on the page but I can not figure out how to have more than one form element (inputs) per pgae.
When I add more than one input the database will not add any of the content.
I know that my code is close, but I am at a loss as the exactly where and what to do about it.
P.S. - I am still new to this and am learning ...
Here is what I have
<?php
$host = 'hostName';
$user = 'userName';
$password = 'password';
$link = mysql_connect($host, $user, $password);
$selected = mysql_select_db('dbName', $link);
if(!isset($_POST['text-input']))
{
echo '<html>
<body>
<form action="post.php" method="post">
<input type="text" name="text-input" id="text-input" value="Update MyDataColumn" style="width:300px;" />
<input type="submit" value="Submit" />
</form>
</body>
</html>'; }
else {
$form_input = $_POST['text-input'] ;
mysql_query('INSERT INTO `tableName` (columnName) VALUES ("' . $form_input . '");');
echo '
<html>
<body>
<script type="text/javascript">
alert(\'Database now contains: <?php echo $form_input ?>. Redirecting...\');
window.location = \'http://url.com\';
</script>
</body>
</html>';
}
?>
I would like to sort out how to post to numerous columns within the same db/table.
Ok, from the answers below I have modified the code to look like this:
<?php
$host = 'dbHost';
$user = 'dbUser';
$password = 'dbPassword';
$link = mysql_connect($host, $user, $password);
$selected = mysql_select_db('dbName', $link);
if(!isset($_POST['text-input']))
{
echo '
<form action="index.php" method="post">
<input type="text" name="text-input" id="text-input" value="Update itemName" style="width:300px;" />
<input type="text" name="text-input2" id="text-input2" value="Update itemDescription" style="width:300px;" />
<input type="text" name="text-input3" id="text-input3" value="Update productID" style="width:300px;" />
<input type="text" name="text-input4" id="text-input4" value="Update itemPrice" style="width:300px;" />
<input type="submit" value="Submit" />
</form>'
; }
else {
$form_input = $_POST['text-input'] ;
$form_input2 = $_POST['text-input2'] ;
$form_input3 = $_POST['text-input3'] ;
$form_input4 = $_POST['text-input4'] ;
mysql_query('INSERT INTO `items` (itemName, itemDescription, productID, itemPrice)
VALUES ("' . $form_input . '", "' . $form_input2 . '", "' . $form_input3 . '", "' . $form_input4 . '");
echo '
<html>
<body>
<script type="text/javascript">
alert(\'Database has been updated. Redirecting to previous url.\');
window.location = \'http://url.com\';
</script>
</body>
</html>';
}
?>
What happens with this code is I get a
syntax error, unexpected '>'
You just have to modify your query to set multiple columns.
HTML:
<form action="post.php" method="post">
<input type="text" name="text-input" id="text-input" value="Update MyDataColumn" style="width:300px;" />
<input type="text" name="text-input2" id="text-input2" value="Update MyDataColumn2" style="width:300px;" />
<input type="text" name="text-input3" id="text-input3" value="Update MyDataColumn3" style="width:300px;" />
<input type="submit" value="Submit" />
</form>
PHP:
$form_input = $_POST['text-input'] ;
$form_input2 = $_POST['text-input2'] ;
$form_input3 = $_POST['text-input3'] ;
mysql_query('INSERT INTO `tableName` (columnName, columnName2, columnName3) VALUES ("' . $form_input . '","' . $form_input2 . '","' . $form_input3 . '");');
In your HTML output you need to add another field like this one (already in your code):
<input type="text" name="text-input" id="text-input"
value="Update MyDataColumn" style="width:300px;" />
BUT, it must have a different "name" (!);
<input type="text" name="text-input2" id="text-input2"
value="Another Input" style="width:300px;" />
Now we fetch the new variable ("text-input2") out of the $_POST array like this:
$form_input = $_POST['text-input']; // Your code...
$form_input2 = $_POST['text-input2']; // for the new input field
And we need to change the SQL command to this:
mysql_query('INSERT INTO `tableName` (columnName) VALUES ("' . $form_input . '");
mysql_query('INSERT INTO `tableName` (columnName) VALUES ("' . $form_input2 . '");
The above SQL command would add both form inputs as a seperate row in your table, they are not connected to eachother.
To have them in the same row you need to change your table first and add another column to it. The SQL command for that is:
ALTER TABLE tableName ADD columnName2 VARCHAR(255);
This will add another column named 'columName2' to the table. And we finally can add both values as one row of the table:
mysql_query('INSERT INTO `tableName` (columnName, columName2)
VALUES ("' . $form_input . '", "' . $form_input2 . '");
That's it ;-)

Categories