I want to insert into my mysql database only those rows that have a checked checkbox at the end.
Since i have several tables and table data cells that have the same name, then my data is stored in arrays (product_name[] etc.):
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<?php
while($res = mysqli_fetch_array($result)) {
echo "<table id='tbl'>
<thead><th name='category[]'>".$res['category_name']."</th></thead>
<tbody>
<tr>
<td><input name='product_name[]' id='name' type='text'></td>
<td><input name='quantity[]' type='text' value='1'></td>
<td><input type='checkbox' name='check[]'></td>
</tr>
</tbody>";
}
?>
</table>
<div class="bottom-btn">
<button id="submit" type="submit">Lisa märgitud külmkappi</button>
</div>
</form>
Do i have to store the checkboxes in array as well (check[])?
My php code for the insert:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$product_name = $_POST['product_name'];
$quantity = $_POST['quantity'];
// $check = $_POST['check'];
foreach($product_name as $i=>$product_name)
{if(!empty($product_name)){
$sql = "INSERT INTO products (id, product_name, category, quantity, expiration_date, barcode) VALUES ('','$product_name', '', '$quantity[$i]', '', '')";
if($stmt = mysqli_prepare($conn, $sql)){
mysqli_stmt_bind_param($stmt, "ss",$param_product_name, $param_quantity);
$param_product_name = $product_name;
$param_quantity=$quantity;
if(mysqli_stmt_execute($stmt)){
header("location: myFridge.php");
} else{
echo "Something went wrong. Please try again later.";
}
mysqli_stmt_close($stmt);
}
}
}
mysqli_close($conn);
}
So far i have tried this: if(!empty($_POST['check'])) and this if(isset($_POST['check']) , but those did not work.
How to check if checkbox is checked before inserting data to database?
EDIT. WORKING.
I added this code to my page to make an array of checkbox on and off values:
function getAllCheckboxValues($check){
$found = array();
foreach ($check as $key => $val){
if($val == 'on'){
$found[] = $key;
}
}
foreach($found as $kev_f => $val_f){
unset($check[$val_f-1]);
}
$final_arr = array();
return $final_arr = array_values($check);
}
$checkbox_arr = getAllCheckboxValues($_POST['check']);
And also added a hidden input before every checkbox:
<input type='hidden' name='check[]' value='off'>
Then matched the checbox array with my products array and voila!
You could simply var_dump($_POST) to see whats in your post request. That always helps when facing issues like that.
Checkboxes come with the value on if they are checked and off if they are not, so it will never be empty and always be set, which is why your checks did not work. You should check if($_POST['check'] === 'on') instead.
Related
My table category has these columns:
idcategory
categorySubject
users_idusers
I have a form with a simple radio buttons and a textbox.
I have a select all statement for category and need to get the idcategory stored into a variable ($getCatId) so I can use this statement:
$sql="INSERT INTO topic(subject, topicDate, users_idusers, category_idcategory, category_users_idusers) VALUES('($_POST[topic])', '$date', '$_SESSION[userid]', '$getCatId', '$_SESSION[userid]');";
What is the best way to get and store categoryid?
if($_SERVER['REQUEST_METHOD'] != 'POST') //show form if not posted
{
$sql = "SELECT * FROM category;";
$result = mysqli_query($conn,$sql);
?>
<form method="post" action="createTopic.php">
Choose a category:
</br>
</br>
<?php
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class= 'choice'><input type='radio' name='category' value='". $row['idcategory'] . "'>" . $row['categorySubject'] ."</div></br>";
}
echo 'Topic: <input type="text" name="topic" minlength="3" required>
</br></br>
<input type="submit" value="Add Topic" required>
</form>';
}
if ($_POST){
if(!isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == false)
{
echo 'You must be signed in to contribute';
}
else{
$sql="INSERT INTO topic(subject, topicDate, users_idusers, category_idcategory, category_users_idusers) VALUES('($_POST[topic])', '$date', '$_SESSION[userid]', '$getCatId', '$_SESSION[userid]');";
$result = mysqli_query($conn,$sql);
echo "Added!";
If I understand this question correctly, you'll have your $getCatId (id of the category) in $_POST['category'] (after sending form) in your case
The first thing you should do is protect yourself from SQL injection by parameterizing your queries before old Bobby Tables comes to pay you a visit.
You might also look into using PDO as I've demonstrated below because it's a consistent API that works with a lot of different database management systems, so this leads to wonderfully portable code for you. Here's an annotated working example on Github:
<?php
// returns an intance of PDO
// https://github.com/jpuck/qdbp
$pdo = require __DIR__.'/mei_DV59j8_A.pdo.php';
// dummy signin
session_start();
$_SESSION['signedIn'] = true;
$_SESSION['userid'] = 42;
//show form if not posted
if($_SERVER['REQUEST_METHOD'] != 'POST'){
$sql = "SELECT * FROM category;";
// run query
$result = $pdo->query($sql);
?>
<form method="post" action="createTopic.php">
Choose a category:
</br>
</br>
<?php
// get results
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "
<div class= 'choice'>
<input type='radio' name='category' value='$row[idcategory]'/>
$row[categorySubject]
</div>
</br>
";
}
echo '
Topic: <input type="text" name="topic" minlength="3" required>
</br></br>
<input type="submit" value="Add Topic" required>
</form>
';
}
if ($_POST){
if(!isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == false){
echo 'You must be signed in to contribute';
} else {
// simulate your date input
$date = date("Y-m-d");
// bind parameters
$sql = "
INSERT INTO topic (
subject, topicDate, users_idusers, category_idcategory, category_users_idusers
) VALUES(
:subject, :topicDate, :users_idusers, :category_idcategory, :category_users_idusers
);
";
// prepare and execute
$statement = $pdo->prepare($sql);
$statement->execute([
'subject' => "($_POST[topic])",
'topicDate' => $date,
'users_idusers' => $_SESSION['userid'],
// to answer your question, here's your variable
'category_idcategory' => $_POST['category'],
'category_users_idusers' => $_SESSION['userid'],
]);
echo "Added!";
}
}
So I'm just making a simple program that puts names into a database. I got that part down, I can enter a name into a form, then display it on the page, but now I'd like to know how to delete them from the database, and no longer show them on the page.
I added a button next to each name that triggers the third if statement (with the commented out query), and from what I can tell it's best to run a query based on the element's id (my primary key that auto increments), but I have no idea how to get the id from the element who's button I'm clicking on.
How do I get the id from one of the elements in my while loop? Or if there's a better way to delete them, what's that?
if (mysqli_connect_errno()) {
die('could not connect');
}
if (isset($_POST['first_name'], $_POST['last_name'])){
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
$putitin = mysqli_query($db, "INSERT INTO names (first_name, last_name) VALUES ('$first_name', '$last_name')");
}
if (isset($_POST['del'])){
//$takeitout = mysqli_query($db, "DELETE FROM names WHERE id = ");
}
?>
<html>
<head>
</head>
<body>
<form action='' method='post'>
<div>
<label for "first_name">First name</label>
<input type="text" name="first_name">
</div>
<div>
<label for "last_name">Last name</label>
<input type="text" name="last_name">
</div>
<div>
<input type="submit" value="Insert">
</div>
</form>
<hr>
<?php
$resultset = $db->query('SELECT * FROM names');
if($resultset->num_rows != 0){
while($rows = $resultset->fetch_assoc()) {
$fname = $rows['first_name'];
$lname = $rows['last_name'];
$id = $rows['id'];
echo "<form action='' method='post'><p>Name: $fname $lname $id<input type='submit' name='del'></form></p>";
}
} else {
echo 'No results';
}
?>
</body>
</html>
This is one way.
change your html part to
<form action='' method='post'>
<input type='hidden' name='id' value='$id' />
<p>Name: $fname $lname $id
<input type='submit' name='del' value=''>
</form></p>
and your php
if (isset($_POST['del'])){
$id = $_POST['id'];
$takeitout = mysqli_query($db, "DELETE FROM names WHERE id = '$id'");
}
Note:
What you can do is to put all your input fields inside your while loop. Then assign values to each of them, but we have to use array to store them accordingly.
We can use checkbox to store the IDs.
What will happen, is user can select from the list of names they wanted to delete by ticking the corresponding checkbox, then pressing the Delete button below.
Your code
<form action="" method="POST">
<?php
$resultset = $db->query('SELECT * FROM names');
if($resultset->num_rows != 0){
while($rows = $resultset->fetch_assoc()) {
$fname = $rows['first_name'];
$lname = $rows['last_name'];
$id = $rows['id'];
echo '<input type="checkbox" name="id[]" value="'.$id.'">'.$fname.' '.$lname.'<br>';
} /* END OF WHILE LOOP */
?>
<input type="submit" value="Delete" name="delete">
</form>
And your PHP that will process the form:
<?php
if(isset($_POST["delete"])){
$counter = count($_POST["id"]);
for($x = 0; $x<$counter; $x++){
if(!empty($_POST["id"][$x])){ /* CHECK IF AN ITEM IS SELECTED */
/* DELETE QUERY */
if($stmt = $db->prepare("DELETE FROM names WHERE id = ?")){
$stmt->bind_param("i",$_POST["id"][$x]);
$stmt->execute();
$stmt->close();
} /* END OF PREPARED STATEMENT */
} /* END OF IF; CHECKING IF IT IS SELECTED */
} /* END OF FOR LOOP */
} /* END OF ISSET DELETE */
?>
I have a table form which has a add new row button which upon clicked adds a new row to the table. I am trying to save all the rows in MySQL on clicking save button.
The code I wrote saves only one row no matter how many row I add. Could someone please tell my what am I doing wrong.
I searched Google but couldn't get anywhere.
Here are my codes:
save.php
<?php
include('connection.php');
if(isset($_POST['submit'])){
$row_data = array();
foreach($_POST['category'] as $row=>$category){
$category = mysql_real_escape_string($category);
$itemName = mysql_real_escape_string($_POST['itemName'][$row]);
$brand = mysql_real_escape_string($_POST['brand'][$row]);
$model = mysql_real_escape_string($_POST['model'][$row]);
$sellingPrice = mysql_real_escape_string($_POST['sellingPrice'][$row]);
$row_data[] = "('$category','$itemName','$brand','$model','$sellingPrice')";
}
}
if(!empty($row_data)){
$insert_query = mysql_query("INSERT INTO sale(Category,ItemName,Brand,Model,SellingPrice) VALUES".implode(',', $row_data));
if(!$insert_query){
echo "Error: " . mysql_error();
}else{
echo "Data Saved Successfully";
}
}
?>
and this is my html form
<form name="form1" id="myForm" action="saveSale.php" method="post">
<tr class="cloneme">
<td><input type="text" name="category[]"></td>
<td><input type="text" name="itemName[]"></td>
<td><input type="text" name="brand[]"></td>
<td><input type="text" name="model[]"></td>
<td><input type="text" name="sellingPrice[]"></td>
</tr>
</tbody>
</table>
</div>
<div class="eventButtons">
<input type="submit" name="submit" id="submit" value="Save">
<input type="reset" name="reset" id="reset" value="Clear" class="btn">
</div>
</form>
You are inserting data outside the for loop so it inserts only the last row or data.. What you have to do is to place insert query within foreach or for loop
if(isset($_POST['submit'])){
$row_data = array();
for($i = 0 ; $i < count($_POST['category']);$i++){
$category = mysql_real_escape_string($_POST[$i]['category']);
$itemName = mysql_real_escape_string($_POST[$i]['itemName']);
$brand = mysql_real_escape_string($_POST[$i]['brand']);
$model = mysql_real_escape_string($_POST[$i]['model']);
$sellingPrice = mysql_real_escape_string($_POST[$i]['sellingPrice']);
$insert_query = mysql_query("INSERT INTO sale(Category,ItemName,Brand,Model,SellingPrice) VALUES ('$category','$itemName','$brand','$model','$sellingPrice')");
if(!$insert_query){
echo "Error: " . mysql_error();
}else{
echo "Data Saved Successfully";
}
}
}
As I dont have enough reputation I am adding my comment as answer.
Your code is fine. It should work. There might be problem while you are cloning the row, may be it is not getting added under the form tag. You can verify it by dumping the $row_data variable.
Please share your javascript code which makes clone of the row, it will help us to solve your problem.
You need to run your query in for loop by counting the array value using count($_POST['category'])
if(isset($_POST['submit'])){
$row_data = array();
for($i= 0; $i <count($_POST['category']);$i++){
$category = mysql_real_escape_string($_POST[$i]['category']);
$itemName = mysql_real_escape_string($_POST[$i]['itemName']);
$brand = mysql_real_escape_string($_POST[$i]['brand']);
$model = mysql_real_escape_string($_POST[$i]['model']);
$sellingPrice = mysql_real_escape_string($_POST[$i]['sellingPrice']);
$insert_query = mysql_query("INSERT INTO sale(Category,ItemName,Brand,Model,SellingPrice) VALUES ('$category','$itemName','$brand','$model','$sellingPrice')");
if(!$insert_query){
echo "Error: " . mysql_error();
}else{
echo "Data Saved Successfully";
}
}
}
after trying to debug this snipet of code for hours, I find I cannot figure out why my edit form wont update for the life of me. I'm not sure if it's because I'm not using GET or POST methods correctly, I'm mis-using mysql, or a combination of the both. I cant even figure out why a line of print "hi"; wont show up. if i take out the line of code testing when the edit submit button is hit the print lines come out but my database wont update. So I figure I'm stuck where I can't do anymore print line debugging untill I figure out what I'm doing wrong. here is my code.. I commented next to the "print "hi";" line that doesnt show up. keep in mind I'm pretty sure I tried every combination of GET and POST and it still doesnt show up...
<html lang="en">
<head>
<title>Employee</title>
</head>
<body>
Clean <br>
<form method="post" action="employ.php">
<input type="text" name="fname">First Name<br>
<input type="text" name="lname">Last Name<br>
<input type="text" name="email">email<br>
<input type="text" name="zip">zip code<br>
<input type="submit" name="add" value="Add"> <!-- button itself -->
</form>
<br>
<?php //server login name password database
$link = mysqli_connect("server", "login", "password", "database") or die(mysqli_error());
if(isset($_POST['add'])) //this processes after user submits data.
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$zip = $_POST['zip'];
$re = "/^[a-zA-Z]+(([\'\- ][a-zA-Z])?[a-zA-Z]*)*$/";
$reEmail = "/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/";
$reZip = "/^\d{5}$/";
//if user passes re test
if( preg_match($re, $fname) && preg_match($re, $lname)
&& preg_match($reEmail, $email) && preg_match($reZip, $zip) )
{ //display current table
$querycheck = "select * from employees where fname='$fname' and email='$email'";
$resultcheck = mysqli_query($link, $querycheck); //link query to database
if(mysqli_num_rows($resultcheck) == 0)// test if query does "nothing"
{//if not process the insert query
$query = "insert into employees values('', '$fname', '$lname', '$email', '$zip')";
mysqli_query($link, $query); //link query to database
print "Employee Added"; // print confirmation
}
else
{
print "That record already exists!";
}
}
else
{
print "You did not fill out the form correctly!";
}
} ////////////////////////////////edit portion/////////////////////////////
if(isset($_GET['edit']))
{
print "teseting edit<br><br>";
?>
<form method="get" action="employ.php">
<input type="text" name="fname" value = "<?php echo $_GET['fname']?>">First Name<br>
<input type="text" name="lname" value = "<?php echo $_GET['lname']?>">Last Name<br>
<input type="text" name="email" value = "<?php echo $_GET['email']?>">email<br>
<input type="text" name="zip" value = "<?php echo $_GET['zip']?>">zip code<br>
<input type="hidden" name="employeeid" value = "<?php echo $_GET['employeeid']?>">
<input type="submit" name="endedit" value="Edit"> <!-- button itself -->
</form>
<?php
print "teseting end edit <br><br>";
if(isset($_POST['endedit'])) //this processes after user submits edited data
{ //tried get and post
print "hi"; // DOESNT APPEAR
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$zip = $_POST['zip'];
$employeeidtemp = $_POST['employeeid'];
$re = "/^[a-zA-Z]+(([\'\- ][a-zA-Z])?[a-zA-Z]*)*$/";
$reEmail = "/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/";
$reZip = "/^\d{5}$/";
//if user passes re test
if( preg_match($re, $fname) && preg_match($re, $lname)
&& preg_match($reEmail, $email) && preg_match($reZip, $zip) )
{ //display current table
//$querycheck = "select * from employees where employeeid='$employeeidtemp'";
//$resultcheck = mysqli_query($link, $querycheck); //link query to database
// if(mysqli_num_rows($resultcheck) == 0)// test if query does "nothing"
// {
$query = "UPDATE employees SET fname='$fname', lname='$lname', email='$email', zip='$zip' WHERE employeeid='$employeeidtemp'";
mysqli_query($link, $query); //link query to database
print "Employee Updated"; // print confirmation
// }
// else
// print "huh?";
}
else
{
print "You did not fill out the form correctly!";
}
}
}
if(isset($_GET['delete']))
{
print "teseting delete<br><br>";
}
showemp();
function showemp()
{
global $link;
if(isset($_GET['choice']))
{
$choice = $_GET['choice'];
}
else
{
$choice = "lname";
}
$query = "select * from employees order by $choice";
$result = mysqli_query($link, $query);
// print table (happens first before input)
// first print row of links/headers that sort
print "<table border='1'>
<tr>
<th>Edit</th>
<th>Delete</th>
<th><a href='employ.php?choice=fname'>FNAME</a></th>
<th><a href='employ.php?choice=lname'>LNAME</a></th>
<th><a href='employ.php?choice=email'>EMAIL</a></th>
<th><a href='employ.php?choice=zip'>ZIP</a></th>
</tr>";
//while the next row (set by query) exists?
while($row = mysqli_fetch_row($result))
{
list($employeeid, $fname, $lname, $email, $zip) = $row;
print "<tr>
<td><a href='employ.php?edit=yes&employeeid=$employeeid&fname=$fname&lname=$lname&email=$email&zip=$zip'>Edit</a></td>
<td><a href='employ.php?delete=yes&employeeid=$employeeid
onclick='return confirm(\"Are you sure\")'>Delete</a></td>
<td>$fname</td>
<td>$lname</td>
<td>$email</td>
<td>$zip</td>
</tr>";
}
print "</table>";
}
?>
</body>
</html>
You have several errors:
You do not check the result of queries, use at least
code mysqli_query($link, $query) or die(mysqli_error($link));
When I kick your code with checking errors, I found that adding query does not work - your empty string value for employeeid does not accepted for my integer field.
Do not use GET in forms. Always POST. If you need reaction on GET-url, write it separately or use $_REQUEST var.
In INSERT query always write fields. When you will decide to change list of fields in mysql table, then you can get the strange behavior of this code.
Your main error is that your condition with print 'hi' is inside the condition if(isset($_GET['edit'])), it does not work when user sublim form.
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.