Update query not updating table - php

I have a user data profile that I want to update when a user has filled out a form. When the update query is run values are being passed to the PHP script but not being changed in the table.
HTML of form:
echo "<br />";
echo "From this page you can change your profile details.";
echo "<br />";
echo "<br />";
echo "<form id='edit' action='../scripts/editscript.php' method='post' accept-charset='UTF-8'>";
echo "<label for='firstname'>First Name:</label>";
echo "<input type='text' id='firstname' name='firstname' />";
echo "<br />";
echo "<label for='lastname'>Last Name:</label>";
echo "<input type='text' id='lastname' name='lastname' />";
echo "<br />";
echo "<label for='username'>User Name:</label>";
echo "<input type='text' id='username' name='username' />";
echo "<br />";
echo "<label for='password'>Password:</label>";
echo "<input type='password' id='password' name='password' />";
echo "<br />";
echo "<label for='passwordconfirm'>Confirm Password:</label>";
echo "<input type='password' id='passwordconfirm' name='passwordconfirm' />";
echo "<br />";
echo "<label for='email'>E-Mail:</label>";
echo "<input type='email' id='email' name='email' />";
echo "<br />";
echo "<label for='like'>Something you like:</label>";
echo "<input type='text' id='like' name='like' />";
echo "<br />";
echo "<label for='dislike'>Something you dislike</label>";
echo "<input type='text' id='dislike' name='dislike' />";
echo "<br />";
echo "<label for='fact'>A fun fact about yourself:</label>";
echo "<input type='text' id='fact' name='fact' />";
echo "<br />";
echo "<label for='allow'>Do you want other people to see parts of your profile:</label>";
echo "<input type='radio' name='allow' value='yes' /> Yes";
echo "<input type='radio' name='allow' value='no' /> No";
echo "<br />";
echo "<br />";
echo "<input type='submit' name='submit' value='Confirm' />";
echo "</form>";
PHP script:
<?PHP
session_start();
$time = time();
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$salt = substr(base64_encode(openssl_random_pseudo_bytes(17)),0,22);
$salt = str_replace("+",".",$salt);
$salt = '$2a$08$' . $salt;
$password = crypt($_POST['password'], $salt);
$email = $_POST['email'];
$like = $_POST['like'];
$dislike = $_POST['dislike'];
$fact = $_POST['fact'];
$allow = $_POST['allow'];
$UID = $_SESSION['user']['UID'];
if ($allow == 'yes') {
$allowvalue = 1;
} else {
$allowvalue = 0;
};
$con = mysqli_connect('localhost','//db_username','//db_pass','//table');
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "UPDATE users SET firstname = '" . $firstname . "',
lastname = '" . $lastname . "',
username = '" . $username . "',
password = '" . $password . "',
email = '" . $email . "',
like = '" . $like . "',
dislike = '" . $dislike . "',
fact = '" . $fact . "',
allowview = " . $allowvalue . " WHERE UID = " . $UID . "";
mysqli_query($con,$query);
mysqli_close($con);
?>
I really don't get why this isn't going as expected. Any help is appreciated. :)

Prepared statements are not only good for avoiding sql infection but they will also help you organizing your code hence make your code more solid
<?php
session_start();
/*your variables*/
$time = time();
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$salt = substr(base64_encode(openssl_random_pseudo_bytes(17)),0,22);
$salt = str_replace("+",".",$salt);
$salt = '$2a$08$' . $salt;
$password = crypt($_POST['password'], $salt);
$email = $_POST['email'];
$like = $_POST['like'];
$dislike = $_POST['dislike'];
$fact = $_POST['fact'];
$allow = $_POST['allow'];
$UID = $_SESSION['user']['UID'];
if ($allow == 'yes') {
$allowvalue = 1;
} else {
$allowvalue = 0;
};
$mysqli = new mysqli("localhost", "//db_username", "//db_pass", "//table");
/* check connection */
if (mysqli_connect_errno()) {
echo ("Failed to connect to MySQL:: %s\n", mysqli_connect_error());
exit();
}
/* Prepare an update statement */
$query = "UPDATE users SET firstname = ?,
lastname = ?,
username = ?,
password = ?,
email = ?,
like = ?,
dislike = ?,
fact = ?,
allowview = ? WHERE UID = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ssssssssii",$firstname, $lastname, $username, $password, $email,
$like, $dislike, $fact, $allowvalue, $UID);
/* Execute the statement */
$stmt->execute();
/* close connection */
$mysqli->close();
?>

do a
var_dump($_SESSION['user']['UID']);
most probably the id does not match the id in the db

I figured out what it was. One of the columns in my database was 'like'. This is a MySQL keyword so it was messing with my query, thanks for the suggestions anyway :)

Related

MYSQLI Real Escape String not working with apostrophe's [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
How to prevent XSS with HTML/PHP?
(9 answers)
Closed 17 days ago.
I have the following code:
<?php
/*
Template Name: trial_app_review
*/
get_header();
?>
<div class="form-container">
<form style="margin-top: 150px;" method="post">
<?php
// Connect to the MySQL database using the MySQLi object
$mysqli = new mysqli('host', 'user', 'password', 'db');
// Check for errors
if ($mysqli->connect_error) {
echo "Error: " . $mysqli->connect_error;
} else {
// Check if the button was clicked
if (isset($_POST['insert_btn'])) {
// Get the values of the row that the button belongs to
$WK = $_POST['WK']; $WK = mysqli_real_escape_string($mysqli, $WK);
$Trial_Year = $_POST['Trial_Year']; $Trial_Year = mysqli_real_escape_string($mysqli, $Trial_Year);
$Trial_Dates = $_POST['Trial_Dates'];$Trial_Dates = mysqli_real_escape_string($mysqli, $Trial_Dates);
$Trial_Club = $_POST['Trial_Club']; $Trial_Club = mysqli_real_escape_string($mysqli, $Trial_Club);
$Trial_Classes = $_POST['Trial_Classes']; $Trial_Classes = mysqli_real_escape_string($mysqli, $Trial_Classes);
$Ring_Width = $_POST['Ring_Width']; $Ring_Width = mysqli_real_escape_string($mysqli, $Ring_Width);
$Ring_Height = $_POST['Ring_Height']; $Ring_Height = mysqli_real_escape_string($mysqli, $Ring_Height);
$double_yes_no = $_POST['double_yes_no']; $double_yes_no = mysqli_real_escape_string($mysqli, $double_yes_no);
$FeePd = $_POST['FeePd']; $FeePd = mysqli_real_escape_string($mysqli, $FeePd);
$num_days = $_POST['num_days']; $num_days = mysqli_real_escape_string($mysqli, $num_days);
$start_date = $_POST['start_date']; $start_date = mysqli_real_escape_string($mysqli, $start_date);
$Trial_City = $_POST['Trial_City']; $Trial_City = mysqli_real_escape_string($mysqli, $Trial_City);
$Trial_St = $_POST['Trial_St']; $Trial_St = mysqli_real_escape_string($mysqli, $Trial_St);
$trial_sec = $_POST['trial_sec']; $trial_sec = mysqli_real_escape_string($mysqli, $trial_sec);
$Trial_Email = $_POST['Trial_Email']; $Trial_Email = mysqli_real_escape_string($mysqli, $Trial_Email);
$Trial_Website = $_POST['Trial_Website']; $Trial_Website = mysqli_real_escape_string($mysqli, $Trial_Website);
$end_date = $_POST['end_date']; $end_date = mysqli_real_escape_string($mysqli, $end_date);
$street_addr = $_POST['street_addr']; $street_addr = mysqli_real_escape_string($mysqli, $street_addr);
$distckwk = $_POST['distckwk']; $distckwk = mysqli_real_escape_string($mysqli, $distckwk);
$club_id = $_POST['club_id']; $club_id = mysqli_real_escape_string($mysqli, $club_id);
$pend_id = $_POST['ID']; $pend_id = mysqli_real_escape_string($mysqli, $pend_id);
$query = "INSERT INTO Calendar (pend_id, WK, Trial_Year, Trial_Dates, Trial_Club, Trial_City, Trial_St, Trial_Classes, Ring_Width, Ring_Height, double_yes_no, Trial_FName, Trial_Email,
Trial_Website, FeePd, start_date, end_date, street_addr, distckwk, club_id,Pend_Confirm)
VALUES ('$pend_id', '$WK', '$Trial_Year', '$Trial_Dates', '$Trial_Club', '$Trial_City', '$Trial_St', '$Trial_Classes', '$Ring_Width', '$Ring_Height', '$double_yes_no', '$trial_sec',
'$Trial_Email', '$Trial_Website', '$FeePd', '$start_date', '$end_date', '$street_addr','$distckwk', '$club_id',CONCAT('Confirmed-', CURRENT_DATE()))";
$result = $mysqli->query($query);
if ($result) {
$update = "UPDATE PendingCalendar SET Pend_Confirm = CONCAT('Confirmed-', CURRENT_DATE()) WHERE ID = '$pend_id'";
$update_result = $mysqli->query($update);if ($update_result) {
echo '<script>window.location.href = "https://nadac.com/success.php";</script>';
} else {
echo "Error: " . $mysqli->error;
}
} else {
echo "Error: " . $mysqli->error;
}
}
else {
// Execute a SELECT query and check for errors
$result = $mysqli->query("SELECT * FROM PendingCalendar WHERE Pend_Confirm IS NULL OR Pend_Confirm ='' ORDER BY WK DESC");
if (!$result) {
echo "Error: " . $mysqli->error;
} else {
// Add the stylesheet
echo "<style>
table {
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
</style>";
// Create the updated HTML table
echo "<table>\n";
echo " <tr>\n";
echo " <th>Action</th>\n";
echo " <th>WK</th>\n";
echo " <th>Trial_Year</th>\n";
echo " <th>Trial_Club</th>\n";
echo " <th>Trial_Classes</th>\n";
echo " <th>Ring_Width</th>\n";
echo " <th>Ring_Height</th>\n";
echo " <th>double_yes_no</th>\n";
echo " <th>Fee Pd</th>\n";
echo " <th>start_date</th>\n";
echo " <th>end_date</th>\n";
echo " </tr>\n";
// Iterate over the results and print each row
while ($row =
$result->fetch_assoc()) {
// Print the table row
echo " <tr>\n";
echo " <td>\n";
echo " <form method='post' >\n";
echo " <input type='hidden' name='ID' value='" . $row['ID'] . "'>\n";
echo " <input type='hidden' name='WK' value='" . $row['WK'] . "'>\n";
echo " <input type='hidden' name='Trial_Year' value='" . $row['Trial_Year'] . "'>\n";
echo " <input type='hidden' name='Trial_Club' value='" . $row['Trial_Club'] . "'>\n";
echo " <input type='hidden' name='Trial_Classes' value='" . $row['Trial_Classes'] . "'>\n";
echo " <input type='hidden' name='Ring_Width' value='" . $row['Ring_Width'] . "'>\n";
echo " <input type='hidden' name='Ring_Height' value='" . $row['Ring_Height'] . "'>\n";
echo " <input type='hidden' name='double_yes_no' value='" . $row['double_yes_no'] . "'>\n";
echo " <input type='hidden' name='FeePd' value='" . $row['FeePd'] . "'>\n";
echo " <input type='hidden' name='start_date' value='" . $row['start_date'] . "'>\n";
echo " <input type='hidden' name='end_date' value='" . $row['end_date'] . "'>\n";
echo " <input type='hidden' name='Trial_Dates' value='" . $row['Trial_Dates'] . "'>\n";
echo " <input type='hidden' name='Trial_City' value='" . $row['Trial_City'] . "'>\n";
echo " <input type='hidden' name='Trial_St' value='" . $row['Trial_St'] . "'>\n";
echo " <input type='hidden' name='Trial_Email' value='" . $row['Trial_Email'] . "'>\n";
echo " <input type='hidden' name='Trial_Website' value='" . $row['Trial_Website'] . "'>\n";
echo " <input type='hidden' name='street_addr' value='" . $row['street_addr'] . "'>\n";
echo " <input type='hidden' name='distckwk' value='" . $row['distckwk'] . "'>\n";
echo " <input type='hidden' name='club_id' value='" . $row['club_id'] . "'>\n";
echo " <input type='hidden' name='trial_sec' value='" . $row['trial_sec'] . "'>\n";
echo " <button type='submit' name='insert_btn'>Insert</button>\n";
echo " </form>\n";
echo " </td>\n";
echo " <td>" . $row['WK'] . "</td>\n";
echo " <td>" . $row['Trial_Year'] . "</td>\n";
echo " <td>" . $row['Trial_Club'] . "</td>\n";
echo " <td>" . $row['Trial_Classes'] . "</td>\n";
echo " <td>" . $row['Ring_Width'] . "</td>\n";
echo " <td>" . $row['Ring_Height'] . "</td>\n";
echo " <td>" . $row['double_yes_no'] . "</td>\n";
echo " <td>" . $row['FeePd'] . "</td>\n";
echo " <td>" . $row['start_date'] . "</td>\n";
echo " <td>" . $row['end_date'] . "</td>\n";
echo " </tr>\n";
} echo "</table>\n";
}
}
}
?>
</form>
</div>
And it works. But when a column has an apostrophe, it removes everything after the apostrophe.
I am definitely a beginner, but I thought the escape string would prevent that from happening?
I made a test record and using something like this: NADAC,Testing'testing"testing it gets shortened to: NADAC,Testing
What am I missing?

cannot for the life of me get $caseid to post

Good day
I have a form that gets the case id from previous post, i then do a select with it and all works 100%
I then let them fill in data and upload files. all good, everything posts as should expect the caseid!!!!
code below.
<!---<input type="submit" value="Submit">-->
<?php
require_once("../models/config.php");
if(isUserLoggedIn()) {
if (!securePage($_SERVER['PHP_SELF'])){die();}
require_once("../models/header.php");
echo "<link href='../models/site-templates/default.css' rel='stylesheet' type='text/css' />";
//$servername = "***.****.***.***";
$servername = "***.****.***.***.****";
$username = "202";
$password = "202#202";
$dbname = "*********";
$caseid = $_REQUEST['caseid'];
echo "
<body>
<div id='wrapper'>
<div id='top'><div id='logo'></div></div>
<div id='content'>
<h1>Cases</h1>
<div id='left-nav'>";
include("../left-nav.php");
echo "</div><div id='main'>";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "
SELECT
id
, case_number
, date_entered
, name
, STATUS
, description
, cust_phone_no
, claim_number_c
, contactname_c
, contact_type_c
, telephonehome_c
, telephonebusiness_c
, telephonemobile_c
, policynumber_c
, billing_address_street
, billing_address_city
, billing_address_state
, billing_address_postalcode
, billing_address_country
, customer_name
FROM
*******.sp_case_view
where id = '$caseid'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$caseid = $row["id"];
$case_number = $row["case_number"];
$date_entered = $row["date_entered"];
$name = $row["name"];
$status = $row["STATUS"];
$description = $row["description"];
$cust_phone_no = $row["cust_phone_no"];
$claim_number_c = $row["claim_number_c"];
$contactname_c = $row["contactname_c"];
$contact_type_c = $row["contact_type_c"];
$telephonehome_c = $row["telephonehome_c"];
$telephonebusiness_c = $row["telephonebusiness_c"];
$telephonemobile_c = $row["telephonemobile_c"];
$policynumber_c = $row["policynumber_c"];
$billing_address_street = $row["billing_address_street"];
$billing_address_city = $row["billing_address_city"];
$billing_address_state = $row["billing_address_state"];
$billing_address_postalcode = $row["billing_address_postalcode"];
$billing_address_country = $row["billing_address_country"];
$customer_name = $row["customer_name"];
echo "<a href='cases.php'><b>Back to Cases</b></a><br><br>";
echo "Customer Name: " . $customer_name ."<br>";
echo "<br>";
echo "Case Number: " . $case_number ."<br>";
echo "Created On: " . $date_entered ."<br>";
echo "<br>";
echo "Description: " . $description ."<br>";
echo "Phone Number: " . $cust_phone_no ."<br>";
echo "Claim Number: " . $claim_number_c ."<br>";
echo "Contact Person: " . $contactname_c ."<br>";echo "<br>";
echo "Address Details: <br>";
echo "Street: " . $billing_address_street ."<br>";
echo "City: " . $billing_address_city ."<br>";
echo "Province: " . $billing_address_state ."<br>";
//echo "Name: <input type='text' value='" . $description . "'><br>";
}
$up_id = uniqid();
require_once("../models/footer.php");
$conn->close();
}
else {
header('location: ../login.php');
}
$full_path = "c:/scott/source/";
$number_of_uploads = 4;
$allowed_file_types = array("jpg","gif","png","txt","zip","xls","doc","docx","xlsx","txt","pdf");
$upload_folder = "./uploads/";
$max_size_in_kb = 10000024;
$rename_files = 1;
echo $caseid;
function printForm()
{
global $allowed_file_types,$number_of_uploads,$max_size_in_kb;
print "<html>
<head>
<meta http-equiv='content-type' content='text/html; charset=utf-8' />
<title></title>
<meta name='description' content='' />
<meta http-equiv='Language' content='en' />
<meta name='language' content='en' />
<!--Progress Bar and iframe Styling-->
</head>
<body>
<br><b>Enter your closure details</b>
<!--<form action='upload.php' method='post'> -->
<form enctype='multipart/form-data' action='upload.php' method='post' name='upload-form' id='upload-form'>
<table>
<tr><td>Plumber Cost including vat: </td><td><input type='text' name='plumcost'></td></tr>
<tr><td>Enter description of work done: </td><td><input type='textarea' name='descrepair'></td></tr>
<tr>
<td>Old Geyser Make: </td><td><input type='text' name='geyserold'> </td>
</tr>
<tr>
<td>Old Geyser Serial Number: </td><td><input type='text' name='geyseroldserial'> </td>
</tr>
<tr>
<td>New Geyser Serial Number: </td><td><input type='text' name='geysernew'> </td>
</tr>
</table>
\n";
for($i=0;$i<$number_of_uploads;$i++)
{
if($i == '0') {
echo "Invoice";
}
elseif($i == '1') {
echo "POD";
}
elseif($i == '2') {
echo "Stocksheet";
}
elseif($i == '3') {
echo "Pictures Zipped";
}
print "<p><input type=\"file\" name=\"file[]\" /></p>\n";
}
print "<p><input type=\"hidden\" name=\"upload\" value=\"1\" /><input type=\"submit\" value=\"Upload\" /></p>\n</form>\n";
print "<p>Allowed file types: ." . implode($allowed_file_types, " ."). "</p>\n";
}
$fileNAMES = array();
if(isset($_POST['upload']))
{
for($i=0;$i<$number_of_uploads;$i++)
{
if(strlen($_FILES['file']['name'][$i]) > 0)
{
$filearray = explode(".", $_FILES['file']['name'][$i]);
$ext = end($filearray);
if($rename_files == 1)
{
if($i==0)
{
$fileNAMES[$i] = $caseid."invoice";
}
if($i==1)
{
$fileNAMES[$i] = $caseid."stocksheet";
}
if($i==2)
{
$fileNAMES[$i] = $caseid."POD";
}
if($i==3)
{
$fileNAMES[$i] = $caseid."picture";
}
}
else
{
$xperiods = str_replace("." . $ext, "", $_FILES['file']['name'][$i]);
$fileNAMES[$i] = str_replace(".", "", $xperiods);
}
if(!in_array(strtolower($ext), $allowed_file_types))
{
print "<p class=\"error\">FAILED: ". htmlspecialchars($_FILES['file']['name'][$i]) ."<br />ERROR: File type not allowed.</p>\n";
}
elseif($_FILES['file']['size'][$i] > ($max_size_in_kb*1024))
{
print "<p class=\"error\">FAILED: ". htmlspecialchars($_FILES['file']['name'][$i]) ."<br />ERROR: File size to large.</p>\n";
}
elseif(file_exists($upload_folder.$fileNAMES[$i] .".". $ext))
{
print "<p class=\"error\">FAILED: ". htmlspecialchars($fileNAMES[$i]) .".". $ext ."<br />ERROR: File already exists.</p>\n";
}
else
{
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $upload_folder.$fileNAMES[$i] .".". $ext))
{
print "<p>UPLOADED: ". htmlspecialchars($fileNAMES[$i]) .".". $ext ."</p>\n";
}
else
{
print "<p class=\"error\">FAILED: ". htmlspecialchars($_FILES['file']['name'][$i]) ."<br />ERROR: Undetermined.</p>\n";
}
}
}
}
printForm();
}
else
{
printForm();
}
?>
</form>
</div></body>
</html>
<?php } else {
echo "0 results";
echo $caseid;
} ?>

Form is submitting multiple entries to the database instead of single

my code basically override requests (for classes that are full in capacity) submitted by students to specific professors. Let's say 2 students have requested an override to the same class, when a professor is logged in, the code fetches the two override requests with an option of accepting/denying, when i as a professor accept/deny a single override request, it does the action for both the override requests instead of the one i chose.
Basically it's not accepting/denying the requests as selected, its doing the same action for all overrides.
Code:
<?php
} else if ($usertype == 1) {
$server = "";
$user = "";
$pass = "";
$db = "";
$db2 = "";
$db3 = "";
$user1 = $_SESSION['username'];
$mysqli = new Mysqli($server, $user, $pass, $db) or mysqli_error($mysqli);
$mysqli2 = new Mysqli($server, $user, $pass, $db2) or mysqli_error($mysqli);
$mysqli3 = new Mysqli($server, $user, $pass, $db3) or mysqli_error($mysqli);
$status= $mysqli->query("SELECT status FROM Overrides WHERE professor = '$user1'")->fetch_object()->status;
$overrides = $mysqli->query("SELECT * FROM Overrides WHERE professor = '$user1'");
$num_rows = mysqli_num_rows($overrides);
?>
<form method="post" action="dbheads.php" name="HF" id="HF" autocomplete="off">
<script type="text/javascript">
function submitForm(action)
{
document.getElementById('HF').action = action;
document.getElementById('HF').submit();
}
</script>
<?php if ($status == 1) {
echo " Overrides today: " . $num_rows;
?>
<?php
while($row = mysqli_fetch_array($overrides)) { ?>
<fieldset> <?php
echo "First Name: " . $row['name'] . "<br />";
echo "<br />Mid. Name: " . $row['mname'] . "<br />";
echo "<br />Fam. Name: " . $row['fname'] . "<br />";
echo "<br />Student ID: " . $row['sid'] . "<br />";
echo "<br />Scolarship: " . $row['sc'] . "<br />";
echo "<br />Phone No: " . $row['phone'] . "<br />";
echo "<br />Email: " . $row['email'] . "<br />";
echo "<br />Subject: " . $row['subject'] . "<br />";
echo "<br />Section: " . $row['section'] . "<br />";
echo "<br />Semester: " . $row['semester'] . "<br />";
$name = $row['name'];
echo "<input type='hidden' name='name' value='$name'>";
$mname = $row['mname'];
echo "<input type='hidden' name='mname' value='$mname'>";
$fname = $row['fname'];
echo "<input type='hidden' name='fname' value='$fname'>";
$sid = $row['sid'];
echo "<input type='hidden' name='sid' value='$sid'>";
$sc = $row['sc'];
echo "<input type='hidden' name='sc' value='$sc'>";
$phone = $row['phone'];
echo "<input type='hidden' name='phone' value='$phone'>";
$email = $row['email'];
echo "<input type='hidden' name='email' value='$email'>";
$subject = $row['subject'];
echo "<input type='hidden' name='subject' value='$subject'>";
$section = $row['section'];
echo "<input type='hidden' name='section' value='$section'>";
$semester = $row['semester'];
echo "<input type='hidden' name='semester' value='$semester'>";
?>
<br />
<div>
<label for="comments" accesskey="c">Notes & Comments:</label><br />
<input type="textarea" name="comments" id="comments" cols="35" rows="10">
<br>
</div>
<br>
<script type="text/javascript">
function submitForm(action)
{
document.getElementById('HF').action = action;
document.getElementById('HF').submit();
}
</script>
...
<input type="button" onclick="submitForm('dbheads.php')" value="Accept" />
<input type="button" onclick="submitForm('dbheads2.php')" value="Deny" /></form>
</fieldset>
<br>
<?php } }
?>
<br />
dbheads.php
<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';
sec_session_start();
?>
<html>
<?php
$mysql_host = "";
$mysql_username = "";
$mysql_password = "r!~";
$mysql_database = "";
$user = $_SESSION['username'];
if (login_check($mysqli) == true) : ?>
<p>Welcome <?php echo htmlentities($user); ?>!</p>
<?php
$mysqli = new Mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database) or die(mysqli_error());
$status = 2;
$stmt = $mysqli->prepare("UPDATE Overrides SET status=? WHERE username='$user'");
$stmt->bind_param("s", $status);
$stmt->execute();
echo htmlentities(accepted);
?>
<?php else : ?>
<p>
<span class="error">You are not authorized to access this page.</span> Please login.
</p>
<?php endif; ?>
</html>
bheads2.php
<html>
<?php
$mysql_host = "";
$mysql_username = "";
$mysql_password = "";
$mysql_database = "";
$user = $_SESSION['username'];
if (login_check($mysqli) == true) : ?>
<p>Welcome <?php echo htmlentities($user); ?>!</p>
<?php
$mysqli = new Mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database) or die(mysqli_error());
$status = 5;
$stmt = $mysqli->prepare("UPDATE Overrides SET status=? WHERE username='$user'");
$stmt->bind_param("s", $status);
$stmt->execute();
echo htmlentities(denied);
?>
<?php else : ?>
<p>
<span class="error">You are not authorized to access this page.</span> Please login.
</p>
<?php endif; ?>
</html>
Any help on how can i fix this? I'm a beginner so ignore the messy code.
It seems you are updating the database with the following query
$stmt = $mysqli->prepare("UPDATE Overrides SET status=? WHERE username='$user'")
Which is simply saying where the username is the person logged in or using the page will be updated to the status of your choosing, do you have a unique identifier for each row of overrides? Override_ID maybe.
If so I would fetch that data on your first page and put it into a hidden input like the other data and then use the following query:
$ovid = $_POST['ovid'];
$stmt = $mysqli->prepare("UPDATE Overrides SET status=? WHERE override_id='$ovid'")
EDIT:
You also seem to be updating WHERE username='$user'as opposed to WHERE professor='$user' on your update pages

Writing data to database

this piece of code i have below reads data from a database, what i want to make is that when you click submit on the following form, it would write the same data to another database and when denied, it would also submit it to another different database. Can you help? since i can't get how to do it.
<?php
} else if ($usertype == 1) {
$server = "localhost";
$user = "";
$pass = "r=Sc!~";
$db = "";
$user1 = $_SESSION['username'];
$mysqli = new Mysqli($server, $user, $pass, $db) or mysqli_error($mysqli);
$overrides = $mysqli->query("SELECT * FROM Overrides WHERE professor = '$user1'");
$num_rows = mysqli_num_rows($overrides);
?>
<?php
echo " Overrides today: " . $num_rows;
?>
<form method="post" action="dbheads.php" name="HeadWritingForm" id="HeadWritingForm" autocomplete="off">
<fieldset>
<?php
while($row = mysqli_fetch_array($overrides)) {
echo "First Name: " . $row['name'] . "<br />";
echo "<br />Mid. Name: " . $row['mname'] . "<br />";
echo "<br />Fam. Name: " . $row['fname'] . "<br />";
echo "<br />Student ID: " . $row['sid'] . "<br />";
echo "<br />Scolarship: " . $row['sc'] . "<br />";
echo "<br />Phone No: " . $row['phone'] . "<br />";
echo "<br />Email: " . $row['email'] . "<br />";
echo "<br />Class: " . $row['class'] . "<br />";
echo "<br />Section: " . $row['section'] . "<br />";
echo "<br />Semester: " . $row['semester'] . "<br />";
}
?>
<br />
<div>
<label for="comments" accesskey="c">Notes & Comments:</label><br />
<textarea name="comments" cols="35" rows="10">
</textarea><br>
</div>
<br>
<input type="submit" class="submit" id="submit" value="Accept" /> <input type="submit" value="Deny"><br>
</fieldset>
</form>
enter code here
<?php
$server = "localhost";
$user = "";
$pass = "r=Sc!~";
$db1 = "Overrides ";
$db2 = "ONTHERDB";
$user1 = $_SESSION['username'];
$mysqli = new Mysqli($server, $user, $pass, $db1) or mysqli_error($mysqli);
$overrides = $mysqli->query("SELECT * FROM Overrides WHERE professor = '$user1'");
$num_rows = mysqli_num_rows($overrides);
$mysqli = new Mysqli($server, $user, $pass, $db2) or mysqli_error($mysqli);
while($row = mysqli_fetch_array($overrides)) {
$QUERY="INSERT INTO $db2(name,mname,fname,sid,sc,phone,email,class,section,semester)VALUES($row[0],
$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10] );
mysqli_query($QUERY);
}

Edit Records PHP Form

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'"

Categories