multiple checkbox post form - php

The below code will only work with one checkbox and ignores the rest. Is there any way that I can have it to delete selected checkboxes? I have tried using implode but it gives me
Warning: implode(): Invalid arguments passed
<form action="" method="post">
<input type="checkbox" name="id" class="check" value = "<?php echo $row['id']; ?>">
<?php echo $row['to_user'];?>
<input type="submit" name="delete">
</form>
<?php
if (isset($_POST['delete'])) {
$id = $_POST['id'];
$ids = implode( ',', $id );
$mydb = new mysqli('localhost', 'root', '', 'database');
$stmt = $mydb->prepare("update messages set deleted = 'yes' where from_user = ? and id = ? ");
$stmt->bind_param('ss', $user, $ids);
$stmt->execute();
echo "Message succesfully deleted";
exit();}
?>

Give the checkbox an array-style name:
<input type="checkbox" name="id[]" class="check" value = "<?php echo $row['id']; ?>">
This will cause $_POST['id'] to be an array of all the checked values. Then delete them in a loop:
$mydb = new mysqli('localhost', 'root', '', 'database');
$stmt = $mydb->prepare("update messages set deleted = 'yes' where from_user = ? and id = ?");
$stmt->bind_param('ss', $user, $id);
foreach ($_POST['id'] as $id) {
$stmt->execute();
}
You can't use a comma-separated list of IDs with =. You can use it with id in (...), but you can't do parameter substitution with this because the number of elements isn't known. So the loop is th best way to do it.

Related

PHP Form not updating

I'm totally stuck on a problem. I'm practicing MySQL data inserts from php, but I am unable to get it working. I am totally new when it comes to php. With MySQL and HTML, I did a few courses on it, so you can say I'm a beginner. This is part three of the example, the first example you have to list all the animals in the table, that part I got working, then the second part is where I have to use a named parameters to extract specific animal types, and it also works fine. Now I'm stuck with the last one inserting data. I have a simple form with animal name and animal type as text boxes, when I click on submit the updated row must auto update in example one and show in the table, but when I click on submit, nothing happens, nothing is inserted into the database, but when I refresh the page or click submit again, then only do I see the updated data. And when fill in data in the two text fields after I clicked refresh or submit, blank data is inserted into the database.
<?php
$db = 'mysql:host=localhost;dbname=animals';
$username = 'root';
$password = '';
$animal_type = $_POST[animal_type];
$animal_name = $_POST[animal_name];
$query = "INSERT INTO animals
(animal_type, animal_name)
VALUES
('$animal_type', '$animal_name')";
$animal = $db->prepare($query);
$animal->bindValue(':animal_id', $animal_id);
$animal->execute();
$animals = $animal->fetchAll();
$animal->closeCursor();
?>
<form action="example3.php" method="post">
Animal Name: <input type="text" name="animal_name"><br>
Animal Type: <input type="text" name="animal_type"><br>
<input type="submit" />
</form>
Any help would be greatly appreciated.
JasonK
Update
So this is what it looks like when completed, but you see those blank entries is what happens when I fill in animal type and animal name and click submit - it just leaves the fields blank, I checked in the database, it does the insert when I click submit. I deduced that whenever I click submit or do a page refresh, it runs the whole code again that is where the blank entries comes from.
This is what my whole code look like.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
/////////////////////////////////////////////////////////////////////////////////Example1/////////////////////////////////////////////////////////////////////////////////////////
<?php include 'menu.inc';
$db = 'mysql:host=localhost;dbname=animal';
$username = 'jason';
$password = '';
try {
$db = new PDO($db, $username, $password);
echo 'Connection successful';
echo '<br />';
}
catch(PDOException $e)
{
echo 'Connection failed' . $e->getMessage();
}
$query = 'SELECT animal_type, animal_name
FROM animals';
$animal = $db->query($query);
$animal->execute();
$animals = $animal->fetchAll();
$animal->closeCursor();
echo "<br>";
?>
<table border="1">
<tr>
<th>Animal Type</th>
<th>Animal Name</th>
</tr>
<?php foreach ($animals as $animal) { ?>
<tr>
<td><?php echo $animal['animal_type']; ?></td>
<td><?php echo $animal['animal_name']; ?></td>
</tr>
<?php } ?>
</table>
/////////////////////////////////////////////////////////////////////////////////Example2/////////////////////////////////////////////////////////////////////////////////////////
<?php
$animal_type = "leopard";
$query = 'SELECT *
FROM animals
WHERE animal_type = :animal_type';
$animal = $db->prepare($query);
$animal->bindValue(':animal_type', $animal_type);
$animal->execute();
$animals = $animal->fetchAll();
$animal->closeCursor();
?>
<p>
<table border="1">
<tr>
<th>Animal Type</th>
<th>Animal Name</th>
</tr>
<?php foreach ($animals as $animal) { ?>
<tr>
<td><?php echo $animal['animal_type']; ?></td>
<td><?php echo $animal['animal_name']; ?></td>
</tr>
<?php }?>
</table>
</p>
/////////////////////////////////////////////////////////////////////////////////Example3/////////////////////////////////////////////////////////////////////////////////////////
<?php
$db = 'mysql:host=localhost;dbname=animals';
$username = 'jason';
$password = '';
$animal_type = $_POST['animal_type'];
$animal_name = $_POST['animal_name'];
$db = new PDO('mysql:host=localhost;dbname=animals', $username, $password);
$query = "INSERT INTO animals
SET animal_type = :animal_type,
animal_name = :animal_name";
$animal = $db->prepare($query);
$animal->bindParam(':animal_type', $animal_type, PDO::PARAM_STR);
$animal->bindParam(':animal_name', $animal_name, PDO::PARAM_STR);
$animal->execute();
?>
<form action="example3.php" method="post">
Animal Name: <input type="text" name="animal_name"><br>
Animal Type: <input type="text" name="animal_type"><br>
<input type="submit" />
</form>
</body>
</html>
To get value from super_globals like ($_POST,$_REQUEST,$_GET) you have to pass index as string
change
$animal_type = $_POST[animal_type];
$animal_name = $_POST[animal_name];
to
$animal_type = $_POST["animal_type"];
$animal_name = $_POST["animal_name"];
And remove un-necessary binding value
$animal->bindValue(':animal_id', $animal_id); //remove this
Also hope you have created database connection and store it in $db
Your insert query is also vulnerable to SQL Injections. Use bind param to insert value
$query = "INSERT INTO animals
(animal_type, animal_name)
VALUES
(:animal_type, :animal_name)";
$animal = $db->prepare($query);
$animal->bindParam(':animal_type', $animal_type);
$animal->bindParam(':animal_name', $animal_name);
$animal->execute();
<?php
$db = 'mysql:host=localhost;dbname=animals';
$username = 'root';
$password = '';
$animal_type = $_POST['animal_type'];
$animal_name = $_POST['animal_name'];
$db = new PDO('mysql:host=localhost;dbname=animals', $username, "");
$query = "INSERT INTO animals
SET animal_type = :animal_type,
animal_name = :animal_name";
$animal = $db->prepare($query);
$animal->bindParam(':animal_type', $animal_type, PDO::PARAM_STR);
$animal->bindParam(':animal_name', $animal_name, PDO::PARAM_STR);
$animal->execute();
?>
<form action="example3.php" method="post">
Animal Name: <input type="text" name="animal_name"><br>
Animal Type: <input type="text" name="animal_type"><br>
<input type="submit" />
</form>
where do you create the database? the only thing i see is a string named $db I think you forgot to create a PDO object like this
$db = new PDO('mysql:host=localhost;dbname=animals', $username, "");
otherwise ist try's to a prepare statement to a string
and array indexes must be a string like this $_POST["animal_type"]
<?php
if(isset($_POST['submit'])){ //check wheter form submit or not
$db = 'mysql:host=localhost;dbname=animals';
$username = 'root';
$password = '';
$animal_type = $_POST['animal_type'];
$animal_name = $_POST['animal_name'];
$stmt = $db->prepare("INSERT INTO animals
(animal_type, animal_name) VALUES (?, ?)");
$stmt->bind_param("ss", $animal_type, $animal_name);
$stmt->execute();
}
?>
<form method="post">
Animal Name: <input type="text" name="animal_name"><br>
Animal Type: <input type="text" name="animal_type"><br>
<input type="submit" name="submit"/> // change this markup input
</form>
Refer this link for more php and mysql tutoral https://www.w3schools.com/PhP/php_mysql_prepared_statements.asp

Update mysql record and pass id

My form is:
<form class="form-horizontal" action="update.php?id=<?php echo $id ?>" method="post">
$sql = 'SELECT * FROM prekes WHERE pirkejo_id=' . $pirkejas . '';
$q = $pdo->prepare($sql);
$prekes = array();
foreach ($pdo->query($sql) as $row) {
if ($row['prek_pav'] != '') {
array_push($prekes, $row);
}
}?>
<input name="prekes[1][pavadinimas]" type="text" value="<?php echo $prekes[0]['prek_pav']?>">
<input name="prekes[1][kaina]" type="text" value="<?php echo $prekes[0]['prek_kaina'] ?>">
<input name="prekes[2][pavadinimas]" type="text"value="<?php echo $prekes[1]['prek_pav']?>">
<input name="prekes[2][kaina]" type="text" value="<?php echo $prekes[1]['prek_kaina'] ?>">
I dont know how to optimize it. I want to update my records in database and have no idea how to pass prekes_id value to UPDATE sql.
I found that My update updates all records with the last value from my form. all recors are same as last entered.
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE customers set name = ?, pavarde = ?, ak = ?, numeris = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name, $pavarde, $ak, $numeris, $id));
foreach ($prekes as $preke) {
$sql = "UPDATE prekes SET prek_pav= ?,prek_kaina=? WHERE prekes_id=".$preke['prekes_id'];
$q = $pdo->prepare($sql);
$q->execute(array($preke['pavadinimas'], $preke['kaina']));
}
Database::disconnect();
header("Location: default.php");
I use this code to solve this. Are there any better working solution to this problem?
My table prekes (prekes_id, pirkejo_id, prek_pav, prek_kaina). I take pirkejo_id from $_POST['id'].

editing and deleting records in a database using radio buttons

<?php
$user_name = "root";
$password = "";
$database = "my_db";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if(isset ($_POST['name']))
{
$name = $_POST['name'];
if(mysql_query("INSERT INTO persons VALUES(' ' , '$name') "))
echo "Successful Insertion!";
else
echo "Please try again!";
}
$result = mysql_query("SELECT * FROM persons");
?>
<html>
<head>
<style type = "text/css">
li { list-style-type: none; display: inline; padding: 10px; text-align: center;}
</style>
</head>
<body>
<form action = " . " method = "POST">
Name: <input type = "text" name = "name"><br>
<input type = "submit" value = "Enter">
</form>
<form name = "delete_form" method = "POST" action = "delete.php" >
<input type = "submit" name = "deleteRecord" value = "Delete Record" />
</form>
<h1>List of Names</h1>
<table border = "1" width = "100%" cellpadding = "5" cellspacing = "2">
<tr>
<td><strong></strong></td>
<td><strong>ID</strong></td>
<td><strong>Company</strong></td>
<td><strong>Edit</strong></td>
<td><strong>Delete</strong></td>
</tr>
<?php while ($row = mysql_fetch_array($result)) { ?>
<tr>
<td><input type="radio" Name="id" value="<?php echo $row['id']; ?>" ></td>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo "<a href = 'edit.php?id=$row[id]'>edit</a>" ?></td>
<td><?php echo "<a href = 'delete.php?id=$row[id]'>delete</a>" ?></td>
</tr>
<?php } ?>
<form name = "edit_form" method = "POST" action = " edit.php?edit= "<?php echo $row['id'] ?> >
<input type = "submit" name = "editRecord" value = "Edit Record" />
</form>
</table>
<?php
while($row = mysql_fetch_array($result))
echo "<li>$row[id]</li> . <li>$row[name]</li> <li> <a href = 'edit.php?edit=$row[id]'>edit</a> </li> <li> <a href = 'delete.php?del=$row[id]'>delete</a></li> <br>";
?>
</body>
</html>
edit.php
<?php
$user_name = "root";
$password = "";
$database = "my_db";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$row = " ";
if (isset($_POST['id']))
{
// if there is an id sent through POST and it isn't null/empty, use that
$id = $_POST['id'];
$SQL = "SELECT * FROM persons WHERE id = '$id' ";
$result = mysql_query($SQL);
$row = mysql_fetch_array($result);
}
else
{
// otherwise use id sent through GET links
$id = $_GET['id'];
$SQL = "SELECT * FROM persons WHERE id = '$id' ";
$result = mysql_query($SQL);
$row = mysql_fetch_array($result);
}
if(isset($_POST['newName']))
{
$id = $_POST['id'];
$newName = $_POST['newName'];
$SQL = "UPDATE persons SET name = '$newName' WHERE id = '$id' ";
$result = mysql_query($SQL) or die("Could not update database" . mysql_error());
echo "<meta http-equiv = 'refresh' content = '0 ; url = index.php'>";
}
?>
<form action = " edit.php" method = "POST">
ID: <input type = "text" name = "id" value = "<?php echo $row[0] ?>"<br><br>
Name: <input type = "text" name = "newName" value = "<?php echo $row[1] ?>"<br><br>
<input type = "submit" value = "Update">
</form>
Hello,
The code above shows how to edit and delete records in a database. Originally, the edit and delete options were in the form of links to a php script which performed the required action. The ID number of the selected row gets passed to the edit or delete php file which then does the action that the user selects (refer to the comments in the code above) I am now trying to modify this code so that I can use a radio button to select a record and then edit or delete the record using radio buttons. I know this sounds trivial but I am having some difficulty with it. Any assistance would be greatly appreciated. Thank you.
Hello Tom. I have made the changes that you suggested but I it still giving the same problem. I have included the edit.php file in case you want to have a look.
The value of your radio buttons needs to contain the ID of the record to be edited.
<td><INPUT TYPE="Radio" Name="radio" value="<?php echo $row['id']; ?>"></td>
Then when you submit the form, you will know the record you are editing has id of value $_POST['radio'].
Though you are already using GET method to pass IDs (through your edit and delete links). I would recommend having consistency, and passing all IDs with parameter id. So
Use this
<td><?php echo "<a href = 'edit.php?id=$row[id]'>edit</a>"; ?></td>
<td><?php echo "<a href = 'delete.php?id=$row[id]'>delete</a>"; ?></td>
And this
<td><input type="radio" name="id" value="<?php echo $row[id]; ?>"></td>
Then in edit.php and delete.php, check to see if an ID was passed through POST (if someone submitted the form) or through GET (they clicked a link), then use whichever has a value.
<?php
if (!empty($_POST['id']))
{
// if there is an id sent through POST and it isn't null/empty, use that
$id = $_POST['id'];
}
else
{
// otherwise use id sent through GET
$id = $_GET['id'];
}
I should also mention that mysql_fetch_array is deprecated and you should be using PDO or MySQLi. Read more here: http://www.php.net/mysql_fetch_array

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.

updating a record in database not working

again I'm trying to study php mysql and it seems that I tried everything thing to figure the problem out.. but it seems as a beginner codes in the internet are not helping.. I really can't update the records in the database.
<html>
<body>
<?php
$db = mysql_connect("localhost", "root");
mysql_select_db("dbtry",$db);
$id = isset($_GET['id']) ? $_GET['id'] : null;
$submit = isset($_POST['submit']);
if ($id) {
if ($submit) {
$result = mysql_query("select * from employees where id = " . mysql_real_escape_string($_GET['id']) );
$row = mysql_num_rows($result);
if ($myrow != 0) {
mysql_query ("UPDATE employees SET firstname='$first',lastname='$last',address='$address',position='$position' WHERE id = '$id'");
}
echo "Thank you! Information updated.\n";
} else {
// query the DB
$result = mysql_query("SELECT * FROM `employees` WHERE `id` = " . mysql_real_escape_string($_GET['id']), $db);
$myrow = mysql_fetch_array($result);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type=hidden name="id" value="<?php echo $myrow["id"] ?>">
First name:<input type="Text" name="first" value="<?php echo $myrow["firstname"] ?>"><br>
Last name:<input type="Text" name="last" value="<?php echo $myrow["lastname"] ?>"><br>
Address:<input type="Text" name="address" value="<?php echo $myrow["address"]
?>"><br>
Position:<input type="Text" name="position" value="<?php echo $myrow["position"]
?>"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?php
}
} else {
// display list of employees
$result = mysql_query("SELECT * FROM employees",$db);
while ($myrow = mysql_fetch_array($result)) {
printf("%s %s<br>\n", $_SERVER['PHP_SELF'], $myrow["id"],
$myrow["firstname"], $myrow["lastname"]);
}
}
?>
</body>
</html>
There are two things potentially causing you a problem: firstly, the values you are trying to set are variables which have not been defined. I'm assuming the begginers code you found assumed you had register globals enabled, you really don't want to do this!
The second problem, is that if you do have register globals enabled, the data isn't being sanitized, so a quotation mark could send the update awry.
Try this instead:
$first = mysql_real_escape_string( $_POST['first'] );
$last = mysql_real_escape_string( $_POST['last'] );
$address= mysql_real_escape_string( $_POST['address'] );
$position = mysql_real_escape_string( $_POST['position'] );
mysql_query ("UPDATE employees SET firstname='$first',lastname='$last',address='$address',position='$position' WHERE id = '$id'");
This should at least get you up and running. I'd strongly advise that you use either the MySQLi library, or PHP PDO, and think about using prepared statements for added security.
mysql_query("UPDATE `employees` SET `firstname`='".$first."', `lastname`='".$last."',
`address`='".$address."', `position`='".$position."' WHERE `id` = '".$id".' ; ", $db) or
die(mysql_error());
I think the problem may lie in your connection to the database. The third parameter of the mysql_connect function is a password. Therefore this:
$db = mysql_connect("localhost", "root");
should be:
$db = mysql_connect("localhost", "root", "yourPassword");
It would also help a lot if you posted what type of error you are getting.
You need to differentiate post and get. Follow the working example below. It will sort you out :D
<html>
<body>
<?php
$db = mysql_connect("localhost", "root","");
mysql_select_db("test",$db);
if($_SERVER['REQUEST_METHOD']=='POST')
{
//SUBMIT FORM
$id=isset($_POST['id'])?$_POST['id']:0;
if ($id) {
$result = mysql_query("select * from parameter where id = " . mysql_real_escape_string($id) );
$rows = mysql_num_rows($result);
if ($rows != 0) {
mysql_query ("UPDATE parameter SET name='".$_POST['name']."',value='".$_POST['value']."' WHERE id = '".$id."'");
echo "Thank you! Information updated.\n";
}
}
}
if($_SERVER['REQUEST_METHOD']=='GET')
{
//SELECT WHERE ID=GER VAR AND DISPLAY
$id = isset($_GET['id']) ? $_GET['id'] :0;//
if ($id) {
// query the DB
$result = mysql_query("SELECT * FROM parameter WHERE `id` = " . mysql_real_escape_string($_GET['id']), $db);
$myrow = mysql_fetch_array($result);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type=hidden name="id" value="<?php echo $myrow["id"] ?>">
First name:<input type="Text" name="name" value="<?php echo $myrow["name"] ?>"><br>
Last name:<input type="Text" name="value" value="<?php echo $myrow["value"] ?>"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?php
}
else {
// display list of employees
$result = mysql_query("SELECT * FROM parameter",$db);
while ($myrow = mysql_fetch_array($result)) {
echo "<a href='".$_SERVER['PHP_SELF']."?id=".$myrow['id']."'>".$myrow['name'].": ".$myrow['value']."</a><br>";
}
}
}
?>
</body>
</html>
Usually when I run into this problem, it's because auto commit is off and I forgot to tell the connection explicitly to commit.
EDIT: Have you tried this: How can I implement commit/rollback for MySQL in PHP?? Depending on your settings, InnoDB can be set to auto commit off, which means you need to tell MySQL explicitly to commit updates after your done.

Categories