Insert multiple records into database - php

I have a form that enables the user to insert multiple data into the database. I have been trying to insert them but to no avail.
Below is the form
<tr>
<td>
<select title = "Please choose" name="menutype[]">
<option value="-1" >--Select--</option>
<?php
$query = "SELECT * FROM MenuType";
$result = $mysqli->query($query);
if ($result==false) {
die( mysqli_error($mysqli));
}
while ($menutype = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $menutype['MenuTypeID'] ?>"><?php echo $menutype['MenuTypeName'] ?></option>
<?php
}
?>
</select>
</td>
<td><input type="text" name="name[]" /></td>
<td><input type="file" name="picture[]" /></td>
<td><textarea rows="4" cols="40" name="description[]"></textarea></td>
<td><input type="text" name="price[]" value=""/></td>
<td>
<select title="Please choose" name="status[]">
<option value="-1" />--Select--</option>
<option value="Available" />Available</option>
<option value="Limited" />Limited</option>
</select>
</td>
</tr>
Below is the php code
$name = $_POST['name'];
$description = $_POST['description'];
$price = $_POST['price'];
$status = $_POST['status'];
$menutypeid = $_POST['menutype'];
if(isset($_FILES['picture'])){
$name_array = $_FILES['picture']['name'];
$tmp_name_array = $_FILES['picture']['name'];
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "images/menu/".$name_array[$i])){
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]. "<br>";
}
}
$imageup = $tmp_name_array; // save the whole url address of the uploaded file into variable
foreach ($name as $value){
$query = "INSERT INTO menu (MenuID, MenuName, MenuPicture, MenuDescription, MenuPrice, MenuStatus, MenuTypeID)
VALUES ('', '$name', '$imageup', '$description', '$price', '$status', '$menutypeid' )";
$mysqli->query($query) or die(mysqli_error($mysqli));
//header('Location:view_menu_for_manager.php');}}
?>
I also have trouble uploading multiple files/images. Help
edited query
foreach ($name as $value){
$query = "INSERT INTO menu (MenuName, MenuPicture, MenuDescription, MenuPrice, MenuStatus, MenuTypeID)
VALUES ('$name', '$imageup', '$description', '$price', '$status', '$menutypeid' )";

try like this
<?php
$name = $_POST['name'];
$description = $_POST['description'];
$price = $_POST['price'];
$status = $_POST['status'];
$menutypeid = $_POST['menutype'];
$data= array('name'=>$name,
'description'=>$description,
'price'=>$price,
'menutypeid'=>$status ,
'status'=>$menutypeid);
if(isset($_FILES['picture'])){
$name_array = $_FILES['picture']['name'];
$tmp_name_array = $_FILES['picture']['name'];
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "images/menu/".$name_array[$i])){
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]. "<br>";
}
}
$imageup = $tmp_name_array; // save the whole url address of the uploaded file into variable
$i=0;
foreach($data as $value){
$name=$value[$i]['name'];
$description=$value[$i]['description'];
$price=$value[$i]['price'];
$status=$value[$i]['status'];
$menutypeid=$value[$i]['menutypeid'];
$query = "INSERT INTO menu (MenuName, MenuPicture, MenuDescription, MenuPrice, MenuStatus, MenuTypeID)
VALUES ('$name', '$imageup', '$description', '$price', '$status', '$menutypeid' )";
$mysqli->query($query) or die(mysqli_error($mysqli));
//header('Location:view_menu_for_manager.php');}
}
?>
Remove foreach because you are getting only one row from html form. I think there is no need of foreach. Echo each variable before inserting into database just to check that you are getting corrct value or not.
Please check this link.
Link

Related

how to auto increment an input name in html and save in database?

I have a table named positions. This table has the list of the different positions that the admin has added in the listOfPositions.php like President, Vice-President, etc. After adding different positions, he can now add the different people under that position. And that's where my problem is. How will I have an auto increment input name for the names of the people depending on how many positions it has in the table positions ?
I tried using javascript, but it increments only in the html and not reflecting to the php when I try to save. My current code where the adding of the names of different persons depending on the position is the ff:
<script type="text/javascript" src="http://code.jquery.com/jquery-git.js"></script>
<form action="post_officers.php" method="post"><br>
<center><select name="year">
<?php
for($i=date('Y'); $i>1999; $i=$i-2) {
$selected = '';
$year2 = $i-2;
if ($year == $i) $selected = ' selected="selected"';
echo ('<option value="'.$year2. "-" . $i .'" '.$selected.'> '.$year2.'-'.$i.'</option>'."\n");
}
?>
</select></center>
<?php
include_once('dbcontroller.php');
$sql = "SELECT * FROM positions ORDER BY pos_id ASC";
$result = mysqli_query($conn, $sql);
/* assign an onchange event handler */
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<br><br>
<table id="options-table">
<tr>
<td><input type="file" name="file" /></td>
<td><input type="hidden" name="position" /><?php echo $position; ?></td>
<td><input type="text" name="name" /></td>
</tr>
</table>
<?php
}
?>
<input type="submit" name="submit" value="SAVE"/>
</form>
<script>
$("input[name='file']").each(function(ind) {
$(this).attr(ind + 1);
});
$("input[name='position']").each(function(ind) {
$(this).attr(ind + 1);
});
$("input[name='name']").each(function(ind) {
$(this).attr(ind + 1);
});
</script>
And this is my php code:
<?php
include ('dbcontroller.php');
date_default_timezone_set('Asia/Manila');
$year = mysqli_real_escape_string($conn,$_POST['year']);
if(isset($_POST['submit'])) {
$result = mysqli_query($conn,"SELECT * FROM officers WHERE year = '$year'");
$num_rows = mysqli_num_rows($result);
if($num_rows>0){
echo "<script type='text/javascript'>alert('Year already exists.'); window.location.href='create_alumni_officers.php';</script>";
}
else {
for ($i = 1; $i <= 8; $i++) {
$name = mysqli_real_escape_string($conn,$_POST['name'.$i]);
$position = mysqli_real_escape_string($conn,$_POST['position'.$i]);
$file=(rand(1000,100000)."-".$_FILES['file'.$i]['name']);
$type=($_FILES['file'.$i]['type']);
$size=$_FILES['file'.$i]['size'];
$loc=($_FILES['file'.$i]['tmp_name']);
$new_size=$size/1024; // file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($loc, '../officers-avatars/'.$final_file)) {
echo "Page is loading, please wait...";
$result = mysqli_query($conn,"INSERT INTO officers VALUES (id, '$year', '$position', '$name', '$final_file', '$new_size', '$type')")
or die(mysqli_error($conn));
echo ("<script type='text/javascript'>window.location.href='alumni_officers.php';</script>");
}
}
}
}
?>
And this doesn't work at all. Any help? I hope you guys understood what I'm trying to ask.
This is the best way to do it:
<?php
include_once('dbcontroller.php');
$sql = "SELECT * FROM positions ORDER BY pos_id ASC";
$result = mysqli_query($conn, $sql);
/* assign an onchange event handler */
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<table id="options-table">
<tr>
<td><input type="file" name="file[<?php echo $position; ?>]" /></td>
<td><input type="hidden" name="position[<?php echo $position; ?>]" value="<?php echo $position; ?>" /><?php echo $position; ?></td>
<td><input type="text" name="name[<?php echo $position; ?>]" /></td>
</tr>
</table>
<?php
}
?>
You don't need the javascript to change input attributes. Remove it.
In php use foreach loop like:
If you are still getting errors I will need to see the output of print_r($_POST);
<?php
$files = $_FILES['file'];
$positions = $_POST['position']; //use this for the foreach loop because it will always have a value
$names = $_POST['name'];
foreach($positions as $key=>$position){
$file = #$files[$key];
$name= #$names[$key];
//Do your magic for each user here
$name = mysqli_real_escape_string($conn,$name);
$position = mysqli_real_escape_string($conn,$position);
$filename = rand(1000,100000)."-".$file['name'];
$type = $file['type'];
$size = $file['size'];
$loc = $file['tmp_name'];
$new_size=$size/1024; // file size in KB
// make file name in lower case
$new_file_name = strtolower($filename);
// make file name in lower case
$final_file = str_replace(' ','-',$new_file_name);
if(move_uploaded_file($loc, '../officers-avatars/'.$final_file)) {
echo "Page is loading, please wait...";
$result = mysqli_query($conn,"INSERT INTO officers VALUES (id, '$year', '$position', '$name', '$final_file', '$new_size', '$type')")
or die(mysqli_error($conn));
echo ("<script type='text/javascript'>window.location.href='alumni_officers.php';</script>");
}
}
?>
As I indicated in the contents, removing context switches miss fide will greatly increase the readability of your code. I'll illustrate below a bit as well as answer the question.
To get what you're after, you could do this:
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<br><br>
<table id="options-table">
<tr>
<td><input type="file" name="file" /></td>
<td><input type="hidden" name="position" /><?php echo $position; ?></td>
<td><input type="text" name="name<?php echo $position; ?>" /></td>
</tr>
</table>
<?php
}
However, to illustrate a small example of removing these contextual switches mid code, see below and pardon but this is air code, if you want a more specific example, just ask.
Let's say you often use the tag thoughout your site in forms. You could drop out of php each time and just write out the straight html. Or, you could create a class, or even a simple function for the html output thusly:
Function opt($int, $parms = '') {
Return '<Option '.$parms.'>'. $int.'</option>';
}
Now your code would look more like this:
While ($r =mysqli_fetch_array ($result)) {
Extract ($r); // learn this, no sense assigning them 1 by 1
$options .= opt($databaseobject, 'name="foo" value="'. $databaseobjectid.'"');
}
Echo $options;

how to insert html table data into mysqli database in single command

I am using a HTML table form to collect data from users. The rows of the table can be increased by clicking ADD MORE button or can be decreased by clicking DELETE button. So the number of rows in the table are not fixed for all users. Sometimes it would be only 4 rows, sometimes it can be 12 rows. I am wondering how can i insert all data(rows) in my mysqli database by clicking SUBMIT button just once. you can check my table in below link :
Demo in JsFiddle
my php code:
<?php
$email = $_SESSION["email"];
$cell = "Select `cellno` FROM `userreg` WHERE email = '$email'";
$result = mysqli_query($conn, $cell);
$cellno = "";
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
$cellno = $row["cellno"];
}
}
if(isset($_POST['submit']))
{
$fullname = $_SESSION["fullname"];
$medname = $_POST['medname'];
$medqty = $_POST['medqty'];
$medtype = $_POST['medtype'];
$num = $_POST['num'];
$date = date("Y.m.d");
$medorder = "INSERT INTO `medorder` (`fullname`, `phoneno`, `medname`, `quantity`, `medtype`, `date`,`orderno` ) VALUES ('$fullname', '$cellno', '$medname','$medqty', '$medtype', CURRENT_TIMESTAMP, '$num' )";
if($conn->query($medorder)=== TRUE)
{
echo"<br>";
echo " Your Question has been submitted successfully";
}
else
{
echo " Error!! Try again or later";
}
}
?>
First Change the names of your inputs:
<TR>
<TD><INPUT type="checkbox" name="chk"/></TD>
<TD><input type="hidden" value="1" name="num[]" id="orderdata">1</TD>
<TD><INPUT type="text" name="medname[]" class="form-control" id="orderdata" placeholder="Your Medicine name"/></TD>
<TD><INPUT type="text" name="medqty[]" class="form-control" id="orderdata" placeholder="Quantity" /></TD>
<TD>
<SELECT name="medtype[]" class="form-control" id="orderdata">
<OPTION value="in">Bangladesh</OPTION>
<OPTION value="de">Germany</OPTION>
<OPTION value="fr">France</OPTION>
<OPTION value="us">United States</OPTION>
<OPTION value="ch">Switzerland</OPTION>
</SELECT>
</TD>
</TR>
Then built your query by looping throught number of rows in the table.
$medorder='';
foreach ($medname as $key => $value) {
$medorder .= "INSERT INTO `medorder` (`fullname`, `phoneno`, `medname`, `quantity`, `medtype`, `date`,`orderno` ) VALUES ('$fullname', '$cellno[$key]', '$medname[$key]','$medqty[$key]', '$medtype[$key]', CURRENT_TIMESTAMP, '$num' ),";
}

Second form submit button seems to be skipped(?) PHP / HTML

I need help about this, I have a PHP page, which searches for records, based on their first and last names, if sql finds the data then the second form comes out, which has lots of textboxes, to update the 'searched'information. And when I click the submit button of the second form , it does nothing, and even if I have syntax or whatever errors I have put on condition if(isset($_POST['submit'])), they end up being disregarded (no error messages will come up), after clicking the submit button, it just goes back to the page's original state, when it has to update the record I have searched for that was just edited. What exactly is the mistake on this part?
class.php - .php file that contains the operations for sql
<? php
$months = array('January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December');
class EmployeeProfile {
public
function openConnection() {
$conn = mysqli_connect("localhost", "root", "", "db_employee");
if (mysqli_connect_errno()) {
echo "Failed to connect to database server";
}
return $conn;
}
public
function insert($query) {
if (mysqli_query($this - > openConnection(), $query) == 1) {
echo "Profile successfully registered!";
} else {
echo "Register failed";
}
}
public
function display($query) {
$result = mysqli_query($this - > openConnection(), $query);
echo "<br><br>";
if ($result - > num_rows == 1) {
while ($row = $result - > fetch_assoc()) {
echo "<table>";
echo "<tr><td><b>First Name</b>: ".$row["firstname"]."</td></tr>";
echo "<tr><td><b>Middle Name</b>: ".$row["middlename"]."</td></tr>";
echo "<tr><td><b>Last Name: </b>".$row["lastname"]."</td></tr>";
echo "<tr><td><b>Date of Birth: </b>".$row["dateofbirth"]."</td></tr>";
echo "<tr><td><b>Age: </b>".$row["age"]."</td></tr>";
echo "<tr><td><b>School: </b>".$row["school"]."</td></tr>";
echo "<tr><td><b>Highest Educational Attainment: </b>".$row["educ"]."</td></tr>";
echo "<tr><td><b>Year Last Attended: </b>".$row["yearattended"]."</td></tr>";
echo "<tr><td><b>Skills: </b>".$row["skills"]."</td></tr>";
echo "<tr><td><b>Previous Company: </b>".$row["prevcompany"]."</td></tr>";
echo "<tr><td><b>Position: </b>".$row["position"]."</td></tr>";
echo "<tr><td><b>Date of Employment:</b> ".$row["dateofemployment"]."</td></tr>";
echo "</table>";
}
} else
{
echo "Profile not found";
}
}
public
function edit($query) {
$result = mysqli_query($this - > openConnection(), $query);
}
}
?>
edit.php - the page itself.
<html>
<title> Edit Profile</title>
<body>
<form method="post" action="?" name="searchform">
<center>
<table>
<tr><td>Enter first or last name</td><td><input type = "text" name="search"><td><td><input type = "submit" value="Search" name="search2"></td></tr>
</form>
</table>
<?php
include("class.php");
if(isset($_POST['search2'])):
$status = "hidden";
$query = "select * from employee WHERE firstname='".$_POST['search']."' OR lastname='".$_POST['search']."' ";
$emp = new EmployeeProfile();
$emp->openConnection();
$result = mysqli_query($emp->openConnection(), $query);
if($result->num_rows == 1):
?>
<form method="post" action="?" enctype="multipart/form-data" name="updateform">
<table>
<tr></tr>
<tr><td></td><td>Edit your profile:</td></tr>
<tr></tr>
<tr><td>*Enter first name:</td><td><input type="text" name="firstname"></td></tr>
<tr><td>Enter middle name:</td><td><input type="text" name="middlename"></td></tr>
<tr><td>*Enter last name:</td><td><input type="text" name="lastname"></td></tr>
<tr>
<td>*Date of Birth:</td><td><select name="month"><?php for($i = 0; $i < count($months); $i++) { echo "<option value=".$months[$i]." >".$months[$i]."</option>" ; }?></select></td>
<td><select name="days"><?php for($i = 1; $i <= 31; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
<td><select name="year"><?php for($i = 1950; $i <= 2014; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
</tr>
<tr><td>*Age:</td><td><input type="text" name="age"></td></tr>
<tr><td>*School:</td><td><input type="text" name="school"></td></tr>
<tr><td>*Highest Educational Attainment:</td><td><input type="text" name="educ"></td></tr>
<tr><td>*Year Last Attended:</td><td><input type="text" name="yearattended"></td></tr>
<tr><td>*Skill(s):</td><td><input type="text" name="skills"></td></tr>
<tr><td>Previous Company:</td><td><input type="text" name="prevcompany"></td></tr>
<tr><td>Position:</td><td><input type="text" name="position"></td></tr>
<tr><td>*Date of Employment:</td><td><select name="empmonth"><?php for($i = 0; $i < count($months); $i++) { echo "<option value=".$months[$i]." >".$months[$i]."</option>" ; }?></select></td>
<td><select name="empyear"><?php for($i = 1950; $i <= 2014; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
</tr>
<tr><td></td><td><input type="submit" value="Register" name="submit"></td></tr>
<tr><td>* - Required</td></tr>
</form>
<?php
if(isset($_POST['submit'])):
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$lastname = $_POST['lastname'];
$dateofbirth = $_POST['month']. " ".$_POST['days']. ", ".$_POST['year'];
$age = $_POST['age'];
$school = $_POST['school'];
$educ = $_POST['educ'];
$yearattended = $_POST['yearattended'];
$skills = $_POST['skills'];
$prevcompany = $_POST['prevcompany'];
$position = $_POST['position'];
$dateofemployment = $_POST['empmonth']. " ".$_POST['empyear'];
$row = $result->fetch_assoc();
$usr = $row["firstname"];
$query2 = "UPDATE employee SET firstname='$firstname', middlename='$middlename', lastname='$lastname', dateofbirth='$dateofbirth', age='$age', school='$school',
educ='$educ', yearattended='$yearattended', skills='$skills', prevcompany='$prevcompany', position='$position', dateofemployment='$dateofemployment',
WHERE firstname='$usr'";
mysqli_query($emp->openConnection(), $query2);
endif;
else:
echo "Profile not found";
endif;
endif;
?>
</table>
</center>
</body>
</html>
and I do really think that this line and beyond gets ignored.
This is part of the edit.php file that is shown above.
<?php
if(isset($_POST['submit'])):
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$lastname = $_POST['lastname'];
$dateofbirth = $_POST['month']. " ".$_POST['days']. ", ".$_POST['year'];
$age = $_POST['age'];
$school = $_POST['school'];
$educ = $_POST['educ'];
$yearattended = $_POST['yearattended'];
$skills = $_POST['skills'];
$prevcompany = $_POST['prevcompany'];
$position = $_POST['position'];
$dateofemployment = $_POST['empmonth']. " ".$_POST['empyear'];
$row = $result->fetch_assoc();
$usr = $row["firstname"];
$query2 = "UPDATE employee SET firstname='$firstname', middlename='$middlename', lastname='$lastname', dateofbirth='$dateofbirth', age='$age', school='$school',
educ='$educ', yearattended='$yearattended', skills='$skills', prevcompany='$prevcompany', position='$position', dateofemployment='$dateofemployment',
WHERE firstname='$usr'";
mysqli_query($emp->openConnection(), $query2);
endif;
In general, there are two kinds of errors present.
HTML tag order errors, which are extensive
Syntax errors.
- > must be -> to be properly parsed
<? php must be <?php to be properly parsed
The syntax errors are present in both files.
Note: the following code contains some debug statements.
<html>
<head>
<?php
echo "<p>In myquery.php header </p>";
error_reporting(E_ALL);
//echo "<p>" . var_dump($_POST); . "</p>";
//echo "<p>" . var_dump($_GET); . "</p>";
?>
<?php
include("class.php");
?>
<title> Edit Profile</title>
</head>
<body>
<?php
echo "<p>In myquery.php body</p>";
?>
<form method="post" action="?" name="searchform">
<table>
<tr>
<td>Enter first or last name</td>
<td><input type = "text" name="search"><td>
<td><input type = "submit" value="Search" name="search2"></td>
</tr>
</table>
</form>
<?php
echo "<p>about to check _post for search2</p>";
if(isset($_POST['search2'])):
echo "<p>found _post for search2</p>";
$status = "hidden";
$query = "select * from employee WHERE firstname='".$_POST['search']."' OR lastname='".$_POST['search']."' ";
echo "<p>about to open DB</p>";
$emp = new EmployeeProfile();
$emp->openConnection();
echo "<p>about to place find query</p>";
$result = mysqli_query($emp->openConnection(), $query);
echo "<p>about to check for successful query</p>";
if($result->num_rows == 1):
echo "<p>successful search query</p>";
?>
<form method="post" action="?" enctype="multipart/form-data" name="updateform">
<table>
<tr></tr>
<tr><td></td><td>Edit your profile:</td></tr>
<tr></tr>
<tr><td>*Enter first name:</td><td><input type="text" name="firstname"></td></tr>
<tr><td>Enter middle name:</td><td><input type="text" name="middlename"></td></tr>
<tr><td>*Enter last name:</td><td><input type="text" name="lastname"></td></tr>
<tr>
<td>*Date of Birth:</td><td><select name="month"><?php for($i = 0; $i < count($months); $i++) { echo "<option value=".$months[$i]." >".$months[$i]."</option>" ; }?></select></td>
<td><select name="days"><?php for($i = 1; $i <= 31; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
<td><select name="year"><?php for($i = 1950; $i <= 2014; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
</tr>
<tr><td>*Age:</td><td><input type="text" name="age"></td></tr>
<tr><td>*School:</td><td><input type="text" name="school"></td></tr>
<tr><td>*Highest Educational Attainment:</td><td><input type="text" name="educ"></td></tr>
<tr><td>*Year Last Attended:</td><td><input type="text" name="yearattended"></td></tr>
<tr><td>*Skill(s):</td><td><input type="text" name="skills"></td></tr>
<tr><td>Previous Company:</td><td><input type="text" name="prevcompany"></td></tr>
<tr><td>Position:</td><td><input type="text" name="position"></td></tr>
<tr><td>*Date of Employment:</td><td><select name="empmonth"><?php for($i = 0; $i < count($months); $i++) { echo "<option value=".$months[$i]." >".$months[$i]."</option>" ; }?></select></td>
<td><select name="empyear"><?php for($i = 1950; $i <= 2014; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
</tr>
<tr><td></td><td><input type="submit" value="Register" name="submit"></td></tr>
<tr><td>* - Required</td></tr>
</table>
</form>
<?php
echo "<p>about to check for submit second form</p>";
if(isset($_POST['submit'])):
echo "<p>found submit for second form</p>";
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$lastname = $_POST['lastname'];
$dateofbirth = $_POST['month']. " ".$_POST['days']. ", ".$_POST['year'];
$age = $_POST['age'];
$school = $_POST['school'];
$educ = $_POST['educ'];
$yearattended = $_POST['yearattended'];
$skills = $_POST['skills'];
$prevcompany = $_POST['prevcompany'];
$position = $_POST['position'];
$dateofemployment = $_POST['empmonth']. " ".$_POST['empyear'];
$row = $result->fetch_assoc();
$usr = $row["firstname"];
$query2 =
"UPDATE employee
SET firstname='$firstname',
middlename='$middlename',
lastname='$lastname',
dateofbirth='$dateofbirth',
age='$age',
school='$school',
educ='$educ',
yearattended='$yearattended',
skills='$skills',
prevcompany='$prevcompany',
position='$position',
dateofemployment='$dateofemployment',
WHERE firstname='$usr'";
echo "<p>about to update DB</p>";
mysqli_query($emp->openConnection(), $query2);
endif;
else:
echo "<p>search query failed</p>";
echo "Profile not found";
endif;
endif;
?>
</body>
</html>

Search mysql using multiple html fields

How do you add multiple fields to search database using html, php and mysql?
Here is the HTML code.
I would like to add more field options to search database for first name, age, gender.
Example: Search for [first name] AND/OR [Age] AND/OR [gender].
<h2>Search</h2>
<form name="search" action="searchresults.php" method="POST">
Seach for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="firstName">First Name</option>
<Option VALUE="lastName">Last Name</option>
<Option VALUE="email">email</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>
Here is the PHP.
Database connection
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
$find=$_POST['find'];
$field=$_POST['field'];
$data="SELECT firstName, lastName, email, userphoto, age FROM contactInfo WHERE upper($field) LIKE '%$find%'";
$result = mysql_query($data);
$count=mysql_numrows($result);
echo '<br><br>';
if($count > 0){
echo"<table border=0>";
//get images and names in two arrays
$firstName= $row["firstName"];
$lastName= $row["lastName"];
$email= $row["email"];
$userphoto= $row["userphoto"];
$age= $row["age"];
$age = array();
$userphoto = array();
$firstName = array();
$lastName = array();
while ($row = mysql_fetch_array($result))
{
$userphoto[] = "<img src='images/".$row['userphoto']."' height='200' width='175'>";
$firstName[] = $row['firstName'];
$lastName[] = $row['lastName'];
$age[] = $row['age'];
$email[] = $row['email'];
}
while(!empty($userphoto))
{
//output images
foreach(array($userphoto, $firstName, $lastName, $age, $email) as $items)
{
echo "<tr>";
foreach($items as $key=>$item)
{
echo "<td><font size =\"3\" >$item</td>";
//output only four of them
if($key==4)
{
break;
}
}
echo "</tr>";
}
//remove the first five images from $images because they're already printed
$userphoto = array_slice($userphoto, 5);
$firstName = array_slice($firstName, 5);
$lastName= array_slice($lastName, 5);
$email = array_slice($email, 5);
$age = array_slice($age, 5);
}
echo"</table>";
I would divide the query in two parts:
First create a static part:
$query = "SELECT firstName, lastName, email, userphoto, age FROM contactInfo WHERE"
And then calculated the dinamic part:
For each field select by the user according to the and/or option:
$query = $query . $nameField . ("and" || "or") . $valueField
Change Your query.
$data="SELECT firstName, lastName, email, userphoto, age FROM contactInfo WHERE `".$field."` LIKE '%".$find."%'";

insert multiple fields using foreach loop

I have a problem when I want to insert multiple fields into one table.
Here's my form:
<h1>Add user</h1>
<form method="post" action="index.php">
<table>
<thead>
<th>Name</th>
<th>Age</th>
</thead>
<tr>
<td><input name="name[]" type="text" /></td>
<td><input name="age[]" type="text" /></td>
</tr>
<tr>
<td><input name="name[]" type="text" /></td>
<td><input name="age[]" type="text" /></td>
</tr>
<tr>
<td><input name="name[]" type="text" /></td>
<td><input name="age[]" type="text" /></td>
</tr>
</table>
<input type="submit" name="submit" value="Submit" />
</form>
And here's the submit code:
if (isset($_POST['submit'])) {
foreach ($_POST as $val) {
$name = $val['name'];
$age = $val['age'];
mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
}
}
The query inserts into the database, but not the values that I've entered.
Can someone please help me?
You are doing a foreach on $_POST rather than on the name/age arrays. You should be doing foreach on name or age array like this:
if (
!empty($_POST['name']) && !empty($_POST['age']) &&
is_array($_POST['name']) && is_array($_POST['age']) &&
count($_POST['name']) === count($_POST['age'])
) {
$name_array = $_POST['name'];
$age_array = $_POST['age'];
for ($i = 0; $i < count($name_array); $i++) {
$name = mysql_real_escape_string($name_array[$i]);
$age = mysql_real_escape_string($age_array[$i]);
mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
}
}
I would also note that you are currently susceptible to SQL injection so I added the step of escaping your strings for name/age.
I would also highly suggest simply making a single bulk insert into the DB instead of an insert of each record individually (I will leave that up to you to implement). This approach is almost always preferable from a performance standpoint.
Finally, you REALLY should not be using mysql_* functions as they are deprecated. Consider changing to mysqli or PDO.
if (isset($_POST['submit'])) {
$i = 0;
foreach ($_POST as $val) {
$name = $_POST['name'][$i];
$age = $_POST['age'][$i];
mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
$i++;
}
}
This will solve your problem !
foreach($_POST['firstname'] as $key=>$value) {
$firstname = $_POST['firstname'][$key];
$lastname = $_POST['tipo'][$key];
echo "Parte: $lastname";
echo "<br>";
echo "Tipo: $firstname";
echo "<br>";
}
A little bit easier code which works for me well.
if (isset($_POST['submit'])) {
$i = 0;
for ((array) $_POST as $val) {
$sql = "INSERT INTO users (name, age) VALUES (
'{$_POST["name"][$i]}','{$_POST["age"][$i]}'
);
mysql_query($sql);
echo (!mysql_affetced_rows()) ? "Query Wrong" : "Query Okay";
$i++;
}
}
below is the fxample how to inset multi row at one time
$query_string = "INSERT INTO YOURTBL_NAME(column_1,column_2)VALUES";
$data ="";
for($i=0;$i<count($YOUR FILE ARRAY);$i++)
{
$data .='("'.$paramater_1[$i].'","'.$paramater_2.'"),';
}
$qry = substr($query_string.$data, 0, -1);
$result = mysql_query($qry);
$education_institute_array = $_POST['education_institute'];
$education_qualification_array = $_POST['education_qualification'];
$education_start_date_array = $_POST['education_start_date'];
$education_end_date_array = $_POST['education_end_date'];
$education_note_array = $_POST['education_note'];
for ($i = 0; $i < count($education_institute_array); $i++) {
$education_institute = mysql_real_escape_string($education_institute_array[$i]);
$education_qualification = mysql_real_escape_string($education_qualification_array[$i]);
$education_start_date = mysql_real_escape_string($education_start_date_array[$i]);
$education_end_date = mysql_real_escape_string($education_end_date_array[$i]);
$education_note = mysql_real_escape_string($education_note_array[$i]);
$sql_education_insert = "INSERT INTO `education` (`user_id`, `education_institute`, `education_qualification`, `education_start_date`, `education_end_date`, `education_note`) VALUES ('$user_id', '$education_institute', '$education_qualification', '$education_start_date', '$education_end_date', '$education_note')";
$sql_result_education = mysql_query($sql_education_insert);
}

Categories