I want to add loop to my sql query so that all the data from the table gets updated at one click. Right now only the last row is getting updated.
<?php
include_once 'db_connect.php';
if(isset($_POST['btn-signup']))
{
$PersonID = mysql_real_escape_string($_POST['PersonID']);
$FirstName = mysql_real_escape_string($_POST['FirstName']);
$Status = mysql_real_escape_string($_POST['Status']);
$Date = mysql_real_escape_string($_POST['Date']);
$uname = trim($uname);
$email = trim($email);
$upass = trim($upass);
// email exist or not
$query = "SELECT Date FROM status WHERE Date='$Date'";
$result = mysql_query($query);
$count = mysql_num_rows($result); // if email not found then register
if($count == 0){
if(mysql_query("INSERT INTO status(PersonID,FirstName,Status, Date) VALUES('$PersonID','$FirstName','$Status','$Date')"))
{
?>
<script>alert('successfully Added ');</script>
<?php
}
else
{
?>
<script>alert('error while registering you...');</script>
<?php
}
}
else{
?>
<script>alert('Sorry Attendence already taken ...');</script>
<?php
}
}
echo "<!DOCTYPE html>\n";
echo "<html>\n";
echo "<head>\n";
echo " <meta charset=\"utf-8\">\n";
echo " <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n";
echo " <title>Attendance</title>\n";
echo "</head>\n";
echo "<body>\n";
echo " \n";
echo "\n";
echo "\n";
include_once 'dbconnect.php';
$query = "SELECT * FROM attandance ";
$result = mysql_query($query);
echo "<h2>Mark Attendance</h2>\n";
echo "<form method=\"POST\" action=\"\">\n";
echo "<table border=\"2\">\n";
echo " <tr>\n";
echo " <th>PersonId</th>\n";
echo " <th>First Name</th>\n";
echo " <th>Status</th>\n";
echo " <th>Date</th>\n";
echo " </tr>\n";
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$PersonID=$row['PersonID'];
$FirstName=$row['FirstName'];
echo "<td> <input type=\"text\" name=\"PersonID\" value=\" $PersonID\"></td>\n";
echo "<td> <input type=\"text\" name=\"FirstName\" value=\" $FirstName\"></td>\n";
echo "<td><select name=\"Status\">\n";
echo " <option value=\"Present\">Present</option>\n";
echo " <option value=\"Absent\">Absent</option>\n";
echo " </select></td>\n";
echo "<td> <input type=\"date\" name=\"Date\" value=\" $Date\"></td>\n";
echo "</tr>\n";
}
echo " </table>\n";
echo "<input id=\"button\" type=\"submit\" name=\"btn-signup\" value=\"Mark\">\n";
echo "</form>\n";
echo "\n";
echo "\n";
echo "<a href='sheet.php'>Attendence Sheet</a>\n";
echo "</body>\n";
echo "</html>\n";
echo "\n";
?>
I am confused as i have used loop in the 2nd part to get value from the database and now i want to use loop to add those value in the database table. How can i add the code to the Insert SQL query in the first part of my code.
Related
I'm trying to create a user record to input into a phpmyadmin database.
createUserRecord($usersTable, [$r2,"'".$_POST["firstName"]."'","'".$_POST["lastName"]."'","'".$_POST["username"]."'","'".$_POST["password"]."'","'".$_POST["admin"]."'","'".$_POST["email"]."'"]);
I think there is an issue with the quotation marks or concatenation of the $_POST variables.
There is a record created in the phpmyadmin database, but the values are either not there for the text data types or the two integer value are showing up as 0. When I use print_r to print the values of this createUserRecord, it only prints '1'.
This is the code for the signup page that creates user records:
<html>
<body>
<p><h2><strong>Welcome to the Marist Room Reservation Recommender!</strong></h2></p>
<p><h3><strong>Reserve a room below!</strong></h3></p>
<?php
require 'sql_helper3.php';
if ($_POST[submitted] == "submitted") {
$r2 = (rand(11111,99999));
createUserRecord($usersTable, [$r2,"'".$_POST["firstName"]."'","'".$_POST["lastName"]."'","'".$_POST["username"]."'","'".$_POST["password"]."'","'".$_POST["admin"]."'","'".$_POST["email"]."'"]);
header('location:verify3.php');
} else {
echo "<h1>Please enter your details:</h1>";
echo "<form action=verify3.php method=post>\n";
echo "First Name: <input type=text name=firstName placeholder=\"Enter First Name\" required=required>\n<br>";
echo "Last Name: <input type=text name=lastName placeholder=\"Enter Last Name\" required=required>\n<br>";
echo "CWID: <input type=\"text\" name=\"CWID\" placeholder=\"Enter CWID\" required=required>\n<br>";
echo "Class: <select name=\"class\">\n";
echo "<option value=\"1\">Freshman</option>\n";
echo "<option value=\"2\">Sophomore</option>\n";
echo "<option value=\"3\">Junior</option>\n";
echo "<option value=\"3\">Senior</option>\n";
echo "</select>\n<br>";
echo " Gender:\n";
echo " <select option name = \"Gender\">\n<br> ";
echo " <option value = \"None\">Select One...</option>\n<br> ";
echo " <option value = \"Male\">Male</option>\n<br> ";
echo " <option value = \"Female\">Female</option>\n<br> ";
echo " </select>\n<br> ";
$sql = "SELECT name, roomsAvailable FROM $dormTable";
if($result = mysqli_query($conn, $sql)) {
$numRows = mysqli_num_rows($result);
echo " <strong>Residence Areas</strong>\n ";
echo " <select name = dorm> \n";
for ($i = 0; $i < $numRows; $i++){
$aDorm = mysqli_fetch_assoc($result);
$dormName = $aDorm['name'];
$dormAvailable = $aDorm['roomsAvailable'];
if($dormName != 'Select One...' && $dormAvailable != 0){
echo "<option value = \"$dormName\" > $dormName ($dormAvailable)</option>\n";
}
elseif ($dormAvailable == 0 && $dormName != 'Select One...'){
echo "<option value = \"$dormName\" disabled=\"disabled\"> $dormName </option> \n";
}
elseif ($dormName == 'Select One...'){
echo "<option value = \"$dormName\"> $dormName </option> \n";
}
}
echo "</select>\n<br><br>";
}
else {
echo "something is wrong: " .mysqli_error($conn);
echo $result;
die;
}
echo "<input type=checkbox name=specialNeeds value=\"1\">Special Needs?\n<br>";
echo "<input type=checkbox name=laundry value=\"1\">Laundry?\n<br>";
echo "<input type=checkbox name=fullyEquippedKitchen value=\"1\">Kitchen?\n<br><br>";
echo "Username:<input type=text name=username placeholder=\"Enter Username\" required=required><br>\n";
echo "Password:<input type=password name=password placeholder=\"Enter Password\" required=required><br>\n";
echo "Email Address:<input type=email name=email placeholder=\"Enter Email\" required=required><br><br>\n";
echo "<input type=checkbox name=admin value=\"1\">Administrator?\n<br>";
echo "<input type=hidden name=submitted value=submitted>\n<br>";
echo "<input type=\"submit\" value=\"Signup\">\n<br>";
echo "</form>\n";
foreach ($_POST as $k => $v){
echo"<input type = hidden name = $k value = \"$v\"> <?php echo print_r($_POST) ?>";
}
}
?>
</body>
This is the function that is called from another php page:
$table = $usersTable;
function createUserRecord($table, $values) {
echo "<br> in createUserRecord(), table is \"$table\", values are ".print_r($values)."\n<br>";
return insertInto($table, ["id", "firstName", "lastName", "username", "password", "admin"], $values);
var_dump($values);
}
function insertInto($table, $columns, $values) {
$sql = "INSERT INTO $table (`" . implode("`, `", $columns) . "`) VALUES ('" . implode("', '", $values) . "')";
return query($sql);
}
This is the results page:
<?php
//Take user selection from verify
require 'sql_helper3.php';
date_default_timezone_set('America/New_York');
$date = date('m/d/Y h:i:s a', time());
$dorm = $_POST["dorm"];
$sql = "SELECT * FROM $dormTable WHERE name = '$dorm'";
if ($result = mysqli_query($conn, $sql)) {
$dormRecord = mysqli_fetch_assoc($result);
}
$reservationsTable = "Reservations";
$r1 = (rand(11111,99999));
// SQL query to fetch information of registered users and finds user match.
$username=$_POST['username'];
$password=$_POST['password'];
$sql = "SELECT * FROM $usersTable WHERE password = \"$password\" AND username = \"$username\"";
echo "Running SQL $sql\n<br>";
$result = mysqli_query($conn,$sql);
$_SESSION['login_user']=$username; // user is logged in now
// echo "Initializing session...";
$aUser = mysqli_fetch_assoc($result);
//print_r($aUser);die;
$_SESSION['user_firstname'] = $aUser['firstName'];
$_SESSION['user_lastname'] = $aUser['lastName'];
$_SESSION['user_email'] = $aUser['email'];
$_SESSION['user_class'] = $aUser['class'];
$_SESSION['user_gender'] = $aUser['Gender'];
$_SESSION['user_kitchen'] = $aUser['fullyEquippedKitchen'];
$_SESSION['user_laundry'] = $aUser['laundry'];
$_SESSION['user_specialneeds'] = $aUser['specialNeeds'];
$_SESSION['user_admin'] = $aUser['admin'];
$_SESSION['user_id'] = $aUser['id'];
createReservationRecord($reservationsTable, [$r1, $date, "'".$usersTable[id]."'", "'".$dormRecord[id]."'", "'".$_POST[CWID]."'", "'".$_POST[firstName]."'", "'".$_POST[lastName]."'", "'".$_POST['class']."'", "'".$_POST[gender]."'", "'".$_POST[fullyEquippedKitchen]."'", "'".$_POST[laundry]."'", "'".$_POST[specialNeeds]."'"]);
//Update the record where the dorm id is used and set the roomsAvailable to -1 for that dorm
$sql = "UPDATE $dormTable SET roomsAvailable = ".--$dormRecord[roomsAvailable] ." WHERE id = $dormRecord[id]";
query($sql);
//Update the record where the dorm id is used and set the roomsreserved to +1 for that dorm
$sql = "UPDATE $dormTable SET roomsReserved = ".++$dormRecord[roomsReserved] ." WHERE id = $dormRecord[id]";
query($sql);
echo"<br>This is the users table ".print_r($usersTable)."<br>";
?>
<html>
<body>
<h1>Reservation Confirmation </h1>
</table>
Confirmation Number: <?php echo "$r1"; ?> <br>
Date: <?php echo "$date";?><br>
First Name: <?php echo $_POST["firstName"];?><br>
Last Name: <?php echo $_POST["lastName"]; ?><br>
CWID: <?php echo $_POST["CWID"]; ?><br>
Gender: <?php echo $_POST["Gender"]; ?><br>
Class: <?php
if($_POST["class"] == 1){
echo "Freshman";
}
elseif($_POST["class"] == 2){
echo "Sophomore";
}
else{
echo "Junior/Senior";
//or we could do upperclassman
}
; ?><br>
Residence Area: <?php echo $_POST["dorm"]; ?><br>
Special Needs: <?php
if ($_POST["specialNeeds"]){
echo "Yes";
}
else{
echo "No";
} ?><br>
Laundry: <?php if (isset($_POST["laundry"])){
echo "Yes";
}
else{
echo "No";
}
?><br>
Fully Equipped Kitchen: <?php
if (isset($_POST["fullyEquippedKitchen"])){
echo "Yes";
}
else{
echo "No";
}
if ($aUser["admin"]) {
echo "<br><br><a href=admin_main.php>Click here</a> to go to the admin landing page.\n<br>";
//header("location: admin_main.php"); // redirecting to admin landing page
}
else {
echo "<br><br><a href=reservations.php>Click here</a> to go to the reservations page.\n<br>";
// header('Location: profile.php'); // Redirecting To Students Landing page
}
?>
<br>
</body>
The output for this results page is:
Running SQL SELECT * FROM Users WHERE password = "bbb" AND username = "kk"
Warning: Illegal string offset 'id' in /home/ubuntu/workspace/Project_Three/results3.php on line 42 Call Stack: 0.0003 241480 1. {main}() /home/ubuntu/workspace/Project_Three/results3.php:0 Users
This is the users table 1
Reservation Confirmation
Confirmation Number: 19843
Date: 11/29/2016 01:28:30 pm
First Name: k
Last Name: b
CWID: 18738783
Gender: Female
Class: Freshman
Residence Area: Leo Hall
Special Needs: No
Laundry: No
Fully Equipped Kitchen: No
Click here to go to the reservations page.
i would like to know how can i make a multiple search criteria with 2 or more textboxes and only one submit button.
my script is:
$sql = "select * from wp_studenti ";
if (isset($_POST['search'])) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .= " WHERE nume= '{$search_term}' ";
}
$query = mysql_query($sql) or die (mysql_error());
echo "<form name ='search_form' method='POST' action='search.php'>";
echo "<center><h3>Cauta:</h3> <input type='text' name='search_box' />";
echo "<input type='submit' name='search' value='Cauta' /></center>";
echo "</form>";
and my results page that shows after search page:
$sql = "select * from wp_studenti ";
if (isset($_POST['search'])) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .= "WHERE nume= '{$search_term}'";
}
echo "<center>\n";
echo "<table border='1'>";
echo "<thead>";
echo "<tr><th>Id</th>";
echo "<th>Nume</th>";
echo "<th>Localitate</th>";
echo "<th>Judet</th>";
echo "<th>Sector Financiar</th>";
echo "<th>Link</th></tr>";
echo "</thead>";
$rst = mysql_query($sql);
while($a_row = mysql_fetch_assoc($rst)) {
echo "<tr>";
echo "<td>"; echo $a_row['id']; echo "</td>";
echo "<td>"; echo $a_row['nume']; echo "</td>";
echo "<td>"; echo $a_row['localitate']; echo "</td>";
echo "<td>"; echo $a_row['judet']; echo "</td>";
echo "<td>"; echo $a_row['sector_financiar']; echo "</td>";
echo "<td>"; echo "<a href='results.php?id={$a_row['id']}'>{$a_row['link']}</a>" ; echo "</td>";echo "</tr>";
echo "</table>";
$sql = "select * from wp_studenti ";
if (isset($_POST['search'])) {
$search_term_by_Cauta = mysql_real_escape_string($_POST['search_box_1']);
$search_term_by_localitate = mysql_real_escape_string($_POST['search_box_2']);
//If you want both search mandatory, use "AND" Operator otherwise use "OR". If you want approximate search use "LIKE" Operator in bellow SQL
$sql .= " WHERE nume= '{$search_term_by_Cauta }' OR localitate = '{$search_term_by_localitate }' ";
}
$query = mysql_query($sql) or die (mysql_error());
echo "<form name ='search_form' method='POST' action='search.php'>";
echo "<center><h3>Cauta:</h3> <input type='text' name='search_box_1' />";
echo "<h3>localitate:</h3> <input type='text' name='search_box_2' />";
echo "<input type='submit' name='search' value='Cauta' /></center>";
echo "</form>";
Well you need another search box:
echo "<center><h3>Cauta:</h3> <input type='text' name='search_box1' /><input type='text' name='search_box2' />";
And you need to use that value in your SQL:
if (isset($_POST['search'])) {
$search_term1 = mysql_real_escape_string($_POST['search_box1']);
$search_term2 = mysql_real_escape_string($_POST['search_box2']);
$sql .= " WHERE nume= '{$search_term1}' OR nume= '{$search_term2}'";
}
But you will have to do some thinking about how the search should work, is it supposed to match exactly one OR the other? If you want the text to contain instead of exactly match, you can use the syntax nume LIKE '%searchword%'
Use mysqli instead of mysql, which is depreciated. By PHP, something like this;
<form method='post'>
<input type='hidden' name='srch' val='1'>
Search Type1: <input type='text' name='s1'>
<br>
Search Type2: <input type='text' name='s2'>
<button>Submit</button>
</form>
<?php
if(isset($_POST['srch']))
{
if(!empty($_POST['s1']))$search = $_POST['s1'];
else if(!empty($_POST['s2']))$search = $_POST['s2'];
else die ('No criteria entered');
rest of your code...
}
?>
Also see functions like mysqli_real_escape for security reasons.
<?php
$status=&$_POST['status'];
$from=&$_POST['date_from'];
$to=&$_POST['date_to'];
$conn=mysqli_connect('localhost','root','','punbus') or die("Database not connected".mysqli_error());
if(isset($_POST['sub'])){
$ins="insert into driver_status(driver_name,status,date_from,date_to)
select Driver_name,'$status','$from','$to' from driver_master";
if(mysqli_query($conn,$ins)){
echo "added";
}
else{
echo "NOT".mysqli_error($conn);
}
}
$sel='select Driver_name from driver_master';
$query=mysqli_query($conn,$sel);
echo "<form action='driver_status.php' method='post'>";
echo "<table cellpadding=5>";
echo "<tr>";
echo "<th>Driver Name</th>";
echo "<th>Status</th>";
echo "<th>From</th>";
echo "<th>To</th>";
echo "</tr>";
while($row=mysqli_fetch_assoc($query)){
echo "<tr>";
echo "<td>".$row['Driver_name']."</td>";
$sel1='select d_status from status';
$query1=mysqli_query($conn,$sel1);
?>
<td>
<select name="status">
<?php
while($row1=mysqli_fetch_assoc($query1)){
$st=$row1['d_status'];
echo "<option value='$st'>$st</option>";
}
?>
</select>
</td>
<?php
echo "</tr>";
}
echo "</table>";
echo '<input type="submit" name="sub" value="Update"/>';
echo "</form>";
?>
That is my code. I want to save option selected from 4 drop down list to mysql. When I submit the form, the value selected from last box are getting saved in all rows of mysql table. Now, please tell me what should I do?
I am getting drop down box values from database table properly so what is the problem?
this is your code.
<?php
$status = $_POST['status'];
$driver_name= $_POST['driver_name'];
$from = $_POST['date_from'];
$to = $_POST['date_to'];
$conn = mysqli_connect('localhost', 'root', '', 'punbus') or
die("Database not connected" . mysqli_error());
if(isset($_POST['sub'])) {
foreach($status as $k=>$s){
$ins = "insert into driver_status(driver_name,status,date_from,date_to) VALUES
('".$driver_name[$k]."','$s','$from','$to')";
if (mysqli_query($conn, $ins)) {
echo "added";
} else {
echo "NOT" . mysqli_error($conn);
}
}
}
$sel = 'select Driver_name from driver_master';
$query = mysqli_query($conn, $sel);
echo "<form action='driver_status.php' method='post'>";
echo "<table cellpadding=5>";
echo "<tr>";
echo "<th>Driver Name</th>";
echo "<th>Status</th>";
echo "<th>From</th>";
echo "<th>To</th>";
echo "</tr>";
while($row=mysqli_fetch_assoc($query)){
echo "<tr><td>".$row['Driver_name']
."<input type=\"hidden\" name=\"driver_name[]\" value=\"".$row['Driver_name']."\"/></td>";
$sel1='select d_status from status';
$query1=mysqli_query($conn,$sel1);
echo "<td><select name=\"status[]\">";
while($row1=mysqli_fetch_assoc($query1)){
echo "<option value=\"".$row1['d_status']."\">".$row1['d_status']."</option>";
}
echo "</select></td></tr>";
}
echo "</table>";
echo '<input type="submit" name="sub" value="Update"/>';
echo "</form>";
?>
this is similar to other textbox
$op="select * from client where active=0";
$op1=mysql_query($op);
echo '<select name="c" id="c" style="width:160px;" required>';
while ($row = mysql_fetch_array($op1))
{
echo $s=$row["c_name"];
if($company!=$s)
{
echo '<option value="'.$row["c_name"].'">'.$row["c_name"].'</option>';
}
}
$c=$_REQUEST['c'];
$sql="insert into project c_name) values('$c')";
$sql1=mysql_query($sql);
I currently have these PHP pages which lets me add a record to a database. (in this case its members) It works perfectly in the sense that I can ADD, DELETE and VIEW. But Im not sure how to get the edit(or UPDATE functionality working.
Here is my db connection Code:
<?php
// Server Info
$server = 'localhost';
$username = 'root';
$password = '';
$database = 'gamgam';
// Connect to database
$connection = new mysqli($server, $username, $password, $database);
?>
Here is my Add Code:
<!DOCTYPE html>
<html>
<head><title>Insert Users</title></head>
<body>
<h2>Insert User Confirmation</h2>
<form action="<?php $_SERVER['PHP_SELF']?>" method="post"/> <br>
<?php
require_once('connection.php');
echo "<label for='memberID' >Member ID:</label>";
echo "<input type='text' name='memberID' id='memberID' />";
echo "<br /><br />";
echo "<label for='username' >Username:</label>";
echo "<input type='text' name='username' id='username' />";
echo "<br /><br />";
echo "<label for='password' >Password:</label>";
echo "<input type='password' name='password' id='password' />";
echo "<br /><br />";
echo "<label for='fName' >Firstname:</label>";
echo "<input type='text' name='fName' id='fName' />";
echo "<br /><br />";
echo "<label for='lName' >Lastname:</label>";
echo "<input type='text' name='lName' id='lName' />";
echo "<br /><br />";
echo "<label for='address' >Address:</label>";
echo "<input type='text' name='address' id='address' />";
echo "<br /><br />";
echo "<label for='email' >Email:</label>";
echo "<input type='text' name='email' id='email' />";
echo "<br /><br />";
echo "<input type='submit' name='submit' value='Submit' />";
echo "<input type='reset' value='Clear' />";
echo "<br /><br />";
?>
</form>
</section>
<p><a href='login.php'>Login</a></p>
<?php
if(!isset($_POST['submit'])) {
echo 'Please Register';
} else {
$memberID = $_POST['memberID'];
$username = $_POST['username'];
$password = $_POST['password'];
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$address = $_POST['address'];
$email = $_POST['email'];
$query = "INSERT INTO `members`
(MemberID, Username, Password, FirstName, LastName,
StreetAddress, Email)
VALUES ('$memberID', '$username', '$password', '$fName',
'$lName', '$address', '$email')";
mysqli_query($connection, $query)
or die(mysqli_error($connection));
$rc = mysqli_affected_rows($connection);
if ($rc==1)
{
echo '<h4>The database has been updated with the following details: </h4> ';
echo 'MemberID: '.$memberID.'<br />';
echo 'Username: '.$username.'<br />';
echo 'Password: '.$password.'<br />';
echo 'First Name: '.$fName.'<br />';
echo 'Last Name: '.$lName.'<br />';
echo 'Address: '.$address.'<br />';
echo 'Email: '.$email.'<br />';
} else {
echo '<p>The data was not entered into the database this time.</p>';
}
}
?>
</body>
</html>
Here is my View Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>
<table border="1" style="width:100%" >
<?php
/*
VIEW.PHP
Displays all data from 'players' table
*/
// connect to the database
include('connection.php');
// get results from database
$result = mysqli_query($connection, "SELECT * FROM members")
or die(mysqli_error());
// loop through results of database query, displaying them in the table
while($row = mysqli_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['MemberID'] . '</td>';
echo '<td>' . $row['Username'] . '</td>';
echo '<td>' . $row['Password'] . '</td>';
echo '<td>' . $row['FirstName'] . '</td>';
echo '<td>' . $row['StreetAddress'] . '</td>';
echo '<td>' . $row['Email'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
And here is the Delete Code:
<?php
// Connect to the database
include('connection.php');
// Confirm that the 'code' variable has been set
if (isset($_GET['MemberID']))
{
// Get the 'MemberID' variable from the URL
$MemberID = $_GET['MemberID'];
// Delete record from database
if ($stmt = $connection->prepare("DELETE FROM members WHERE MemberID = ? LIMIT 1")) {
$stmt->bind_param("i",$MemberID);
$stmt->execute();
$stmt->close();
} else {
echo "ERROR: could not prepare SQL statement.";
}
$connection->close();
// Redirect user after delete is successful
header("Location: view.php");
} else {
// If the 'code' variable isn't set, redirect the user
header("Location: view.php");
}
?>
I have gone through many basic php form templates online trying to incorporate what they have done to achieve results but have not had any success. What code needs to be written for my website to have the functionality to edit records already created in the database without going through phpmyadmin. Any help is apreciated.
Edit will be just just like Add, but you need to read the record first and populate the field values.
Start with the code from add and do something like:
<?php $MemberID = (int) $_GET['MemberID']; ?>
<form action="<?php $_SERVER['PHP_SELF']?>" method="post"/> <br>
<input type="hidden" name="MemberID" value="<?php echo $MemberID; ?>"
<?php
require_once('connection.php');
$result = mysqli_query($connection, "SELECT * FROM members where MemberID = $MemberID") or die(mysqli_error());
// loop through results of database query, displaying them in the table
$row = mysqli_fetch_assoc($result);
extract($row);
echo "<label for='memberID' >Member ID:</label>";
echo "$memberID"; // member ID should not be editable
echo "<br /><br />";
echo "<label for='username' >Username:</label>";
echo "<input type='text' name='username' id='username' value="$username" />";
echo "<br /><br />";
The PHP code will have a query like
`UPDATE `members` SET `username` = '$username' ... WHERE `MemberID` = '$MemberID'"
I am required to create a drop down box which gathers the records from a database to populate the drop down. When one of the values is selected, a form is to be displayed which contains the data relating to the value selected.
The form is to have the function of showing the selected data, but also to update the record in the database when filled out and Submit.
I have created a php file to try and accomplish this, but Im getting errors such as undefined index and unknown column.
I am only new to PHP so this is a big task for me. Could someone have a look at my code and inform me if there are any errors.
Ive been trying to piece code together here and there from the net but its been tricky trying to get it all to work.
I am not getting any errors now after some tweaking, but the record wont update. I get a 'record updated successfully' message but the record isn't updated.
I am pretty sure the lack of a record update is coming down to the ID not getting collected properly via the $q=$row["BearId"] but if I use $q=$_GET["q"] I get nothing but errors. I am not completely positive this is the problem though, that is why Im asking the question here.
I would appreciate any help that you can give. Ive gotten so far with this thing and yet I cant get it to update the record.
EDIT: I have pinpointed the problem down to the id in
$sql = "UPDATE //snip WHERE BearId = '$q'";
$q=$row["BearId"];
If I manually change BearId to equal '1' then the record is updated.
updatebears.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Update Bears</title>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("result").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getvalues.php?q="+str,true);
xmlhttp.send();
}
</script>
<style>
// style elements
</style>
</head>
<body>
<h1>Update Bears</h1>
Select a Bear:
<br />
<select name="bears" onchange="showUser(this.value)">
<option value="">Select a BearId</option>
<?php
$query = "SELECT * FROM bears";
$mysqli = new mysqli('localhost','User','123','bears');
$result = $mysqli->query($query);
while($row = $result->fetch_assoc())
echo '<option value="'.$row["BearId"].'">'.$row["BearId"].'</option>';
?>
</select>
<br />
<?php
$q=$row["BearId"];
$mysqli = new mysqli('localhost','User','123','bears');
$sql = "SELECT * FROM bears WHERE BearId='".$q."'";
if(array_key_exists('_submit_check', $_POST))
{
$weight = $_POST['Weight'];
$sex = $_POST['Sex'];
$type = $_POST['Type'];
$colour = $_POST['Colour'];
$breed = $_POST['BreedId'];
$sql = "UPDATE bears SET Weight = '$weight', Sex = '$sex', Type = '$type', Colour = '$colour', Breed = '$breed' WHERE BearId = '$q'";
if($mysqli->query($sql) === TRUE)
{
echo 'Record updated successfully<br />';
}
else
{
echo $sql.'<br />' . $mysqli->error;
}
$mysqli->close();
}
?>
<br />
<div id="result"></div>
<br />
Click here to Visit Task 2 (Insert Bears) | Click here to Visit Task 3 (Display Bears)
</body>
</html>
getvalues.php
<?php
$q=$_GET["q"];
$mysqli = new mysqli('localhost','User','123','bears');
$sql = "SELECT * FROM bears WHERE BearId='".$q."'";
if($stmt = $mysqli->prepare($sql))
{
$stmt->execute();
$stmt->bind_result($BearId, $Weight, $Sex, $Type, $Colour, $Breed);
while ($stmt->fetch())
{
echo "<form method='post' name='form1' onsubmit='return validateForm()' action='updatebears.php'>";
echo "<p>";
echo "<label for='BreedId'>BreedId:</label>";
echo "<br />";
echo "<select id='BreedId' name='BreedId' />";
echo "<option value='".$Breed."'>".$Breed."</option>";
echo "<option value='1'>1. Polar</option>";
echo "<option value='2'>2. Brown</option>";
echo "<option value='3'>3. Panda</option>";
echo "</select>";
echo "</p>";
echo "<p>";
echo "<label for='Weight'>Weight(kg):</label>";
echo "<br />";
echo "<input type='text' id='Weight' name='Weight' value='".$Weight."' />";
echo "</label>";
echo "</p>";
echo "<p>";
echo "Sex: ";
echo "<br />";
echo "<label for='M'>Male</label><input type='radio' id='M' value='M' name='Sex'";
if($Sex=='M') echo "checked";
echo "/>";
echo "<label for='F'>Female</label><input type='radio' id='F' value='F' name='Sex'";
if($Sex=='F') echo "checked";
echo "/>";
echo "</p>";
echo "<p>";
echo "<label for='Type'>Type:</label> ";
echo "<br />";
echo "<input type='text' id='Type' name='Type' maxlength='100' value='".$Type."' />";
echo "</p>";
echo "<p>";
echo "<label for='Colour'>Colour:</label>";
echo "<br />";
echo "<input type='text' id='Colour' name='Colour' maxlength='20' value='".$Colour."' />";
echo "</p>";
echo "<p>";
echo "<input type='submit' value='Submit' />";
echo "<input type='reset' value='Reset' />";
echo "<input type='hidden' name='_submit_check' value=1 />";
echo "</p>";
echo "</form>";
}
}
else
{
echo 'Unable to connect';
exit();
}
?>
Thanks for the help.
I believe what you need to do is create a hidden input type for the BearId within the getvalues.php file. That way when your form performs the post you can get the BearId from the post as opposed to trying to get it from the $row['BearId']. I'm fairly certain $row['BearId'] is not the same $row['BearId'] that the user selected when he first goes to the getvalues.php form. Have you tried printing $row['BearId'] to html to verify it's a legitimate value?
if(array_key_exists('_submit_check', $_POST))
{
$id = $_POST['BearId']
$weight = $_POST['Weight'];
$sex = $_POST['Sex'];
$type = $_POST['Type'];
$colour = $_POST['Colour'];
$breed = $_POST['BreedId'];
$sql = "UPDATE bears SET Weight = '$weight', Sex = '$sex', Type = '$type', Colour = '$colour', Breed = '$breed' WHERE BearId = '$id'";
if($mysqli->query($sql) === TRUE)
{
echo 'Record updated successfully<br />';
}
else
{
echo $sql.'<br />' . $mysqli->error;
}
$mysqli->close();
}
?>
<h1>getvalues.php</h1>
<?php
$q=$_GET["q"];
$mysqli = new mysqli('localhost','User','123','bears');
$sql = "SELECT * FROM bears WHERE BearId='".$q."'";
if($stmt = $mysqli->prepare($sql))
{
$stmt->execute();
$stmt->bind_result($BearId, $Weight, $Sex, $Type, $Colour, $Breed);
while ($stmt->fetch())
{
echo "<form method='post' name='form1' onsubmit='return validateForm()' action='updatebears.php'>";
echo <input type="hidden" name="BearId" value='".$q."'>
echo "<p>";
echo "<label for='BreedId'>BreedId:</label>";
echo "<br />";
echo "<select id='BreedId' name='BreedId' />";
echo "<option value='".$Breed."'>".$Breed."</option>";
echo "<option value='1'>1. Polar</option>";
echo "<option value='2'>2. Brown</option>";
echo "<option value='3'>3. Panda</option>";
echo "</select>";
echo "</p>";
echo "<p>";
echo "<label for='Weight'>Weight(kg):</label>";
echo "<br />";
echo "<input type='text' id='Weight' name='Weight' value='".$Weight."' />";
echo "</label>";
echo "</p>";
echo "<p>";
echo "Sex: ";
echo "<br />";
echo "<label for='M'>Male</label><input type='radio' id='M' value='M' name='Sex'";
if($Sex=='M') echo "checked";
echo "/>";
echo "<label for='F'>Female</label><input type='radio' id='F' value='F' name='Sex'";
if($Sex=='F') echo "checked";
echo "/>";
echo "</p>";
echo "<p>";
echo "<label for='Type'>Type:</label> ";
echo "<br />";
echo "<input type='text' id='Type' name='Type' maxlength='100' value='".$Type."' />";
echo "</p>";
echo "<p>";
echo "<label for='Colour'>Colour:</label>";
echo "<br />";
echo "<input type='text' id='Colour' name='Colour' maxlength='20' value='".$Colour."' />";
echo "</p>";
echo "<p>";
echo "<input type='submit' value='Submit' />";
echo "<input type='reset' value='Reset' />";
echo "<input type='hidden' name='_submit_check' value=1 />";
echo "</p>";
echo "</form>";
}
}
else
{
echo 'Unable to connect';
exit();
}