PHP inserting multiple checkbox AND textbox arrays into MySQL Database - php

I'm having trouble with the array results in my php. My first problem is this :
It shows everything even if the checkbox isn't checked. My second problem is that it won't insert the values to the database even though it's connected to the database (as you can see in the previous screenshot, it says "connected successfully").
This is my html form:
<form method="POST">
<input type="hidden" name="item[]" value="cupcake">
<input type="text" name="items" value="cupcake" readonly><br>
<b>Price :</b> <span name="price" value="3.00">$17.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[]" type="checkbox" value="17" /><span>Add to Cart</span></label></div></div></td><br>
<input type="hidden" name="item[]" value="cake">
<input type="text" name="items" value="cake" readonly><br>
<b>Price :</b> <span name="price" value="20.00">$20.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[]" type="checkbox" value="20" /><span>Add to Cart</span></label></div></div></td><br>
<input type="submit" name="insertBT"><br>
</form>
PHP:
if(isset($_POST['insertBT']))
{
class db_conn
{
public function create_conn($servername, $username, $password, $db)
{
global $conn;
$conn = new mysqli ($servername, $username, $password, $db);
}
public function check_conn()
{
global $conn;
if($conn->connect_error)
{
die ("Connection Failed : " . $conn->connect_error);
}
else
{
echo ("Connected Successfully <br>");
}
}
public function insert()
{
if(isset($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $check) {
$check = implode(',', $_POST['checkbox']);
$name = implode(',', $_POST['item']);
$quantity = implode(',', $_POST['quantity']);
}
echo $check . "<br>";
echo $name . "<br>";
echo $quantity . "<br>";
mysql_query("INSERT INTO purchases(Product, Quantity, Price) VALUES('$name', '$quantity','$check')");
}
}
}
$obj1 = new db_conn;
$obj1->create_conn("localhost","root","", "dbtest");
$obj1->check_conn();
$obj1->insert();
}

You shouldn't be using implode. That puts a comma-separated list of everything in the form into each row that you insert, and repeats this for every box that's checked. You should just insert one item in each row, by indexing the arrays.
However, when you have a checkbox in a form, it only submits the ones that are checked. The result of this is that the indexes of the $_POST['checkbox'] array won't match up with the corresponding $_POST['item'] and $_POST['quantity'] elements. You need to put explicit indexes into the checkbox names so you can relate them.
<form method = "POST">
<input type = "hidden" name = "item[]" value = "cupcake">
<input type = "text" name = "items" value = "cupcake" readonly><br>
<b>Price :</b> <span name = "price" value = "3.00">$17.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[0]" type="checkbox" value="17" /><span>Add to Cart</span></label></div></div></td><br>
<input type = "hidden" name = "item[]" value = "cake">
<input type = "text" name = "items" value = "cake" readonly><br>
<b>Price :</b> <span name = "price" value = "20.00">$20.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[1]" type="checkbox" value="20" /><span>Add to Cart</span></label></div></div></td><br>
<input type = "submit" name = "insertBT"><br>
</form>
Then your PHP code can be like this:
$stmt = $conn->prepare("INSERT INTO purchases (Product, Quantity, Price) VALUES (?, ?, ?)");
$stmt->bind_param("sis", $name, $quantity, $price);
foreach ($_POST['checkbox'] as $i => $price) {
$name = $_POST['name'][$i];
$quantity = $_POST['quantity'][$i];
$stmt->execute();
}
BTW, putting the prices in your HTML seems like a bad idea. Nothing stops the user from modifying HTML using the web inspector before they submit the form, so they could lower the price. You should get the prices from the database when processing the form.
Also, notice that in your original code you opened the database connection using MySQLi, but then you tried to do the insert using mysql_query instead of $conn->query(). You can't mix APIs like that; myql_query can only be used when you open the connection with mysql_connect.

Related

Update multiple SQL records using one PHP/MySQLi query

Is it possible to update multiple records in one MySQLi query?
There are 4 records to be updated (1 for each element level) when the submit button is clicked.
The results are posted to a separate PHP page which runs the query and returns the user back to the edit page. elementid is 1,2,3,4 and corresponds with Earth, wind, fire, water. These never change (hence readonly or hidden)
<form id="edituser" name="edituser" method="post" action="applylevelchanges.php">
<fieldset>
<legend>Edit Element Level</legend>
<?php
while($userdetails->fetch())
{?>
<input name="clientid" id="clientid" type="text" size="8" value="<?php echo $clientid; ?>" hidden />
<input name="elementid" id="elementid" type="text" size="8" value="<?php echo $elementid;?>" hidden />
<input name="elemname" id="elemname" type="text" size="15" value="<?php echo $elemname; ?>" readonly />
<input name="elemlevel" id="elemlevel" type="text" size="8" required value="<?php echo $elemlevel; ?>" /></br>
</br>
<?php }?>
</fieldset>
<button type="submit">Edit Student Levels</button>
</form>
And the code to apply the changes
<?php
if (isset($_POST['clientid']) && isset($_POST['elementid']) && isset($_POST['elemname']) && isset($_POST['elemlevel'])) {
$db = createConnection();
$clientid = $_POST['clientid'];
$elementid = $_POST['elementid'];
$elemname = $_POST['elemname'];
$elemlevel = $_POST['elemlevel'];
$updatesql = "update stuelement set elemlevel=? where clientid=? and elementid=?";
$doupdate = $db->prepare($updatesql);
$doupdate->bind_param("iii", $elemlevel, $clientid, $elementid);
$doupdate->execute();
$doupdate->close();
$db->close();
header("location: edituserlevel.php");
exit;
} else {
echo "<p>Some parameters are missing, cannot update database</p>";
}

html radio button with an "other" selection that has a text box

When my insert runs it will write the text in the text box but if I choose a radio button selection other than "other" nothing is inserted into the table.
If I remove the "other"code the radio button selected is written to the table.
here is the code
<input type="radio" name="job" value="PHP Programmer">PHP Programmer
<input type="radio" name="job" value="SQL Programmer">SQL Programmer<br>
<input type="radio" name="job">Other <input type="text" name="job" >
<h3>* If yes, check which ISO standard(s) you are accredited?</h3>
<input type="radio" name="iso_standard" value="17020">17020
<input type="radio" name="iso_standard" value="17025">17025
<br />
<input action="submit" type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['job']) && isset($_POST['iso_standard']))
{
$job = mysqli_real_escape_string($db, $_POST['job']);
$iso_standard =mysqli_real_escape_string($db, $_POST['iso_standard']);
$sql="insert into tbl_test_insert(iso_cert, iso_standard)
values ('$job', '$iso_standard')";
if(!mysqli_query($db, $sql))
{
die('Error: ' .mysqli_error($db));
}
echo "1 record added";
}
else
{
echo "You didn't choose all the options!
}
?>
You are overwriting the value of job with the text input field. It does not mather if it has any value or not.
Please rename your <input type="text" name="job" > to for example otherJob and you should be fine
edit:
change <input type="radio" name="job">Other <input type="text" name="job" >
to <input type="radio" name="job" value="other">Other <input type="text" name="otherJob">
change $job = mysqli_real_escape_string($db, $_POST['job']);
to
$job = mysqli_real_escape_string($db, $_POST['job']);
$otherJob = mysqli_real_escape_string($db, $_POST['otherJob']);
if ($job == 'other') {
$jobField = $otherJob;
} else {
$jobField = $job;
}
and change $sql="insert into tbl_test_insert(iso_cert, iso_standard)
values ('$job', '$iso_standard')";
to $sql="insert into tbl_test_insert(iso_cert, iso_standard)
values ('$jobField', '$iso_standard')";

MySQL/PHP: Insert form array into database?

I am a PHP newbie having a problem inserting an array from a form into the database using foreach statement.
I am trying to create a form that accepts Score, Grade and Comment for each subject. However,only the last subject gets inserted into the database. The list of subjects is loaded from previously registered subjects (I have no problem with that). My problem is getting all the subjects to save back to database.
This is the form i use:
<legend>ENTER RESULTS:</legend>
<input type="hidden" name="results[]" value= "<?php foreach ($subjects as $subject):?>
<ul>
<li> <input type="text" name="subject_name" size="10" value ="<?php htmlout($subject['subject_name']); ?>"/>
</label>
<label for="subject_score">SCORE:</label>
<input type="text" name="subject_score" size="5" value = "<?php
htmlout($subject_score);?>"/> <label for="subject_score">GRADE:</label>
<input type="text" name="subject_grade" size="5" value = "<?php
htmlout($subject_grade);?>"/><label for="subject_grade">COMMENT:</label>
<input type="text" name="subject_comment" size="30" value = "<?php
htmlout($subject_comment);?>"/> </div></li>
<?php endforeach; ?>
<input type="hidden" name="student_id" value="<?php
htmlout($student_id); ?>
</fieldset>
This is the php code i use:
if (isset($_GET['result']))
{
try
{
$sql = 'INSERT INTO results SET
student_id = :student_id,
subject_name = :subject_name,
subject_grade = :subject_score,
subject_grade = :subject_grade,
subject_comment = :subject_comment';
$s = $pdo->prepare($sql);
foreach ($_POST['results'] as $result)
{
$s->bindValue(':student_id',$_POST['student_id']);
$s->bindValue(':subject_name', $_POST['subject_name']);
$s->bindValue(':subject_score', $_POST['subject_score']);
$s->bindValue(':subject_grade', $_POST['subject_grade']);
$s->bindValue(':subject_comment', $_POST['subject_comment']);
$s->execute();
}
}
catch (PDOException $e)
{
$error = 'Could not Register the Student for the Subjects, Please try again'.$e->GetMessage();
include 'error.html.php';
exit();
}
echo 'Success';
you can use form element in array like subject_score[]
your form should be like
foreach
<input type="text" name="subject_name[]" size="10" value ="<?php htmlout($subject['subject_name']); ?>"/>
</label>
<label for="subject_score">SCORE:</label>
<input type="text" name="subject_score[]" size="5" value = "<?php
htmlout($subject_score);?>"/> <label for="subject_score">GRADE:</label>
<input type="text" name="subject_grade[]" size="5" value = "<?php
htmlout($subject_grade);?>"/><label for="subject_grade">COMMENT:</label>
<input type="text" name="subject_comment[]" size="30" value = "<?php
htmlout($subject_comment);?>"/> </div></li>
endforeach
then you can collect those value like below
foreach($_POST['subject_name'] as $key=>$val){
//val will hold subject name
}

Insert array values + single form values into all rows

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.

multiple arrays data posting and mysql insert using foreach php

i have form as below with same name text field columns, i want to insert multiple arrays data to mysql using this below form. pls tell me how to do this using foreach in php mysql
First Column
<input name="date[]" type="text" class="datepicker">
<input type="text" name="local[]" />
<input type="text" name="desc[]" />
<input type="text" name="ta[]" />
<input type="text" name="car[]" />
Second Column
<input name="date[]" type="text" class="datepicker">
<input type="text" name="local[]" />
<input type="text" name="desc[]" />
<input type="text" name="ta[]" />
<input type="text" name="car[]" />
First of all I would rename your form fields to make this easier:
<?php
$number_of_columns = 2;
for($i=0;$i<$number_of_columns;$i++) :?>
<input name="col[<?=$i?>][date]" type="text" class="datepicker">
<input type="text" name="col[<?=$i?>][local]" />
<input type="text" name="col[<?=$i?>][desc]" />
<input type="text" name="col[<?=$i?>][ta]" />
<input type="text" name="col[<?=$i?>][car]" />
<?php endfor;?>
And then once you get the data, you can just loop through the $_POST['col'] array and insert each one individually into the database. I'm assuming here that you've already connected to your database and are using the mysql library.
$cols = $_POST['col'];
$table = 'table_name';
foreach($cols as $col) {
$local = mysql_real_escape_string($col['local']);
$desc = mysql_real_escape_string($col['desc']);
$ta = mysql_real_escape_string($col['ta']);
$car = mysql_real_escape_string($col['car']);
mysql_query("INSERT INTO `{$table}` (`local`, `desc`, `ta`, `car`) VALUES('{$local}', '{$desc}', '{$ta}', '{$car}')") or die(mysql_error());
}
Try this code:
extract($_POST);
$n = count($date);
for ($i = 0; $i < n; $i++) {
$query = 'INSERT INTO `table` (`c1`, `c2`, `c3`, `c4`, `c5`) VALUES (\'' . $date[$i] . '\', \'' . $local[$i] . '\', \'' . $desc[$i] . '\', \'' . $ta[$i] . '\', \'' . $car[$i] . '\')';
// Here you must execute your query
}

Categories