Inserting multiple rows into MySQL with checkbox - php

Below is my code. I have two MySQL database tables, one is "member" and another one is "participants". I would like to display the data in table "member" to my local host page and I did it. However, I cannot insert multiple rows of "member" data by using checkbox to my database table "participants". I am stuck. Any help is much appreciated.
<?php
try {
$con = new PDO("mysql:host=localhost;dbname=kgruum member", "root", "");
$sql = $con->query("SELECT * FROM member");
echo "<table class='info' align='center' border='1'>";
echo "<tr><td width='10'></td>
<td width='10'><b>ID</b></td>
<td width='500'><b>Name</b></td>
<td width='50'><b>Handicap</b></td><tr>";
foreach($sql as $row) {
$ID = $row["ID"];
$Name = $row["Name"];
$Handicap = $row["Handicap"];
echo "<tr>
<td><form method='POST' action='Add participant.php'><input type='checkbox' name='insert[]' value='$ID'></td>
<td>$ID</td>
<td>$Name</td>
<td>$Handicap</td><tr>";
}
echo"</table><div align='center'><input type='image' value='submit' src='add selected button.png' alt='submit Button' onmouseover='this.src='pink add selected button.png'' onmouseout='this.src='add selected button.png'' name='add_btn' id='add_btn'></div><br></form>";
if(isset($_POST['add_btn'])) {
if(!empty($_POST['insert'])) {
foreach($_POST['insert'] as $check) {
$st=$con->prepare("INSERT INTO participants(ID,Name,Handicap) VALUES('$ID','$Name','$Handicap')");
$insert->bindParam('ID',$ID);
$insert->bindParam('Name',$Name);
$insert->bindParam('Handicap',$Handicap);
$st->execute();
}
echo "<script type='text/javascript'>
alert('Successful Insert ! ');
window.location.href = 'Add participant.php';
</script>";
} else {
echo "<script type='text/javascript'>alert('You didn't choose which user you want to insert ! ')</script>";
}
}
} catch(PDOException $e) {
echo "error".$e->getMessage();
}
?>

You are not storing the $Name and $Handicap values in the insert[] array, you only storing the $ID value.
To resolve, do something like this:
<input type='checkbox' name='insert[]' value='$ID|$Name|$Handicap'>
Then:
foreach($_POST['insert'] as $check) {
$values = explode('|', $check);
$ID = $values[0];
$Name = $values[1];
$Handicap = $values[2];
//The rest of your SQL code goes here as you have it...
$check = '';
}

Related

Incorrect record updating

I am trying to update a specific row in a table; however, when the query runs, it updates the last record added instead of the record selected.
The SQL statement was taken straight from phpmyAdmin. I have tried "UPDATE registration_tbl SET Paid = 'PAID' WHERE ID='$row21'" and that still did not work.
Have I put something wrong in the code?
<table class="table table-striped table-hover table table-responsive-sm table-responsive-md table-responsive-lg">
<tr>
<th>Title</th>
<th>First Name</th>
<th>Last Name</th>
<th>Sex</th>
<th>Age</th>
<th>Address Type</th>
<th>Address 1</th>
<th>Address 2</th>
<th>Home</th>
<th>Work</th>
<th>Cell</th>
<th>Email Address</th>
<th>Congregation</th>
<th>RMC</th>
<th>Auxillary</th>
<th>Occupation</th>
<th>Category</th>
<th>Username</th>
<th>Submission Date</th>
<th>Payment Status</th>
<th>Action</th>
</tr>
<?php
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$result_set = mysqli_query($conn,"SELECT * FROM registration_tbl");
$num_messages = mysqli_num_rows($result_set);
$num = 0;
while($row = mysqli_fetch_array($result_set))
{
$row1 = $row["Title"];
$row2 = $row["FirstName"];
$row3 = $row["LastName"];
$row4 = $row["Sex"];
$row5 = $row["Age"];
$row6 = $row["AddressType"];
$row7 = $row["Address1"];
$row8 = $row["Address2"];
$row9 = $row["Home"];
$row10 = $row["Work"];
$row11 = $row["Cell"];
$row12 = $row["EmailAdd"];
$row13 = $row["Congregation"];
$row14 = $row["RMC"];
$row15 = $row["Auxillary"];
$row16 = $row["Occupation"];
$row17 = $row["Category"];
$row18 = $row["Username"];
$row19 = $row["DateSubmitted"];
$row20 = $row["Paid"];
$row21 = $row["ID"];
$num++;
echo "<tr>";
echo "<td>$row1</td>";
echo "<td>$row2</td>";
echo "<td>$row3</td>";
echo "<td>$row4</td>";
echo "<td>$row5</td>";
echo "<td>$row6</td>";
echo "<td>$row7</td>";
echo "<td>$row8</td>";
echo "<td>$row9</td>";
echo "<td>$row10</td>";
echo "<td>$row11</td>";
echo "<td>$row12</td>";
echo "<td>$row13</td>";
echo "<td>$row14</td>";
echo "<td>$row15</td>";
echo "<td>$row16</td>";
echo "<td>$row17</td>";
echo "<td>$row18</td>";
echo "<td>$row19</td>";
echo "<td>$row20</td>";
if($row20 != "PAID")
{
echo "<td><input type='submit' class='btn btn-success' name='paid' value='PAID' /></td></tr>";
}
}
echo "</table></br>";
echo "<table><tr><td>";
echo $num_messages . " Registration(s) Found!";
echo "</td></tr></table>";
if(isset($_POST['paid']))
{
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$updatePaymentStmt = "UPDATE `registration_tbl` SET `Paid` = 'PAID' WHERE `registration_tbl`.`ID` = $row21;";
if(mysqli_query($conn, $updatePaymentStmt))
{
echo "<script>alert('Payment updated successfully!')</script>";
}
else
{
echo "<script>alert('Error in updating Payment!')</script>";
}
}
I think you're going to want a separate form for each row in the table. And you'll need a hidden field in that form containing the ID so the server knows which ID to process when it receives the submission.
Remove any <form>...</form> tags you may have placed to wrap around the whole table, and instead use:
if($row20 != "PAID")
{
echo "<td><form action='' method='post'><input type='submit' class='btn btn-success' name='paid' value='PAID' /><input type='hidden' name='id' value='".$row["ID"]."'/></form></td></tr>";
}
and then
if(isset($_POST['paid']))
{
$id = $_POST["id"];
///etc, you can now use $id in a parameter in your query, to select the correct row
P.S. The rest of the code could also be greatly simplified, as others have mentioned in the comments, and you should definitely fix the SQL injection issue - that's a serious security problem.
This bug comes about from a flaw in your thinking rather than unexpected behaviour in the code.
Effectively you have a while loop that iterates over the entire results set (from the first query) and updates the $row* variables. What this means is that $row21 is always going to be the last selected record. If you were to chuck an ORDER BY id DESC on the end you'd find that the first record was always updated...
So what you actually want to do is add the id into the button - and make each button it's own form - so that when the form is posted the intended id is in the button's value.
Something like:
<?php
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$registrations = $mysqli->query($conn,"SELECT * FROM registration_tbl");
$num_messages = $registration->num_rows;
while ($row = $registrations->fetch_assoc() {
echo "<tr>";
echo "<td>{$row["Title"]}</td>";
echo "<td>{$row["FirstName"]}</td>";
echo "<td>{$row["LastName"]}</td>";
echo "<td>{$row["Sex"]}</td>";
echo "<td>{$row["Age"]}</td>";
echo "<td>{$row["AddressType"]}</td>";
echo "<td>{$row["Address1"]}</td>";
echo "<td>{$row["Address2"]}</td>";
echo "<td>{$row["Home"]}</td>";
echo "<td>{$row["Work"]}</td>";
echo "<td>{$row["Cell"]}</td>";
echo "<td>{$row["EmailAdd"]}</td>";
echo "<td>{$row["Congregation"]}</td>";
echo "<td>{$row["RMC"]}</td>";
echo "<td>{$row["Auxillary"]}</td>";
echo "<td>{$row["Occupation"]}</td>";
echo "<td>{$row["Category"]}</td>";
echo "<td>{$row["Username"]}</td>";
echo "<td>{$row["DateSubmitted"]}</td>";
echo "<td>{$row["Paid"]}</td>";
echo $row["Paid"]] !== "PAID" ?
"<td><form method='post'><button class='btn btn-success' name='paid' value='{$row["ID"]}'>Paid</button></form></td>" :
"<td></td>";
}
echo "</tr>";
}
echo "</table></br>";
echo "<table><tr><td>";
echo $num_messages . " Registration(s) Found!";
echo "</td></tr></table>";
if ($_POST['paid'] ?? null) {
$sql = "UPDATE `registration_tbl` SET `Paid` = 'PAID' WHERE `registration_tbl`.`ID` = ?";
$query = $mysqli->prepare($sql);
$query->bind_param("i", $_POST["paid"]);
echo $query->execute() ?
"<script>alert('Payment updated successfully!')</script>" :
"<script>alert('Error in updating Payment!')</script>";
}
}

How to create dynamic insert query using php and mysql? [duplicate]

hi friends i'm creating a php page to import the data from a csv file into sql database..
here database table and number of fields are specified by user itself..
if user specifies 4 fields, then it is created using a for loop as follows..
<?php
include('connect.php');
$name = $_POST['table_name'];
//echo $name;
$create_tab = "CREATE TABLE $name(id varchar(15) PRIMARY KEY)";
if(mysql_query($create_tab,$con))
{
echo "Table <b><i>$name</i></b> created successfully... <br/> <br/>Add columns...";
}
else {
die('Error1'.mysql_error());
}
$field = $_POST['number_of_fields'];
//echo $name.$field;
echo '<form id="form1" name="form1" method="post" action="update-table.php">';
echo "<p>
<label for='tablename'></label>
<input type='hidden' name='tablename' id='tablename' value='$name' size='5'/>
</p>";
echo "<p>
<label for='fields'></label>
<input type='hidden' name='fields' id='fields' value='$field' size='5'/>
</p>";
echo '<table border="1" cellpadding="5" cellspacing="5">';
for ( $i = 1; $i <= $field; $i ++) {
echo '<tr>';
echo '<td>';
echo "<p>
$i
</p>";
echo'</td>';
echo '<td>';
echo "<p>
<label for='textfield$i'></label>
<input type='text' name='field$i' id='textfield$i' />
</p>";
echo'</td>';
echo '<td>';
echo "
<select name='select$i' id='select$i'>
<option value='varchar(200)'>varchar</option>
<option value='int'>int</option>
<option value='float'>float</option>
<option value='date'>date</option>
</select>";
echo '</td>';
echo '</tr>';
}
echo '</table>';
?>
<p>File Location :
<input type="text" name="fileField" id="fileField" />
</p>
<br/>
<INPUT type="image" name="search" src="images/alter.gif" border="0" height="75" width=120">
</form>
then table create and alter as follows..
<?php
include('connect.php');
$field = $_POST[fields];
$name = $_POST[tablename];
for ( $i = 1; $i <= $field; $i++) {
//getting field names
$varname = ($txtfield . $i);
$$varname = $_POST[field.$i];
// echo $$varname;
$fi = $$varname;
//getting field types
$selname = ($selfield . $i);
$$selname = $_POST[select.$i];
$dt = $$varname;
$sql = "ALTER TABLE $name ADD $fi $dt";
if(mysql_query($sql,$con))
{
echo "Field <b><i>$fi</i></b> added successfully...<br/>";
}
else {
die('Error1'.mysql_error());
}
}
?>
as above database table and fields are crated...
i got the concept of inserting data using static variables as follows..
<?php
// data import
include('connect.php');
$field = $_POST['fileField']; //file directory
echo "<br/><br/>Import file path: ";
echo $field;
$file = $field;
$lines = file($file);
$firstLine = $lines[0];
foreach ($lines as $line_num => $line) {
if($line_num==0) { continue; } //escape the header column
$arr = explode(",",$line);
$column1= $arr[0];
$column2= $arr[1];
// ' escape character
if (strpos($column2, "'") == FALSE)
{
$column21 = $column2;
}
else{
$column21 = str_replace ("'", "\'", $column2);
}
$column3= $arr[2];
$column4= $arr[3];
//print data from csv
echo "<table border='1' width='800' cellpadding='5' cellspacing='2'>";
echo "<tr>";
echo "<td width='8'>";
echo $column1;
echo "</td>";
echo "<td width='100'>";
echo $column21;
echo "</td>";
echo "<td width='5'>";
echo $column3;
echo "</td>";
echo "<td width='5'>";
echo $column4;
echo "</td>";
echo "</tr>";
echo "</table>";
$import="INSERT into $name (id,name,year1,year2) values(
'$column1','$column21','$column3','$column4')";
mysql_query($import) or die(mysql_error());
}
?>
now, my question is how can i make this insert statement dynamic as such it creates field names and values dynamically inside insert query from the data obtained from for loop in table create and alter query???
If I understand your question correctly, it sounds like you want to combine your inserts into one query (which is very smart performance wise). SQL allows you to insert multiple rows at once like so:
INSERT INTO table (id, first, last) VALUES(NULL, 'Ryan', 'Silvers'),(NULL, 'Oscar', 'Smith'),(NULL, 'Jessica', 'Owens')
So by using creating an array of VALUES and using implode to join them you can make one query:
//Create rows
foreach($rows as $row) {
$queryRows[] = "(NULL, '".$row['first']."', '".$row['last']."')";
}
//Create query
$query = 'INSERT INTO table (id, first, last) VALUES'.implode(',', $queryRows);
Now that I understand your real question, I can give you a basic overview of what you need to do to achieve this. You need to create a form that allows a user to enter data that will be inserted into the table.
<form method="post" action="process.php">
<input name="field1" />
<!-- and more -->
</form>
Then you need to write a PHP script to process the form submission and insert the data into MySQL:
<?php
//Check form submission and validate entries, then...
$stmt = $pdo->prepare('INSERT INTO table (field1) VALUES(:field1)');
$stmt->execute(array(':field1', $_POST['field1']));
?>
Then you need to write a PHP script to process the form submission and insert the data into MySQL:
function insert($tablet,$datad)
{
if(empty($tablet)) { return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$query1 = "select * from user";
$result1 = mysql_query($query1);
$numcolumn = mysql_num_fields($result1);
$addd = "";
$count = 0;
for ( $i = 1; $i < $numcolumn; $i++ )
{
$columnnames = mysql_field_name($result1, $i);
if(($numcolumn-1) == $i)
{
$addd .= $columnnames;
$data .= "'".$datad[$count]."'";
}
else
{
$addd .= $columnnames.",";
$data .= "'".$datad[$count]."',";
}
$count++;
}
$ins = "INSERT INTO ".$tablet."(".$addd.")"."VALUES(".$data.")";
mysql_query($ins);
header('Location: index.php');
exit;
}

Insert that particular value changed record

From the below code, if it displays 10 records and if the user changes 'Code' or 'Number' value of 2nd and 5th record, how to insert only that 2nd and 5th record in another separate table. But from my insert query i can insert all 10 records. But i need only two affected records to be inserted. Please help.
include('DB.php');
$sql="SELECT * FROM customer where customer_name='".$q."' ";
$result = mysql_query($sql);
$num_row = mysql_num_rows($result);
$row_count=1;
if($num_row>0)
{
echo "<table >
<tr>
<th>S.No</th>
<th>Name</th>
<th>Code</th>
<th>Number</th>
</tr>";
while($row = mysql_fetch_array($result)) {
$c_name=$row['c_name'];
$c_code=$row['c_code'];
$c_number=$row['c_number'];
echo "<tr>";
echo "<td> $row_count.</td>";
echo "<td><input type='text' name='c_name[]' id='c_name' value='$c_name' readonly /></td>";
echo "<td><input type='text' name='c_code[]' id='c_code' value='$c_code' /></td>";
echo "<td><input type='text' name='c_number[]' id='c_number' value='$c_number' /></td>";
echo "</tr>";
$row_count++;
}
echo "</table>";
}
INSERT:
$c_name=$_POST['c_name'];
$c_code=$_POST['c_code'];
$c_number=$_POST['c_number'];
if(isset($c_code))
{
for($i=0;$i<count($c_code);$i++)
{
{
$insert=mysql_query("INSERT INTO customer_table2(name,code,number)
VALUES ('$c_name[$i]','$c_code[$i]','$c_number[$i]')");
}
}
Do a SELECT query first, to see if the row is already in the original table. If not, add it to the new table.
$c_name=$_POST['c_name'];
$c_code=$_POST['c_code'];
$c_number=$_POST['c_number'];
if(isset($c_code))
{
for($i=0;$i<count($c_code);$i++)
{
// Prevent SQL injection
$name = mysql_real_escape_string($c_name[$i]);
$code = mysql_real_escape_string($c_code[$i]);
$number = mysql_real_escape_string($c_number[$i]);
$select = mysql_query("SELECT COUNT(*) AS c FROM customer WHERE name = '$name' AND code = '$code' AND number = '$number'");
$row = mysql_fetch_assoc($select);
if ($row['c'] == 0) {
$insert=mysql_query("INSERT INTO customer_table2(name,code,number)
VALUES ('$name','$code','$number')");
}
}
}

How to add update, delete and view button in my php rows

I want to add "update", "delete" and "view" in the other page button in the right side of the table rows of my php table. Please help me to add it. Here is my code:
<?php
$conn = mysqli_connect('localhost','root','','dbname');
if(mysqli_connect_errno()){
echo 'Failed to connect: '.mysqli_connect_error();
}
$query = "SELECT * FROM table";
$results = mysqli_query($conn,$results);
echo '<table border="1">';
echo '<tr>';
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo '</tr>';
while($row=mysqli_fetch_array($results)){
echo '<tr>';
echo '<td>'.$row['Firstname'].'</td>';
echo '<td>'.$row['Lastname'].'</td>';
echo '</tr>';
}
echo '</table>';
mysqli_close($conn);
?>
echo '<tr>';
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo "<th>Actions</th>";
echo '</tr>';
while($row=mysqli_fetch_array($results)){
echo '<tr>';
echo '<td>'.$row['Firstname'].'</td>';
echo '<td>'.$row['Lastname'].'</td>';
echo "<td>
Update
Delete
View
</td>";
echo '</tr>';
}
echo '</table>';
You should use jquery/Ajax for delete. It is better option.
For delete write this function: Need to add min jquery file
<script src="js/jquery-1.7.1.min.js"></script>
<script>
function deleteRow(id)
{
$.ajax({
url: 'delete.php',
type: "POST",
data: {
'id' : id,
},
success : function(response) {
alert('Record deleted');
},
error : function() {
},
complete : function() {
}
});
}
</script>
write your delete record code in 'delete.php'.
This is one option. You can do this in more good and specific way. Everything to say here is not possible for me.
for view you can do this in two ways.
1) If you want to display in same format, redirect it on self page and put condition like.
if(isset($_POST['id'])
{
$id = $_POST['id'];
$query = "SELECT * FROM table where id=$id";
}
else
{
$query = "SELECT * FROM table";
}
2) If you want in different format, Do same thing in view.php select only that record.
One simple thing i want to ask what is the need for view? when it is already in table above.
For Update write in your update.php :
if(isset($_POST['id'])
{
$id = $_POST['id'];
$query = "SELECT * FROM table where id=$id";
}
and set form action
<form method="post" action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>">
fetch value of above result in input box like and also fetch id as hiiden field:
<input type='text' name='firstname' value='<?php echo $row['firstname']; ?>
<input type='hidden' name='id' value='<?php echo $row['id']; ?>
and for update you can go like:
if(isset($_POST['firstname'] && isset($_POST['lastname'] ) // Here you can use your any required field
{
//Your update logic go here like:
$id = $_POST['id'];
$query = "UPDATE table SET firstname=$_POST['firstname'] where id=$id"; // Your whole update query.
}
i see some mistake in your code:
$query = "SELECT * FROM table";
$results = mysqli_query($conn,$results);
should be:
$query = "SELECT * FROM table";
$results = mysqli_query($conn,$query);
try this
echo '<table border="1">';
echo '<tr>';
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo "<th></th>";
echo '</tr>';
while($row=mysqli_fetch_array($results)){
echo '<tr>';
echo '<td>'.$row['Firstname'].'</td>';
echo '<td>'.$row['Lastname'].'</td>';
echo "<td>
<input type='submit' value='update'>
<input type='submit' value='delete'>
<input type='submit' value='view'>
</td>";
echo '</tr>';
}
echo '</table>';
Try this functions:
<?php
Class Db {
protected $connection;
public function __construct() {
$this->connection = $connection;
}
function insert($table,array $data) {
$fields = '';$values = '';
foreach($data as $col => $value) {
$fields.= $col.",";
}
foreach($data as $col => $value) {
$values.= "'".replace_str($value)."',";
}
$fields = substr($fields,0,-1);
$values = substr($values,0,-1);
if(!$query = mysqli_query($this->connection,"insert into ".$table."(".$fields.") values(".$values.")")) {
HandleDBError("Error inserting data to the table\query:$query");
}
return $query;
}
function update($table, array $data, $where) {
$fields = '';$values = '';
foreach($data as $col => $value) {
$values.= $col."='".replace_str($value)."',";
}
$values = substr($values,0,-1);
if(!$query = mysqli_query($this->connection,"update ".$table." set ".$values." where ".$where)) {
HandleDBError("Error updating data to the table\query:$query");
}
return $query;
}
function delete($table, $where = '') {
if ($where)
return mysqli_query($this->connection,"delete from ".$table." where ".$where);
return mysqli_query($this->connection,"delete from ".$table);
}
function get($strQuery) {
if(!$query = mysqli_query($this->connection,$strQuery)) {
HandleDBError("Error inserting data to the table\query:$query");
}
$data = [];
while($row = mysqli_fetch_assoc($query)) {
$data[] = $row;
}
return $data;
}
}
?>

Create hyperlink on table result and fill editable form in other page

I'm having problems to find how to create an hyperlink in a table column result and then, on click, open another page with all fields (textboxes) filled. Imagine when a click an ID, i do a select * from table where column_id = ID... Is there a way to do it?
Thanks.
Best regards
I'm not completely sure what you are asking, but this may help you a bit.
First make a Javascript.
<script type="text/JavaScript">
function selectID() {
var ID = document.getElementById("ID").value;
document.location.href ="yoursite.php?ID="+ID;
}
</script>
Then connect to your database to query the table for a link ID (or more) for example by changing the variable $value.
<?php
//Connect to database
mysql_connect("host", "user", "pass");
mysql_select_db("db_name");
$value = 'something';
$ID = $_GET['ID'];
if (!$ID) {
$ID = 0;
}
if ($ID == 0) {
$query = "SELECT * FROM table WHERE `column_1` = '$value'";
$result = mysql_query($query);
echo "<table>";
while($myrow = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>";
echo "ID";
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
elseif ($ID > 0) {
$query2 = "SELECT * FROM table WHERE `column_id` = '$ID'";
$result2 = mysql_query($query2);
while($myrow2 = mysql_fetch_array($result2)) {
$value1 = $myrow2['column_1'];
$value2 = $myrow2['column_2'];
}
echo "<form type=\"GET\" action=\"$PHP_SELF\">";
echo "<input type=\"text\" id=\"ID\" name=\"ID\" value=\"$ID\"><br>";
echo "<input type=\"text\" id=\"value1\" name=\"value1\" value=\"$value1\"><br>";
echo "<input type=\"text\" id=\"value2\" name=\"value2\" value=\"$value2\"><br>";
echo "<input type=\"hidden\" id=\"search\" name=\"search\" value=\"searching\">";
echo "<input type=\"submit\" id=\"submitbutton\" name=\"submitbutton\" value=\" Search \">";
echo "</form>";
}
?>

Categories