echo "<form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\">";
if ($isAdmin === '1'){
echo "<input id=\"checkbox\" name=\"checkbox\" type=\"checkbox\" checked=\"checked\" value=\"1\" />";
} else {
echo "<input id=\"checkbox\" name=\"checkbox\" type=\"checkbox\" value=\"0\" />";
}
echo "<input type=\"submit\" name=\"formSubmit\" value=\"X\" />";
echo "</form>";
The above code is inside a while loop so it makes a form for each user. My php code looks like this:
$status = '0';
if (isset($_POST['checkbox']) && $_POST['checkbox'] == '1') {
$status = $_POST['checkbox'];
}
$stmt = $mysqli->prepare("UPDATE members SET isAdmin = ? WHERE id = \"$id\"");
$stmt->bind_param('s', $status);
$stmt->execute();
$stmt->close();
$mysqli->close();
Without actually submitting the form to the server, why does the admin user become a non-admin user just by refreshing the page?
UPDATED CODE:
?>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<input type="checkbox" id="checkbox" name="checkbox" value="<?php echo ($checked)? '1' : '0'; ?>"<?php if($checked) echo ' checked="checked"'; ?> />
<input type="hidden" id="userid" name="userid" value="<? echo $members_row['id']; ?>" />
<input type="submit" id="submit" name="submit" value=">>" />
</form>
<?
$status = '0';
if (isset($_POST['checkbox']) && $_POST['checkbox'] == '1') {
$status = $_POST['checkbox'];
$id = $_POST['id'];
$stmt = $mysqli->prepare("UPDATE members SET isAdmin = ? WHERE id = \"$id\"");
$stmt->bind_param('s', $status);
$stmt->execute();
$stmt->close();
$mysqli->close();
}
Couple things, move your bracket to the end of the php snippet, and just check that the post is set but not that it equals anything. $status will be used to update it at the time of post. Side note, since the form is in a loop, id="checkbox" is going to be a problem when/if you use javascript. id="*" should to be unique in order to provide value. Finally, the origin of $id is unknown from the script provided, you will want to make sure you bind_param on that value as well (perhaps it should be provided by the post?). Not sure on the origin of that variable so hard to comment on that.
$checked = ($isAdmin == '1');
?>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<input id="checkbox" name="checkbox" type="checkbox" value="<?php echo ($checked)? '1' : '0'; ?>"<?php if($checked) echo ' checked="checked"'; ?> />
<input type="submit" name="formSubmit" value="X" />
</form>
<?php //continue with loop
Presumably this is at the top since your forms reference PHP_SELF:
<?php
if (isset($_POST['checkbox'])) {
$status = $_POST['checkbox'];
// The $id variable is suspect here. Probably should be provided by the post?
$stmt = $mysqli->prepare("UPDATE members SET isAdmin = ? WHERE id = '$id'");
$stmt->bind_param('s', $status);
$stmt->execute();
$stmt->close();
$mysqli->close();
}
If I were doing this, I would either use a function or a class/method to make it more human-readable and reusable:
function updateUserRole($id,$status,$mysqli)
{
$stmt = $mysqli->prepare("UPDATE members SET isAdmin = ? WHERE id = ?");
$stmt->bind_param('si', $status,$id);
$stmt->execute();
$stmt->close();
}
// To execute, include the function
// then run the "if" condition
if (isset($_POST['checkbox']))
updateUserRole($_POST['id'],$_POST['checkbox'],$mysqli);
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!";
}
}
Trying to make a CRUD, everything works except my Update function. I feel like the problem is in the second sql query. When I click on submit it just refreshes and the change is gone. Can anyone show me how to find what I need to change/show me what to change?
<head>
<title>Update</title>
</head>
<body>
</form>
<?php
require_once('dbconnect.php');
$id = $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<form action="" method="post">';
echo "Company: <input type=\"text\" name=\"CName\" value=\"".$row['CName']."\"></input>";
echo "<br>";
echo "Contact: <input type=\"text\" name=\"Contact\" value=\"".$row['Contact']."\"></input>";
echo "<br>";
echo "City: <input type=\"text\" name=\"City\" value=\"".$row['City']."\"></input>";
echo "<br>";
echo "<input type=\"Submit\" = \"Submit\" type = \"Submit\" id = \"Submit\" value = \"Submit\">";
echo "</form>";
}
echo "</table>";
} else {
echo "0 results";
}
if(isset($_POST['Submit'])){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();
?>
Instead of building a form inside PHP, just break with ending PHP tag inside your while loop and write your HTML in a clean way then start PHP again. So you don't make any mistake.
Also you've to submit your $id from your form too.
Try this
<?php
require_once('dbconnect.php');
$id = $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?= $id ?>" />
Company: <input type="text" name="CName" value="<?= $row['CName'] ?>" />
<br>
Contact: <input type="text" name="Contact" value="<?= $row['Contact'] ?>" />
<br>
City: <input type="text" name="City" value="<?= $row['City'] ?>" />
<br>
<input type="Submit" name="Submit" id="Submit" value="Submit" />
</form>
<?php
} // end while loop
echo "</table>";
}
else {
echo "0 results";
}
Note: You are passing undefined variables into your update query. As you are submitting your form you must have to define those variables before you use them.
if (isset($_POST['Submit'])) {
$CName = $_POST['CName'];
$Contact = $_POST['Contact'];
$City = $_POST['City'];
$id = $_POST['id'];
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();
that loop? ID primary key or not?
maybe u need create more key in table dealer like as_id
<input type="hidden" name="idform" value="$as_id">
in statment
if($_POST){
$idf = $_POST['idform'];
if(!empty($idf)){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where as_id=$idf";
$result = $conn->query($sql);
}
$conn->close();
}
I've got a page with checkboxes generated with the database. When we press the checkbox and submit it, it is working fine and it is updating in the database. But when I try to uncheck "1" checkbox it is checking out all checkboxes which are selected.
Query:
if(isset($_POST['submit'])){
foreach ($_POST['untrain'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainQuery = "UPDATE room_users SET trained = '1' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainQuery);
}
}
if(isset($_POST['submit'])){
foreach ($_POST['amk'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainedQuery = "UPDATE room_users SET trained = '0' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainedQuery);
}
}
Checkboxes:
<?php
if($room->trained == 1)
{ ?>
<input type='hidden' value="<?php echo $room->user_id; ?>" name="amk[<?php echo $room->room_id; ?>]">
<input type='checkbox' value="<?php echo $room->user_id; ?>" name="trained[<?php echo $room->room_id; ?>]" checked>
<?php echo "Y"; }
else{ ?>
<input type='checkbox' value="<?php echo $room->user_id; ?>" name="untrain[<?php echo $room->room_id; ?>]">
<?php echo "N";
}?>
</td>
<Td><?php
if($room->active == 1) {
?> <input type='checkbox' name="<?php echo $room->room_id; ?>" checked>
<?php echo "Active"; }
else { ?>
<input type='checkbox' name="<?php echo $room->room_id; ?>"
<?php echo "Inactive"; } ?>
I used the trick with the "hidden" input before the checkbox, but the only problem is that it is not working. When I click on it, it resets all checkboxes to 0.
I think you are missing how the combo checkbox + hidden input does work.
So here you go freely inspired by this answer:
<input id="foo" name="foo" type="checkbox" value="1" />
<input name="foo" type="hidden" value="0" />
Looks like you do know, if you use the trick, that, if the checkbox is unchecked, it will not be present in the post. So to trick the form, we will always add an hidden field. And if the checkbox is checked, then the fact that it will be included in the post is going to override the value of the hidden input.
So for your specific problem :
<td>
<input type="checkbox" value="1" name="trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>]" <?php echo ($room->trained == 1) ? ' checked' : '' ?> /> Trained
<input type="hidden" value="0" name="trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>]"/>
</td>
Please note the use of the ternary operator on this part of the code <?php echo ($room->trained == 1) ? ' checked' : '' ?> which I may use a lot when writing html template.
Please also note the trick on the name trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>] which is needed because we cannot set the user_id as value of the input.
Then for the processing part :
if ( isset ( $_POST['submit'] ) ) {
foreach ( $_POST['trained'] as $ids => $value ) {
// This query needs protection from SQL Injection!
// ^ good point, on which I would suggest you using PDO and prepared statement :)
list($room_id,$user_id) = explode('_',$ids);
// ^ now need to explode the name on the underscore to get both user_id and room_id cf the trick above
$untrainQuery = "UPDATE room_users SET trained = '$value' WHERE user_id = $user_id AND room_id = $room_id";
$db->update ( $untrainQuery );
}
}
Wash, rinse, repeat for every checkbox you need and you should be good to go.
echo "<form name='input' action='admin_selecteren_voor_verwijderen.php' method='post'>";
$sql_bestelling= "SELECT * FROM producten";
foreach($dbh->query($sql_bestelling) as $row)
{
$product_id=$row['product_id'];
$product_naam=$row['product_naam'];
$prijs=$row['prijs'];
$foto=$row['foto'];
echo "
<br>
<img src='$foto' height='70' width='50' border='0'>
<b>$product_naam</b> <input type='checkbox' name='$product_naam' value='$product_naam'></br>
</br></br></br>";
//if (isset($_POST['submit'])){
// $sql = "DELETE FROM `producten` WHERE product_naam='$product_naam'";
// $query = $dbh->prepare( $sql );
// $result = $query->execute();
//}
}
if(!empty($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $check) {
echo "check: ", $check;
}
}
echo "
<input type='submit' value='Delete'>
</form>";
?>
I want to have a list of product in my webshop administrator page. Every product has a checkbox. I want to be able to delete all of the product of the checkboxes are checked. But I don't know how.. The above is what I have so far. The added picture is how it looks on the page. But the page is a list of product selected from the database with a foreach loop as can be seen in the code. The checkbox also is in the loop. I don't know how to assign every product which is check to a variable and then delete them from the database. Can anyone help me?
Name all the checkboxes a same, like delete[] , and and put the name of product in the value of each checkbox.
Example :
<form action="..." method='post' >
user1<input type="checkbox" name="delete[]"
value="<?php echo $product_naam ?>" /><br />
user2<input type="checkbox" name="delete[]"
value="<?php echo $product_naam ?>" /><br />
user3<input type="checkbox" name="delete[]"
value="<?php echo $product_naam ?>" /><br />
user4<input type="checkbox" name="delete[]"
value="<?php echo $product_naam ?>" /><br />
<input type='submit' value='delete' />
</form>
Delete query :
<?php
if(isset($_POST['delete'])){
$ids = $_POST['delete'];
$sql = "DELETE FROM `producten` WHERE product_naam
IN('".implode("','", $ids)."')";
//execute query
}
?>
You're looking for $_POST['checkbox'] but that's not what you have in your form. Name the checkboxes all checkbox[] and use $product_naam as the value.
<input type='checkbox' name='checkbox[]' value='$product_naam'>
Now you can loop over it and delete with your foreach loop.
you should not name the checkbox to the product name, just call it delete or something. Then you can use the foreach method to delete them from the database, like this:
<?php
echo "<form name='input' action='admin_selecteren_voor_verwijderen.php' method='post'>";
$sql_bestelling= "SELECT * FROM producten";
foreach($dbh->query($sql_bestelling) as $row)
{
$product_id=$row['product_id'];
$product_naam=$row['product_naam'];
$prijs=$row['prijs'];
$foto=$row['foto'];
echo "
<br>
<img src='$foto' height='70' width='50' border='0'>
<b>$product_naam</b> <input type='checkbox' name=delete' value='$product_naam'></br>
</br></br></br>";
//if (isset($_POST['submit'])){
// $sql = "DELETE FROM `producten` WHERE product_naam='$product_naam'";
// $query = $dbh->prepare( $sql );
// $result = $query->execute();
//}
}
if(isset($_POST['delete'])) {
foreach($_POST['delete'] as $delete){ {
$sql = "DELETE FROM producten WHERE product_naam= $delete";
$query = $dbh->prepare( $sql );
$result = $query->execute();
}
}
echo "
<input type='submit' value='Delete'>
</form>";
?>
Also, it seems to me you're mistaking "value" with "name", read up on it. And it would be good to read something about PDO, mysql isn't safe. http://www.php.net/manual/en/book.pdo.php
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.