I am working with three database tables.
users
class
user_class
I'm making a page so that student can be assigned to classes using a checkbox. How do I get it so that if the value of a student being in a class is currently in the database, the checkbox for that class will already have the student value checked.
<?php
$showAllStudents = "SELECT * FROM users";
mysqli_query($mysqli, $showAllStudents) or die ('Error finding Students');
$result = mysqli_query($mysqli, $showAllStudents);
echo"<table border='1' cellspacing='10' align='center'>";
echo "<tr><th></th><th>User ID</th><th>User Name</th><th>First Name</th>
<th>Second Name</th></tr>";
while ($row = $result->fetch_object()){
echo "<tr>";
echo "<td><input type='checkbox' id='" .$row->userID . "'
name='check_box[]' value='" .$row->userID . "' /></td>";
echo "<td>" .$row->userID . "</td>";
echo "<td>" .$row->username . "</td>";
echo "<td>" .$row->forename . "</td>";
echo "<td>" .$row->surname . "</td>";
echo "</tr>";
}
if (isset($_POST['submitClassStudent'])) {
//get ID from header
$classID = $_GET['id'];
//print_r ($_POST);
//for each ticked checkbox convert to a UserID variable
foreach ($_POST['check_box'] as $userID) {
$editClassStudentQuery = "INSERT INTO `user_class`(userID, classID)
VALUES('$userID', '$classID')";
$insert_row = $mysqli->query($editClassStudentQuery) or die($mysqli->error . __LINE__);
if ($insert_row) {
header('Location: classeditor.php');
} else {
echo "Error: " . $editClassStudentQuery . "<br>" . $mysqli->error;
}
}
}
?>
To mark a checkbox as already checked you just need to add checked as one of its attributes.
<input type="checkbox" id="already-checked" checked> Already checked
W3 Schools
if the user exists then echo 'checked' in tag
Example: echo "<input type ='checkbox'";if(YourConditionHere)echo "checked>";else echo ">";
Related
I'm trying to make a HTML table as a frontend to a mySQL database. The table displays fine and I can type in the edits I want to make to each row of the table but when I press the submit button the changes aren't actually made. Can anyone see where I'm going wrong?
<?php
include("db.php");
$sql = "SELECT * FROM `artist`";
$result = mysqli_query($conn, $sql);
if (isset($_POST['update'])){
$artID = $_POST['artID'];
$artName = $_POST['artName'];
$key = $_POST['hidden'];
$UpdateQuery = "UPDATE `artist` SET `artID` = '$artID', `artName` = '$artName' WHERE `artist`.`artID` = '$key'";
mysqli_query($conn,$UpdateQuery);
header("Location: {$_SERVER['HTTP_REFERER']}");
exit;
};
echo "<table border='1'>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Name</th>";
echo "</tr>";
if ($result->num_rows > 0) {
echo "<form id ='artisttable' action ='getartiststable.php' method ='post'>";
// output data of each row
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" ."<input type='text' name ='artID' value ='" . $row['artID'] . "' </td>";
echo "<td>" . "<input type='text' name ='artName' value ='" . $row["artName"] . "' </td>";
echo "<td>" . "<input type = 'hidden' name ='hidden' value='" . $row['artID'] . "' </td>";
echo "<td>" . "<input type='submit' name ='update'" . " </td>";
echo "</tr>";
}
echo "</form>";
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
The db.php file simply includes the connection info to the mySQL database and I'm 100% sure there's nothing wrong with it as it retrieves the table correctly it just doesn't update.
You are putting form tag inside tr which is not allowed td are only allowed
so you have to remove that tr from there.
You have to use jquery or you can replace the table with some other grid structure so that it can look the same and the form can be placed there as well
One more suggestion Don't mix the php and html together separate them for the clean code
If you do all these you code will be like this
Your form is being constructed with multiple elements with the same name. When you submit the form it is using the last elements as the values so regardless of the record you want updated the last record is being updated (or throwing an error because of string encapsulation). You should use parameterized queries as well.
So instead of:
if ($result->num_rows > 0) {
echo "<form id ='artisttable' action ='getartiststable.php' method ='post'>";
// output data of each row
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" ."<input type='text' name ='artID' value ='" . $row['artID'] . "' </td>";
echo "<td>" . "<input type='text' name ='artName' value ='" . $row["artName"] . "' </td>";
echo "<td>" . "<input type = 'hidden' name ='hidden' value='" . $row['artID'] . "' </td>";
echo "<td>" . "<input type='submit' name ='update'" . " </td>";
echo "</tr>";
}
echo "</form>";
echo "</table>";
Use:
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_array($result)) {?>
<form class='artisttable' action ='getartiststable.php' method ='post'>
<tr>
<td><input type='text' name ='artID' value ='<?php echo $row['artID'];?>' /></td>
<td><input type='text' name ='artName' value ='<?php echo $row["artName"];?>' /></td>
<td><input type = 'hidden' name ='hidden' value='<?php echo $row['artID'];?>' /></td>
<td><input type='submit' name ='update'" . " </td>
</tr>
</form>
<?php } ?>
</table>
So you get a form for each data set. Here's a link on prepared statements with mysqli: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php. You also should update your mark up. Tables for formatting aren't the best approach. Your inputs also weren't closed missing >.
Also this changed artisttable from an id to class because there will be multiples. Update CSS/JS accordingly.
if (isset($_POST['update'])){
$UpdateQuery = "UPDATE eventcalendar SET Title='$_POST[title]', Detail='$_POST[detail]' WHERE ID='$_GET[ID]'";
mysql_query($UpdateQuery, $con);
}
$sql = "SELECT * FROM eventcalendar";
$myData = mysql_query($sql,$con);
echo "<table border=1'>
<tr>
<th>Id</th>
<th>Title</th>
<th>Detail</th>
<th>Event Date</th>
<th>Date Added</th>
</tr>";
while($row = mysql_fetch_array($myData)){
echo "<form action=details.php method=post>";
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . "<input type=text name=title value=" . $row['Title'] . " </td>";
echo "<td>" . "<input type=text name=detail value=" . $row['Detail'] . " </td>";
echo "<td>" . $row['eventDate'] . "</td>";
echo "<td>" . $row['dateAdded'] . "</td>";
echo "<td>" . "<input type=submit name=update value=update" . " </td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysql_close($con);
This is my code, yet when i try to execute it, it execute all my rows in my table instead of the only 1 I edited. I've searched for like 2 hours but still can't find it. Does any of you know maybe how I can fix this?
Looks like you need to include the ID in the form action.
echo '<form action="details.php?ID='.$row['ID'].'" method="post">';
This will allow the use of the $_GET['ID'] value in your update query.
Alternatively, add the ID as a hidden field in your form like
echo '<input type="hidden" name="ID" value="'.$row['ID'].'">';
And change the SQL query to use $_POST['ID'] instead of $_GET['ID'].
$UpdateQuery = "UPDATE eventcalendar SET Title='$_POST[title]', Detail='$_POST[detail]' WHERE ID='$_POST[ID]'";
Something you also need to look into is escaping the input that you're using with your SQL statement.
Aside from the SQL Injection issues, your problem is that:
You're using $_GET[ID] in your query, instead of $_POST[ID]
You aren't posting the ID back to the form at all. Try adding this:
echo "<input type='hidden' name='ID' value='{$row[ID]}'>";
Your $_POST[title], $_POST[detail] and $_GET[ID]are interpreted as plain strings, not as the evaluated value, to get the evaluated value, you have to make use of concatenation.
Update this part :
if (isset($_POST['update'])){
$UpdateQuery = "UPDATE eventcalendar SET Title='$_POST[title]', Detail='$_POST[detail]' WHERE ID='$_GET[ID]'";
mysql_query($UpdateQuery, $con);
}
to this:
if (isset($_POST['update']))
{
$UpdateQuery = "UPDATE eventcalendar SET Title='". $_POST['title']. "', Detail='". $_POST['detail']. "' WHERE ID='". $_POST['ID']. "'";
mysql_query($UpdateQuery, $con);
}
I am trying to send the same email only to selected users. I am printing values from table and want to select specific users to send an email.
<form name="unos" action="mail-proizvodi.php" method="post">
<?
echo "<table border='5'>
<tr>
<th> </th>
<th>ID</th>
<th>NAZIV</th>
<th>ADRESA</th>
<th>DRZAVA</th>
<th>GRAD</th>
<th>EMAIL</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo '<td><input type="checkbox" name="email[]" value="' . $row['ID'] . '"></td>';
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['NAZIV'] . "</td>";
echo "<td>" . $row['ADRESA'] . "</td>";
echo "<td>" . $row['DRZAVA'] . "</td>";
echo "<td>" . $row['GRAD'] . "</td>";
echo "<td>" . $row['EMAIL'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
<input type="submit" name="submit" value="submit">
</form>
my mail-proizvodi.php code
$mail=$_POST['email'];
echo "Dzenad catic";
$query= "SELECT `EMAIL` FROM `clanovi` WHERE ID='$mail[0]'";
if(sizeof($mail)>1)
{
for($i=1; $i<sizeof($mail); $i++)
{
$query.=" OR ID = '$mail[$i]' ";
}
}
$result=mysqli_query($con,$query);
while(FALSE!==($row=mysqli_fetch_row($result))) {
$bccfields[] = $row['EMAIL'];
}
echo sprintf("<a href=mailto:test#test.ba?bcc=%s />\n",
urlencode(implode(',',$bccfields)));
echo "Send" ;
Post I am receiving is an array. And when I do var_dump($mail) I get
array
0 => string '20' (length=2)
1 => string '30' (length=2)
Any help or advice is appreciated. Thanks in advance.
I am posting solution for the problem I had in case someone else face similar mistake.
$mail=$_POST['email'];
$query= "SELECT `EMAIL` FROM `clanovi` WHERE ID ='$mail[0]'";
if(sizeof($mail)>1)
{
for($i=1; $i<sizeof($mail); $i++)
{
$query.=" OR ID = '$mail[$i]' ";
}
}
$result=mysql_query($query);
if (!$result) {
echo "Could not successfully run query ($query) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while(FALSE!==($row=mysql_fetch_assoc($result))) {
$bccfields[] = $row['EMAIL'];
}
echo sprintf("<a href=mailto:prodaja#alternativa.ba?bcc=%s />\n",
urlencode(implode(',',$bccfields)));
echo "Send" ;
mysql_free_result($result);
My Code so far. The data gets pulled correctly
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Request");
echo "<table border='1'>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Prayer Request</th>
<th>Deactivate Request</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Reg_F_Name'] . "</td>";
echo "<td>" . $row['Reg_L_Name'] . "</td>";
echo "<td>" . $row['Reg_Request'] . "</td>";
echo "<td><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=\"".$rows['Reg_ID']. "\" /></td>";
echo "</tr>";
}
echo "</table>";
echo
"<form action='' method='post'>
<input type='submit' name='use_button' value='Update' />
</form>";
if(isset($_POST['use_button']))
{
echo "hey";
$del_id = $_POST['checkbox'];
$detectinglocations = 'your database table name';
foreach($del_id as $value){
$sql = "Update Request set Reg_Status=0 WHERE Reg_ID='".$value."'";
$result = mysql_query($sql);
}
}
mysqli_close($con);
?>
Nothing Happens when I Click Submit. I am wanting it to Update the reg_Status to 0 for every check box that is click. So whats my problem. Thank you in advance for helping!
try adding an input hidden field with same name as the checkbox name before each checkbox and with value 0 .
The checkbox doesnt get posted when not checked.
Guys I cant see why it is that my code will only Update the last row on the table. It will populate the entire HTML page with a table with the info from phpAdmin. I can then change this info, on the html page. It all works fine if there is only one record, anymore than one and it only takes effect on the last row. I am new to all this, so excuse the code, here it is......
<html>
<?php
$con = mysql_connect("localhost","root");
if(!$con){
die("Cant get there Bren: " . mysql_error());
}
mysql_select_db("Web_Data",$con);
if (isset($_POST['update'])){
$UpdateQuery = "UPDATE Vehicles SET Vehicle_Id='$_POST[Vehicle_Id]',
Registration='$_POST[Registration]',Make='$_POST[Make]',Model='$_POST[Model]',
Classification='$_POST[Classification]',Rental_Price='$_POST[Rental_Price]',
Current_Status='$_POST[Current_Status]',Mileage='$_POST[Mileage]'
WHERE Vehicle_Id='$_POST[hidden]'";
echo "<center> Vechicle Id '$_POST[hidden]' succesfully VEHICLE UPDATED </center>";
mysql_query($UpdateQuery, $con);
};
$sql = "Select * From Vehicles";
$myData = mysql_query($sql,$con);
echo" <center> <table border = 3>
<tr>
<th>Vehicle_Id</th>
<th>Registration</th>
<th>Make</th>
<th>Model</th>
<th>Classification</th>
<th>Rental_Price</th>
<th>Current_Status</th>
<th>Mileage</th>
</tr></center>";
while($record = mysql_fetch_array($myData)){
echo "<form action = UpdateWD.php method=post>";
echo "<tr>";
echo "<td>" . "<input type = text name = Vehicle_Id value=" . $record['Vehicle_Id'] . " </td>";
echo "<td>" . "<input type = text name = Registration value=" . $record['Registration'] . " </td>";
echo "<td>" . "<input type = text name = Make value=" . $record['Make'] . " </td>";
echo "<td>" . "<input type = text name = Model value=" . $record['Model'] . " </td>";
echo "<td>" . "<input type = text name = Classification value=" . $record['Classification'] . " </td>";
echo "<td>" . "<input type = text name = Rental_Price value=". $record['Rental_Price'] . " </td>";
echo "<td>" . "<input type = text name = Current_Status value=" . $record['Current_Status'] . " </td>";
echo "<td>" . "<input type = text name = Mileage value=" . $record['Mileage'] . " </td>";
echo "<td>" . "<input type = hidden name = hidden value=" . $record['Vehicle_Id'] . " </td>";
echo "<td>" . "<input type = submit name = update value= update" . " </td>";
echo "</from>";
}
echo"</table>";
mysql_close($con);
?>
<br><br><br>
<footer>
Copyright © 2013 ABU LTD
About -
Privacy Policy -
Contact Us
Logout
</footer> <!--footer-->
</html>
See here:
Use while loop to display all fetched records.
<?php
// Make a MySQL Connection
$sql = "Select * From Vehicles";
$myData = mysql_query($sql,$con) or die(mysql_error());
while($row = mysql_fetch_array($myData)){
echo $row['Vehicle_Id'];
}
?>
And mysql_query can't use multiple queries.
The easiest thing is to just run them separately. I believe you can do multi query but I haven't tried it.
Just get the idea how you can run multiple queries using foreach loop.
$updateArray = array(21=>300,23=>200,24=>100);
foreach($updateArray as $id=>$value)
{
$query = "UPDATE cart SET cart_qty='$value' WHERE cart_id = '$id'";
mysql_query($query,$link);// $link is specified above
}
here is my mistake
hours and hours and all it was
echo "<td>" . "<input type = 'submit' name = 'update' value= 'update'" . " />";
echo "</td>";
echo "</tr>";
echo "</form>";
had "form" spelt "from" & didnt close the </tr>