Store Value in Database With For Loop - php

Here's my code: you will automatically understand what it does
<form method="post">
Enter Your Numbers
<input type="number" name="number" min="1" max="10" />
<input type="submit" name="submit" value="submit" />
</form>
<?php
if(isset($_POST['submit']))
{
$number = $_POST['number'];
for ($x=0; $x<=$number; $x++) {
echo "<input type=\"text\" name=\"tbno".$x."\">";
}
echo "<input type=\"submit\" value=\"submit\" name=\"submit1\">";
}
if(isset($_POST['submit1']))
{
$link = mysql_connect("localhost", "root", "");
$db = mysql_select_db("bookabook");
}
?>
Here's my question: I want to store the textbox values in database, but I don't know how to do this.
if(isset($_POST['submit1']))
{
$link = mysql_connect("localhost", "root", "");
$db = mysql_select_db("bookabook");
//WHAT SHOULD I WRITE HERE
}
Can anyone tell me please?

# HTML
echo "<input type='text' name='tbno[]' value='$x'>";
# PHP
$array = $_POST[tbno];
foreach ($array as $key => $value) {
echo "$key = $value<br/>";
}

Instead of using a counter $x -> name=\"tbno".$x."\", just set your inputs to an array -> name=\"tbno[]\". Then on form submit you can easily loop through them using a foreach or for loop.
<?php
if(isset($_POST['tbno']))
{
//your db connection
foreach($_POST['tbno'] as $tbno){
//INSERT INTO tbl VALUE $tbno
}
echo 'INSERTED DATA';
}
?>
<form method="post">
<?php
if(isset($_POST['number']))
{
$number = $_POST['number'];
for ($x=0; $x<$number; $x++) {
echo "<input type=\"text\" name=\"tbno[]\">";
}
}
else
{ ?>
Enter Your Numbers<input type="number" name="number" min="1" max="10" />
<?php
} ?>
<input type="submit" name="submit" value="submit" />
</form>
I condensed your 2 forms into 1, as the only thing that changes the inputs, so there is less code.

I think what you're looking for is an insert statement. I'm not sure I understand the code, but I understand the objective. All you need to do is create an insert(like below) statement in the for-loop that loops through the books, etc..
$number = trim($_POST['number']);
$numberOfBooks = mysqli_real_escape_string($mysqlDatabseConnectionObject,$numberOfBooks); //variable to be inserted in the database
$insertQuery = sprintf("INSERT INTO <table_name> VALUES('%s'",$numberOfBooks)); //statement to be executed
$insertResults = $mysqlDatabseConnectionObject->query($insertQuery); //execute the query
print_r($insertResults); //printing the query execution results

if(isset($_POST['submit1']))
{
$link = mysql_connect("localhost", "root", "");
$db = mysql_select_db("bookabook");
$values = "";
foreach($_POST as $key => $inputValue){
$values.="(".$inputValue."),";
}
$SQL_string = "INSERT INTO mitabla(micampo) VALUES $values";
mysql_query($SQL_string,$link);
}

Related

Variable is not getting stored after submitting the form

Sorry if the Title doesn't make any sense.
So, my code is as follows:
<?php
$conn=new mysqli("localhost","root","aman8blue","users");
$conn->connect_error;
$querynor= mysqli_query($conn,"SELECT * FROM userinfo");
$nor=mysqli_num_rows($querynor);
for($i=1; $i<=$nor; $i++) {
?>
<form method='post'>
<label class='switch'><input type='checkbox' name='check' value=1 onChange='this.form.submit()'><span class='slider_round'></span></label>
</form>
<?php
$status = 0;
if(isset($_POST['check'])) {
$status=1;
}
if($status==1) {
echo "WORKING!";
}
else {
echo "NOPE!";
}
}
?>
But no matter what, even if I tick the checkbox, it shows "WORKING!". I can't understand where am I wrong.
(Sorry the previous one was incomplete)
Thanks in Advance!
add
name="check"
in your input since post is looking for name attribute and you don't have one
<?php
$conn = new mysqli("localhost", "root", "xxxx", "users");
$conn->connect_error;
$querynor = mysqli_query($conn, "SELECT * FROM userinfo");
$nor = mysqli_num_rows($querynor);
echo '<form method=\'post\'>';
for ($i = 1; $i <= $nor; $i++)
{
?>
<label class='switch'><input type='checkbox' name='check[<?php echo $nor[$i]['id']; ?>]' value=1 onChange='this.form.submit()' <?php echo (isset($_POST['check'][$nor[$i]['id']]) ? 'checked':''); ?>>
<span class='slider_round'></span>
</label>
<?php
}
echo '</form>';
?>
As the answer to the comment.

PHP multiple checkbox to database

hello i have been trying to use multiple checkboxes to input info to a db i used [] with checkbox name but "array" is saved to db. What code and where should i input for this to work correctly? thank you!
this is my form code:
<?php
require_once('connection.php');
if(isset($_GET['process']))
{
$query = "Insert INTO `lista_precios` (Marca) values('$_POST[Marca]')";
//echo $query; exit;
$result = mysql_query($query) or die(mysql_error());
if(!$result)
{
$msg = "not Inserted";
}
else
{
$msg = "Inserted";
header("location:form.php?m=".$msg);
}
}
?>
<method="post" action="form.php?process">
<p>MARCA: <br><br>
<input type="checkbox" name="Marca" value="ACER">ACER
<input type="checkbox" name="Marca" value="AOC">AOC
<input type="checkbox" name="Marca" value="APPLE">APPLE
<input type="submit" name="Submit" value="Submit" />
</form>
And this is my connection:
<?php
$link=mysql_connect("xxxx","xxxx","xxxx");
$database='xxxxxxx';
if (!$link)
die('Failed to connect to Server'.mysql_error());
$db=mysql_select_db($database, $link);
session_start();
if(!$db)
die('Failed to select Data Base '.mysql_error());
?>
First off you need to set your checkboxes names and turn them to name=Marca[]
<form method="post" action="form.php?process">
<p>MARCA: <br><br>
<input type="checkbox" name="Marca[]" value="ACER">ACER
<input type="checkbox" name="Marca[]" value="AOC">AOC
<input type="checkbox" name="Marca[]" value="APPLE">APPLE
<input type="submit" name="Submit" value="Submit" />
</form>
Then on your form.php process the values:
Note: You have to understand, you can't just put $_POST['Marca'] and concatenate them into the string, you have to get each value and build the insert query.
if(isset($_GET['process'])) {
$marca = isset($_POST['Marca']) ? $_POST['Marca'] : null;
if(count($marca) < 3) {
// your validation that no checkboxes were selected
$msg = 'You need to select at least 3 values';
header("Location: form.php?m=".$msg);
}
$values = implode(',', $marca);
$statement = "INSERT INTO `lista_precios` (`Marca`) VALUES ('$values');";
// should result into
// INSERT INTO `lista_precios` (`Marca`) VALUES ('ACER,AOC,APPLE');
// then continue on your query code
$query = mysql_query($statement);
$msg = ($query && mysql_affected_rows() > 0) ? 'Inserted' : 'Not Inserted';
header("Location: form.php?m=".$msg);
}
you can try this...
<?php
require_once('connection.php');
if(isset($_GET['process']))
$marc = implode(", ", $_POST['Marca']); <== add this
{
$query = "Insert INTO `lista_precios` (Marca) values('" . $marc . "')"; <== change this
//echo $query; exit;
$result = mysql_query($query) or die(mysql_error());
if(!$result)
{
$msg = "not Inserted";
}
else
{
$msg = "Inserted";
header("location:form.php?m=".$msg);
}
}
?>
<method="post" action="form.php?process">
<p>MARCA: <br><br>
<input type="checkbox" name="Marca[]" value="ACER">ACER <==change this
<input type="checkbox" name="Marca[]" value="AOC">AOC <==change this
<input type="checkbox" name="Marca[]" value="APPLE">APPLE <==change this
<input type="submit" name="Submit" value="Submit" />
</form>
Use at least MySQLi instead of deprecated MySQL. Try this:
connection.php:
<?php
$con=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
?>
Your main file:
<html>
<body>
<?php
include('connection.php');
if(isset($_POST['Submit'])){ /* IF FORM IS SUBMITTED */
if(!empty($_POST['Marca'][0])){ /* IF THE SUBMITTED CHECKBOX IS SELECTED */
$acer=mysqli_real_escape_string($con,$_POST['Marca'][0]); /* ESCAPE STRING */
} /* END OF IF NOT EMPTY MARCA 0 */
else { $acer=""; }
if(!empty($_POST['Marca'][1])){ /* IF THE SUBMITTED CHECKBOX IS SELECTED */
$aoc=mysqli_real_escape_string($con,$_POST['Marca'][1]); /* ESCAPE STRING */
} /* END OF IF NOT EMPTY MARCA 1 */
else { $aoc=""; }
if(!empty($_POST['Marca'][2])){ /* IF THE SUBMITTED CHECKBOX IS SELECTED */
$apple=mysqli_real_escape_string($con,$_POST['Marca'][2]); /* ESCAPE STRING */
} /* END OF IF NOT EMPTY MARCA 2 */
else { $apple=""; }
$overalldata=$acer.", ".$aoc.", ".$apple;
$query = "INSERT INTO lista_precios (Marca) VALUES ('$overalldata')";
$result = mysqli_query($con,$query); /* INSERT QUERY */
echo "Inserted data properly.<br>";
} /* END OF ISSET SUBMIT */
?>
<form method="POST" action=""> <?php /* SUBMIT PAGE ON ITSELF */ ?>
<p>MARCA: <br><br>
<?php
echo "<input type='checkbox' name='Marca[0]' value='ACER'>ACER";
echo "<input type='checkbox' name='Marca[1]' value='AOC'>AOC";
echo "<input type='checkbox' name='Marca[2]' value='APPLE'>APPLE";
?>
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>

Update echoed data using WHILE loop. Only updates one record

I can't seem to be able to update any records except the first one.
I am not sure how to modify any of the displayed records.
<?php
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'][0];
$type = $_POST['type'][0];
// if I echo $id & $type, it only gives me the first record.**
mysql_query("
UPDATE membership_type
SET mt_type ='$type'
WHERE mt_id = '$id'"
);
}
?>
ALl of this is within the same php page.
<form name=form action='' method='post'>
<?php
$result=mysql_query("SELECT * FROM membership_type;");
while($rows=mysql_fetch_array($result))
{ ?>
<input size=35 class=textField type=text name='type[]' value='<?php echo $rows['mt_type']; ?>'>
<input type=hidden name='m_id[]' value="<?php echo $rows['mt_id']; ?>">
<input type=submit value="Update">
<?php
}
?>
How do I edit any of the displayed records by simply clicking Update button???
First: You should NEVER use the mysql_* functions as they are deprecated.
Second: Try this code:
<?php
// Get a connection to the database
$mysqli = new mysqli('host', 'user', 'password', 'database');
// Check if there's POST request in this file
if($_POST){
foreach($_POST['m_id'] as $id => $type){
$query = "UPDATE membership_type
SET mt_type = '".$type."'
WHERE mt_id = '".$id."'";
// Try to exec the query
$mysqli->query($query) or die($mysqli->error);
}
}else{
// Get all membership_type records and then iterate
$result = $mysqli->query("SELECT * FROM membership_type") or die($mysqli->error); ?>
<form name='form' action='<?php echo $_SERVER['PHP_SELF'] ?>' method='post'>
<?php while($row = $result->fetch_object()){ ?>
<input size='35'
class='textField'
type='text'
name='m_id[<?php echo $row->mt_id ?>]'
value='<?php echo $row->mt_type; ?>'>
<input type='submit' value="Update">
<?php } ?>
</form>
<?php } ?>
Third: In order to add more security (this code is vulnerable), try mysqli_prepare
Only the first record is updated on every form submission because you have set $id = $_POST['m_id'][0], which contains the value of the first type[] textbox. To update all the other records as well, loop through $_POST['m_id'].
Replace it. Hope this works.
<?php
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'];
$type = $_POST['type'];
$i = 0;
foreach($id as $mid) {
mysql_query("UPDATE membership_type
SET mt_type='".mysql_real_escape_string($type[$i])."'
WHERE mt_id = '".intval($mid)."'") OR mysql_error();
$i++;
}
}
?>
Try this :
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'];
$type = $_POST['type'];
$loopcount = count($id);
for($i=0; $i<$loopcount; $i++)
{
mysql_query("
UPDATE membership_type
SET mt_type ='$type[$i]'
WHERE mt_id = '$id[$i]'"
);
}
}
You HTML was malformed and you were passing as an array but then only using the first element. Consider:
<form name="form" action="" method="post">
<?php
$result = mysql_query("SELECT * FROM membership_type;");
while($row = mysql_fetch_array($result))
echo sprintf('<input size="35" class="textField" type="text" name="m_ids[%s]" value="%s" />', $row['mt_id'], $row['mt_type']);
?>
<input type="submit" value="Update">
</form>
Then the server script:
<?php
if(isset($_POST["action"]) && $_POST["action"] == "Update"){
foreach($_POST['m_ids'] as $mt_id => $mt_type)
mysql_query(sprintf("UPDATE membership_type SET mt_type ='%s' WHERE mt_id = %s LIMIT 1", addslashes($mt_type), (int) $mt_id));
}
There are other things you could be doing here, eg. prepared statements, but this should work.

PHP - Getting back Post from forEach select form

i have a website where the admin can choose to add a certain number of bbcode tags and the corresponding html tags.
First he chooses how many tags he wants to add from a drop down select form in a for Each loop.
Depending on how many tags he chose when he clicked the submit button, the corresponding number of input tags appear in a second form, also in a for Each loop. He fills in the bbcode and html input and clicks the submit button. Normally the tags should be added to my database but in this case when he clicks submit the form disappears and nothing is added..
Here is the code :
//FIRST FORM WHERE HE DECIDES HOW MANY TAGS TO ADD
<form id='nbbalises' action='config.ini.php' method='post' accept-charset='UTF-8'>
<fieldset>
<legend>How many tags ?</legend>
<input type='hidden' name='submitted' id='submitted' value='1' />
<?php
echo '<select name="number">';
$range = range(1,50,1);
foreach ($range as $nb) {
echo "<option value='$nb'>$nb</option>";
}
echo "</select>";
?>
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form><br /> <br />
<?php
if (!(empty($_POST['number']))) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
//SECOND FORM WHERE I GENERATE THE INPUT DEPENDING ON THE NUMBER CHOSEN FROM FIRST FORM
<form id='balises' action='config.ini.php' method='post' accept-charset='UTF-8'>
<fieldset>
<legend>Balises bbc : </legend>
<input type='hidden' name='submitted' id='submitted' value='1' />
<?php
foreach ($range2 as $nb2) {
echo "<label>bbcode tag $nb2 :</label>
<input type='text' size='40' name='bbc$nb2' id='bbc$nb2' maxlength='40' />
<label>html tag $nb2 :</label>
<input type='text' size='40' name='html$nb2' id='html$nb2' maxlength='40' />
<br />";
}
}
?>
<input type='submit' name='Submit2' value='Submit2' />
</fieldset>
</form>
<?php
//PROBLEM STARTS HERE, NOTHING WORKS UNDER HERE
if (isset($_POST['Submit2'])){
//CONNECT TO MY DATABASE
connectDB();
for ($i=0; $i<$number ; $i++){
if (!(empty($_POST["bbc$i"])) && (empty($_POST["html$i"])))
//FUNCTION ADDS TAGS TO DATABASE
addBbc($_POST["bbc$i"], $_POST["html$i"]);
}
mysql_close();
}
}
//MY FUNCTIONS TO ADD THE BBCODE AND HTML TO DATABASE
function connectDB(){
//connexion DB
$link = mysql_connect('127.0.0.1', 'USERNAME', 'PASSWORD');
if (!$link) {
die('Erreur de connexion: ' . mysql_error());
}
$db = mysql_select_db('1213he200967',$link) or die("N'a pu selectionner
1213he200967");
mysql_query("SET NAMES 'utf8'");
}
function addBbc($bbc, $html){
$b = mysql_real_escape_string($bbc);
$h = mysql_real_escape_string($html);
$query="INSERT INTO bbcode (BBC,HTML) VALUES ('$b','$h')";
$result = mysql_query($query) or die("error");
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
return false;
}
else return true;
}
Thank you very much, and sorry if my code is amateur-ish, i'm only starting in php.
EDIT
Found part of my problem
$number = $_POST['number'];
$range2 = range(1,$number,1);
This goes from 1 to the number chosen by the user in the first form.
for ($i=0; $i<$number ; $i++){
if (!(empty($_POST["bbc$i"])) && (empty($_POST["html$i"])))
//FUNCTION ADDS TAGS TO DATABASE
addBbc($_POST["bbc$i"], $_POST["html$i"]);
This goes from 0 to $number - 1
So i changed my code to this.
for ($i=0; $i<$number ; $i++){
$nb = $i + 1;
if (!(empty($_POST["bbc$nb"])) && (empty($_POST["html$nb"]))) {
addBbc($_POST["bbc$nb"], $_POST["html$nb"]);
}
else echo "$nb tags empty ";
This works a bit better but now it goes to the else just here above and displays "2 tags empty", so it still doesn't quite work.
Ok to solve it I finally decided to post the data from the second form to another page and i modified my code to this.
for ($i=0; $i<$number ; $i++){
$nb = $i + 1;
$varBbc = 'bbc'.$nb;
$varHtml = 'html'.$nb;
if ((isset($_POST[$varBbc])) && (isset($_POST[$varHtml]))) {
addBbc($varBbc, $varHtml);
}
else echo "$nb tags empty ";
}
Apparently using !empty instead of isset doesn't work in this case, maybe because of the html tags.
$nb should be in double quotes.
so echo "<option value='$nb'>$nb</option>"
change to echo "<option value='".$nb."'>$nb</option>";
and also
if (!(empty($_POST['number']))) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
change to:
if (isset($_POST['submit'])) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>

Deleting Multiple Records using Checkboxes in PHP

I am having an issue where I need to be able to delete multiple records using checkboxes.
Here is the code that I currently have.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post" action="insert_ticket.php">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
<tr><td><input type="submit" name="submit" value="Add"/></td></tr>
</table>
</table>
</form>
<form method="post" action="delete_ticket.php">
<input type="submit" name="delete" value="Delete"/>
</form>
</table>
<?php
print "<table width=80% border=1>\n";
$cols = 0;
while ($get_info = mysql_fetch_assoc($result)){
$id = $get_info->id;
if($cols == 0)
{
$cols = 1;
print "<tr>";
print "<th>Select</th>";
foreach($get_info as $col => $value)
{
print "<th>$col</th>";
}
print "<tr>\n";
}
print "<tr>\n";
print "<td><input type='checkbox' name='selected[]' id='checkbox[]' value=$id></td>";
foreach ($get_info as $field)
print "\t<td align='center'><font face=arial size=1/>$field</font></td>\n";
print "</tr>\n";
}
print "</table>\n";
mysql_close();
?>
<!------------------------------------------------------------!>
</BODY>
</HTML>
Delete.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#####################################
if($_POST['delete']) {
$checkbox = $_POST['selected'];
$countCheck = count($_POST['selected']);
for($i=0;$i<$countCheck;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM ticket_history WHERE Auto = $del_id";
$result = mysql_query($sql);
}
}
?>
I just want to be able to delete rows checked. How would I go about doing this effectively and efficiently?
Thank you in advance.
The simple answer to your question would be to use:
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN ()',
implode(',', $checkbox));
However as people will jump in and tell you, you are vulnerable to SQL injection. You should never trust user input. You are deleting using an ID, which I'm assuming must be an integer.
Using something like this will validate that:
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
// If one is invalid, I would assume nothing can be trusted
// Depends how you want to handle the error.
die('Invalid input');
}
}
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
Other issues:
You seem to be using id's, but have not selected that field in your initial query.
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
Then you reference:
$id = $get_info->id;
Check the HTML output is actually what you expect.
In your delete query, you are referencing the field Auto. Is that your ID field?
And lastly, there no checking if the user has permission to do so. If this is a public site anyone can delete from that table.
Example of using two submit buttons within one form:
<?php
if (isset($_POST['create'])) {
echo "Create!";
}
elseif (isset($_POST['delete'])) {
echo "Delete!";
}
?>
<html>
<form method="post">
<input type="submit" name="create" value="Create"/>
<input type="submit" name="delete" value="Delete"/>
</form>
</html>

Categories