I have a html form which has 2*12 input fields with name="links[]" and name="ids[]"...
I want to update column 'link' with those 12 links using those 12 ids
I know we need a loop for that.
But don't know how to make the sql query.
$ids=mysqli_real_escape_string($conn, $_POST['ids']);
foreach($ids as $id){....}
$links=mysqli_real_escape_string($conn, $_POST['links']);
foreach($links as $link){....}
$sql="update query.....";
EDIT:
It works with two variables $id and $season but when i add more than two variable like $episode etc. it doesn't work. it doesn't execute other variable only first two are executed and it sets the values of $season to 1 or sometimes 0 of all the entries in the table.
for($i=0 ; $i<count($record['id']); $i++){
$id=mysqli_real_escape_string($conn, $record['id'][$i]);
$season=mysqli_real_escape_string($conn, $record['season'][$i]);
$episode=mysqli_real_escape_string($conn, $record['episode'][$i]);
$rel_id=mysqli_real_escape_string($conn, $record['rel_id'][$i]);
$link=mysqli_real_escape_string($conn, $record['link'][$i]);
//sQl Query
$sql = "UPDATE series SET season='$season' and episode='$episode' and rel_id='$rel_id' and link='$link' WHERE id='$id'";
if ($conn->query($sql) === TRUE) {}
else { echo "Error: " . $sql . "<br>" . $conn->error; };
Try the below code.
<form name="rec" id="rec" method="post">
<input type="text" name="reord[id][]">
<input type="text" name="reord[season][]">
<input type="text" name="reord[episode][]">
<input type="text" name="reord[rel_id][]">
<input type="text" name="reord[link][]">
<br/>
<input type="text" name="reord[id][]">
<input type="text" name="reord[season][]">
<input type="text" name="reord[episode][]">
<input type="text" name="reord[rel_id][]">
<input type="text" name="reord[link][]">
<br/>
<input type="text" name="reord[id][]">
<input type="text" name="reord[season][]">
<input type="text" name="reord[episode][]">
<input type="text" name="reord[rel_id][]">
<input type="text" name="reord[link][]">
</br>
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST['submit'])){
$record = $_POST['reord'];
$id = $season = $episode = $rel_id = $link = '';
for($i=0 ; $i<count($record['id']); $i++){
$id= mysqli_real_escape_string($conn, $record['id'][$i]);
$season=mysqli_real_escape_string($conn, $record['season'][$i]);
$episode=mysqli_real_escape_string($conn, $record['episode'][$i]);
$rel_id=mysqli_real_escape_string($conn, $record['rel_id'][$i]);
$link= mysqli_real_escape_string($conn, $record['link'][$i]);
echo $sql = "UPDATE series SET season='$season' and episode='$episode' and rel_id='$rel_id' and link='$link' WHERE id=$id";
$conn->query($sql);
}
}
?>
$ids=mysqli_real_escape_string($conn, $_POST['ids']);
foreach($ids as $key => $id){
$sql="update tablename set fieldname=value where link=$_POST[links][$key] and id=$id";
}
This might work. If not give me more details.
UPDATE `tablename` SET `fieldname` = CASE
WHEN id = 1 AND xyz = 3 THEN `value 1`
WHEN id = 2 AND xyz = 3 THEN `value 2`
WHEN id = 3 AND xyz = 3 THEN `value 3`
END
In the scenario described I would use SET-WHEN-THEN query
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)
I am trying to insert 4 forms that are the same. but with different values to mysql using PHP.
When I submit my data, the database only takes the values from the last form and inserts it 4 times. I am trying to get the values from all 4 on submit.
<div class="req3">
<h1>Requirement 4</h1>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<br>
Enter info for 4 teams and it will inserted into the database<br><br>
<div class="sqlForm">
<p class="formHead">Team 1</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br>
</div>
<div class="sqlForm">
<p class="formHead">Team 2</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br>
</div>
<div class="sqlForm">
<p class="formHead">Team 3</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br>
</div>
<div class="sqlForm">
<p class="formHead">Team 4</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br><br></div>
<input class="styled-button" type="submit" name="insert" value="Submit">
</form>
<?php
if (isset($_POST['insert'])) {
insertTable();
} else {
$conn->close();
}
function insertTable() {
$servername = "localhost:3306";
$username = "XXXXX";
$password = "XXXXX";
$dbname = "XXXXX";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo ("Connection failed: " . $conn->connect_error);
} else {
$varTname = $_POST['teamname'];
$varCity = $_POST['city'];
$varBplayer = $_POST['bestplayer'];
$varYearformed = $_POST['yearformed'];
$varWebsite = $_POST['website'];
$sql = "INSERT INTO Teams (teamname, city, bestplayer, yearformed, website)
VALUES ('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite')";
if ($conn->multi_query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysql_query($sql);
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
}
}
?>
chnage the names of your controls so they Post as Arrays
<input type="text" name="teamname[G1]">
<input type="text" name="teamname[G2]">
this why when you use $varTname = $_POST['teamname']; $varTname is an array and each of the 4 values of teamname are set as $varTname['G#'] where # matches the number you set for that group of input fields.
then use a for loop to get the data and execute your query, something like bellow. while you at it you can also fix up your SQL Injection vulnerability. you may also want to so some more sanitation to the data just to be sure
$varTname = $_POST['teamname'];
$varCity = $_POST['city'];
$varBplayer = $_POST['bestplayer'];
$varYearformed = $_POST['yearformed'];
$varWebsite = $_POST['website'];
$stmt = $mysqli->prepare('INSERT INTO Teams (teamname, city, bestplayer, yearformed, website) VALUES (?,?,?,?,?,?)');
$varTname1Bind = "";
$varTnameBind = "";
$varCityBind = "";
$varBplayerBind = "";
$varWebsiteBind = "";
// assuming they are all strings, adjust where needed
$stmt->bind_param('sssssss',
$varTname1Bind,
$varTnameBind,
$varCityBind,
$varBplayerBind,
$varYearformedBind,
$varWebsiteBind);
for($i = 1; i < 5; $i++)
{
$varTname1Bind = $varTname['G'.$i];
$varTnameBind = $varTname['G'.$i];
$varCityBind = $varCity['G'.$i];
$varBplayerBind = $varBplayer['G'.$i];
$varYearformedBind = $varYearformed['G'.$i];
$varWebsiteBind = $varWebsite['G'.$i];
$stmt->execute();
}
will save you on how much code you need to do
You can convert your input names into arrays by adding [] then in your php loop through the array of the $_POST[] and built up your $sql by concatenating the values until you finish looping through all values and INSERT it as multiple values.
HTML:
<label>Team Name:</label> <input type="text" name="teamname[]"><br>
<label>City:</label> <input type="text" name="city[]"><br>
<label>Best Player:</label> <input type="text" name="bestplayer[]"><br>
<label>Year Formed:</label> <input type="text" name="yearformed[]"><br>
<label>Website:</label> <input type="text" name="website[]"><br>
PHP:
<?php
$sql = "INSERT INTO Teams (teamname, city, bestplayer, yearformed, website) VALUES ";
for($i = 0 ; $i < count($_POST['teamname']) ; $i++){
$varTname = $_POST['teamname'][$i];
$varCity = $_POST['city'][$i];
$varBplayer = $_POST['bestplayer'][$i];
$varYearformed = $_POST['yearformed'][$i];
$varWebsite = $_POST['website'][$i];
$sql .= "(" .$varTname. " , " .$varCity. " , " .$varBplayer. " , " .$varYearformed. " , " .$varWebsite. "),";
}
$sql = rtrim($sql, ','); // omit the last comma
// Then Excute your query
?>
This way you don't need to give them unique names name="test1", name="test2" and so, to see it in action check this PHP Fiddle in the bottom of the result page, I've already set the values of the input fields, just hit submit and go to the bottom of the result page to see the composed INSERT statement.
NOTE that the above SQL is just a demo on how to build it up, DO NOT use it like this without validation and sanitizing.. ALSO STOP querying this way and instead use Prepared Statements with PDO or MySQLi to avoid SQL Injection.
So for MySQLi prepared statements, procedural style - I work with PDO - as you see in this PHP Fiddle 2, the code is:
<?php
// you validation goes here
if (isset($_POST['insert'])) {
insertTable();
} else {
$conn->close();
}
function insertTable() {
// enter your credentials below and uncomment it to connect
//$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
$sql = "INSERT INTO Teams (teamname, city, bestplayer, yearformed, website) VALUES";
$s = '';
$bind = '';
for($i = 0 ; $i < count($_POST['teamname']) ; $i++){
$sql .= " (?, ?, ?, ?, ?)";
$s .= 's';
$varTname = $_POST['teamname'][$i];
$varCity = $_POST['city'][$i];
$varBplayer = $_POST['bestplayer'][$i];
$varYearformed = $_POST['yearformed'][$i];
$varWebsite = $_POST['website'][$i];
$bind .= " , " . $varTname. " , " .$varCity. " , " .$varBplayer. " , " .$varYearformed. " , " .$varWebsite;
}
$sql = rtrim($sql, ','); // omit the last comma
$s = "'" .$s. "'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, $s , $bind);
mysqli_stmt_execute($stmt);
}
?>
Normally this is done by creating arrays of form controller.
<input type="text" name="teamname[]">
<input type="text" name="city[]">
And then you can get an array in post request.
Hope this helps!
use different name like teamname1,teamname2,teamname3,teamname4
<input type="text" name="teamname1">
<input type="text" name="teamname2">
<input type="text" name="teamname3">
<input type="text" name="teamname4">
For get values :-
$varTname1 = $_POST['teamname1'];
$varTname2 = $_POST['teamname2'];
$varTname3 = $_POST['teamname3'];
$varTname4 = $_POST['teamname4'];
For insert values :-.
$sql = "INSERT INTO Teams (teamname)
VALUES ('$varTname1'),
('$varTname2'),
('$varTname3'),
('$varTname4')
or you can try this:-
<input type="text" name="teamname[]">
Get value like :-
$_POST['teamname'][0]
try this method
$sql = "INSERT INTO Teams (teamname, city, bestplayer,yearformed,website)
VALUES ('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
";
$sql.= query same as abov
$sql.= query same as abov
$sql.= query same as abov
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
note the . dot after the first query.
I think you should also use an auto increment keyThis should work.
Hi I want to add a lot of inputs with same name to my database.
I am working on a recipe submit form, that adds in ingredients with form input text. I have multiple inputs with same name, and want them all to be added to the database. By array of some sort.
I have a jquery that makes it possible to add in more ingredients and amount, don't think it is important for this question. So won't add.
Till now I have this html/php:
<form id="opskriftReg" name="opskriftReg" action="opskriftRegSave.php" method="post">
*Ingredienser:<br>
Ingrediens: <input type="text" name="ingredients[]">
Mængde: <input type="text" name="amount[]"><br>
<div id="InputsWrapper"></div>
<input type="button" id="AddMoreFileBox" value="Tilføj ingrediens"><br>
<input type="submit" value="Submit">
</form>
And this for php/database input:
$mysqli = new mysqli ("localhost","","","brugerreg");
//Add this php add to database:
$ingredients = $_POST['ingredients'];
$amount = $_POST['amount'];
echo $ingredients." ".$amount;
$sql = "INSERT INTO `brugerreg`.`opskriftreg` (`ingredients`,
`amount`) VALUES ('".$ingredients."', '".$amount."')";
$stmt = $mysqli->prepare($sql); $stmt->execute();
Make your jQuery print your inputs such as:
<input type="text" name="ingredients[]">
<input type="text" name="amount[]">
Note the [] in the name, these are called HTML input arrays.
Now you can access these inputs in your PHP as:
$ingredients = implode(',',$_POST['ingredients']);
$amount = implode(',',$_POST['amount']);
echo $ingredients."<br>".$amount; //you could comment this
$sql = "INSERT INTO `brugerreg`.`opskriftreg` (`ingredients`,
`amount`) VALUES ('".$ingredients."', '".$amount."')";
$stmt = $mysqli->prepare($sql); $stmt->execute();
You could use the implode() function to convert an array into a single string with a delimiter
Found here.
Every time you add new input with same name, append it with "[]", so in the end you get:
Ingrediens: <input type="text" name="ingredients[]">
Mængde: <input type="text" name="amount[]"><br>
Ingrediens: <input type="text" name="ingredients[]">
Mængde: <input type="text" name="amount[]"><br>
Ingrediens: <input type="text" name="ingredients[]">
Mængde: <input type="text" name="amount[]"><br>
And in php:
$ingredients = $_POST['ingredients']; // $ingredients is now an array
$amount = $_POST['amount']; // $amount is now an array
echo $amount[0];
echo $amount[1];
To insert it into database just prepare the query accordingly, for example iterate over the array and concatenate the "('".$ingredients."', '".$amount."')" for every pair.
$values = "".
for ($i = 0; $i < sizeof($amount); $i++) {
$values .= "('".$ingredients[$i]."', '".$amount[$i]."')";
if ($i != sizeof($amount) - 1) {
$values .= ", ";
}
}
$sql = "INSERT INTO `brugerreg`.`opskriftreg` (`ingredients`,`amount`) VALUES " . $values;
I am trying to insert values from a form into my mysql database. I have single value forms + array values from the form. How can I insert the array values into my database with the single form values attached to all rows?
The HTML:
Start:<br>
<input type="text" name="start" id="start">
End:<br>
<input type="text" name="end" id="end">
<input type="text" name="item[]" placeholder="Manufacturer #" /><br>
<input type="text" name="description[]" placeholder="Description" /><br>
<input type="text" name="item[]" placeholder="Manufacturer #" /><br>
<input type="text" name="description[]" placeholder="Description" /><br>
<input type="text" name="item[]" placeholder="Manufacturer #" /><br>
<input type="text" name="description[]" placeholder="Description" /><br>
The PHP:
if (isset($_POST['submit']))
{
$link = mysql_connect('localhost', 'user', 'pass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb") or die(mysql_error());
echo 'Connected successfully';
$query = "INSERT INTO agreement (start, end, item_number, item_description) VALUES ";
foreach($_POST['item'] as $i => $item)
{
// Get values from post.
$item = mysql_real_escape_string($item);
$description = mysql_real_escape_string($_POST['description'][$i]);
$start = mysql_real_escape_string($_POST['start'][$i]);
$end = mysql_real_escape_string($_POST['end'][$i]);
// Add to database
$query = $query." ('$start','$end','$item','$description') ,";
}
$query = substr($query,0,-1); //remove last char
$result = mysql_query($query);
}
I will be changing the code to mysqli/pdo, I know that the current code is unsecure.
Any help is appreciated, thanks!
Just use $_POST['start'] and $_POST['end'] without array access since they will be the same each time. You can use array access for item and description.