Trying to make something so I can edit rows from database using a PHP form but when I click edit it shows in the wrong order.
I know I can't edit the top one because it's ID is 0 and i'll change that later on but the others are showing when editing they are Text, Name, Rank
But I want them to be Name, Rank, Text
You can try for yourself here:http://rumblegaming.co.uk/admin/home
<?php
/*
Allows the user to both create new records and edit existing records
*/
// connect to the database
include("connect.php");
// creates the new/edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($name = '', $rank ='', $text ='', $error = '', $id = '')
{ ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
<?php if ($id != '') { echo "Edit Record"; } else { echo "New Record"; } ?>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1><?php if ($id != '') { echo "Edit Record"; } else { echo "New Record"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
} ?>
<form action="" method="post">
<div>
<?php if ($id != '') { ?>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<p>ID: <?php echo $id; ?></p>
<?php } ?>
<strong>Name:</strong> <input type="text" name="name"
value="<?php echo $name; ?>"/><br/>
<strong>Rank:</strong> <input type="text" name="rank"
value="<?php echo $rank; ?>"/><br/>
<strong>Text:</strong> <input type="text" name="text"
value="<?php echo $text; ?>"/><br/>
<input type="submit" name="submit" value="Submit" />
</div>
</form>
</body>
</html>
<?php }
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['id']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id']))
{
// get variables from the URL/form
$id = $_POST['id'];
$name = htmlentities($_POST['name'], ENT_QUOTES);
$rank = htmlentities($_POST['rank'], ENT_QUOTES);
$text = htmlentities($_POST['text'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($name == '' || $rank == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($name, $rank, $text, $error, $id);
}
else
{
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE Team SET name = ?, rank = ?, text = ? WHERE id=?"))
{
$stmt->bind_param("sssi", $name, $rank, $text, $id);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: home");
}
}
// if the 'id' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
{
// make sure the 'id' value is valid
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the recod from the database
if($stmt = $mysqli->prepare("SELECT * FROM Team WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $rank, $text, $name);
$stmt->fetch();
// show the form
renderForm($name, $rank, $text, NULL, $id);
$stmt->close();
}
// show an error if the query has an error
else
{
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else
{
header("Location: home");
}
}
}
/*
NEW RECORD
*/
// if the 'id' variable is not set in the URL, we must be creating a new record
else
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// get the form data
$firstname = htmlentities($_POST['firstname'], ENT_QUOTES);
$lastname = htmlentities($_POST['lastname'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($firstname == '' || $lastname == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($firstname, $lastname, $error);
}
else
{
// insert the new record into the database
if ($stmt = $mysqli->prepare("INSERT players (firstname, lastname) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $firstname, $lastname);
$stmt->execute();
$stmt->close();
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare SQL statement.";
}
// redirec the user
header("Location: view.php");
}
}
// if the form hasn't been submitted yet, show the form
else
{
renderForm();
}
}
// close the mysqli connection
$mysqli->close();
?>
You can simply re-arrange your select statement.
eg. instead of
if($stmt = $mysqli->prepare("SELECT * FROM Team WHERE id=?"));
use
if($stmt = $mysqli->prepare("SELECT Name, Rank, Text FROM Team WHERE id=?"));
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am using this tutorial(http://www.killersites.com/community/index.php?/topic/3064-basic-php-system-view-edit-add-delete-records-with-mysqli/) and I followed every step required in order to create new records into the database but I cannot get update/edit to successfully update my database. I know that the code is not for html5 but I will fix that later. Additionally, retrieve & delete works.
What am I doing wrong? Why is it not working? Any help is greatly appreciated.
Also my table is structured like this,
Table: supplyDetails
Columns:
id int(11) AI PK
localAuthority varchar(50)
supplyRef varchar(50)
supplyName varchar(50)
estimatedDailyWater varchar(10)
numberOfConsumers varchar(45)
dateOfAssessment date
mitigatedRating varchar(2)
finalRating varchar(2)
Here is my records.php
<?php
/*
Allows the user to both create new records and edit existing records
*/
// connect to the database
include("connect-db.php");
// creates the new/edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($localauth = '', $supref = '', $supname = '', $waterusage = '', $numofconsum = '', $dateofassess = '', $mitrating = '', $frating = '', $error = '', $id = '') {
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
<?php
if ($id != '') {
echo "Edit Record";
} else {
echo "New Record";
}
?>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1>
<?php
if ($id != '') {
echo "Edit Record";
} else {
echo "New Record";
}
?>
</h1>
<?php
if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
}
?>
<form action="" method="post">
<div>
<?php
if ($id != '') {
?>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<p>ID: <?php echo $id; ?></p>
<?php } ?>
<label>Local Authority: *</label>
<input type="text" name="localAuthority" value="<?php echo $localauth; ?>"/>
<br/>
<label>Supply Reference: *</label>
<input type="text" name="supplyRef" value="<?php echo $supref; ?>"/>
<br/>
<label>Supply Name: *</label>
<input type="text" name="supplyName" value="<?php echo $supname; ?>"/>
<br/>
<label>Estimated Daily Water Usage: *</label>
<input type="text" name="estimatedDailyWater" value="<?php echo $waterusage; ?>"/>
<br/>
<label>Number of Consumers: *</label>
<input type="text" name="numberOfConsumers" value="<?php echo $numofconsum; ?>"/>
<br/>
<label>Date of Assessment: *</label>
<input type="date" name="dateOfAssessment" value="<?php echo $dateofassess; ?>"/>
<br/>
<label>Mitigated Rating: *</label>
<input type="text" name="mitigatedRating" value="<?php echo $mitrating; ?>"/>
<br/>
<label>Final Rating: *</label>
<input type="text" name="finalRating" value="<?php echo $frating; ?>"/>
<p>* required</p>
<input type="submit" name="submit" value="Submit" />
</div>
</form>
</body>
</html>
<?php
}
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['id'])) {
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit'])) {
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id'])) {
// get variables from the URL/form
$id = $_POST['id'];
$localAuthority = htmlentities($_POST['localAuthority'], ENT_QUOTES);
$supplyRef = htmlentities($_POST['supplyRef'], ENT_QUOTES);
$supplyName = htmlentities($_POST['supplyName'], ENT_QUOTES);
$estimatedDailyWater = htmlentities($_POST['estimatedDailyWater'], ENT_QUOTES);
$numberOfConsumers = htmlentities($_POST['numberOfConsumers'], ENT_QUOTES);
$dateOfAssessment = htmlentities($_POST['dateOfAssessment'], ENT_QUOTES);
$mitigatedRating = htmlentities($_POST['mitigatedRating'], ENT_QUOTES);
$finalRating = htmlentities($_POST['finalRating'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($localAuthority == '' || $supplyRef == '' || $supplyName == '' || $estimatedDailyWater == '' || $numberOfConsumers == '' || $dateOfAssessment == '' || $mitigatedRating == '' || $finalRating == '') {
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($localAuthority, $supplyRef, $supplyName, $estimatedDailyWater, $numberOfConsumers, $dateOfAssessment, $mitigatedRating, $finalRating, $error, $id);
} else {
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE supplyDetails SET localAuthority = ?, supplyRef = ?, supplyName = ?, estimatedDailyWater = ?, numberOfConsumers = ?, dateOfAssessment = ?, mitigatedRating = ?, finalRating = ? WHERE id=?")) {
$stmt->bind_param("sssssdssi", $localAuthority, $supplyRef, $supplyName, $estimatedDailyWater, $numberOfConsumers, $dateOfAssessment, $mitigatedRating, $finalRating, $id);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else {
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: view.php");
}
}
// if the 'id' variable is not valid, show an error message
else {
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else {
// make sure the 'id' value is valid
if (is_numeric($_GET['id']) && $_GET['id'] > 0) {
// get 'id' from URL
$id = $_GET['id'];
// get the recod from the database
if($stmt = $mysqli->prepare("SELECT * FROM supplyDetails WHERE id=?")) {
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $localAuthority, $supplyRef, $supplyName, $estimatedDailyWater, $numberOfConsumers, $dateOfAssessment, $mitigatedRating, $finalRating);
$stmt->fetch();
// show the form
renderForm($localAuthority, $supplyRef, $supplyName, $estimatedDailyWater, $numberOfConsumers, $dateOfAssessment, $mitigatedRating, $finalRating, NULL, $id);
$stmt->close();
}
// show an error if the query has an error
else {
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else {
header("Location: view.php");
}
}
}
/*
NEW RECORD
*/
// if the 'id' variable is not set in the URL, we must be creating a new record
else {
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit'])) {
// get the form data
$localAuthority = htmlentities($_POST['localAuthority'], ENT_QUOTES);
$supplyRef = htmlentities($_POST['supplyRef'], ENT_QUOTES);
$supplyName = htmlentities($_POST['supplyName'], ENT_QUOTES);
$estimatedDailyWater = htmlentities($_POST['estimatedDailyWater'], ENT_QUOTES);
$numberOfConsumers = htmlentities($_POST['numberOfConsumers'], ENT_QUOTES);
$dateOfAssessment = htmlentities($_POST['dateOfAssessment'], ENT_QUOTES);
$mitigatedRating = htmlentities($_POST['mitigatedRating'], ENT_QUOTES);
$finalRating = htmlentities($_POST['finalRating'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($localAuthority == '' || $supplyRef == '' || $supplyName == '' || $estimatedDailyWater == '' || $numberOfConsumers == '' || $dateOfAssessment == '' || $mitigatedRating == '' || $finalRating == '') {
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($localAuthority, $supplyRef, $supplyName, $estimatedDailyWater, $numberOfConsumers, $dateOfAssessment, $mitigatedRating, $finalRating, $error);
} else {
// insert the new record into the database
if ($stmt = $mysqli->prepare("INSERT supplyDetails (localAuthority, supplyRef, supplyName, estimatedDailyWater, numberOfConsumers, dateOfAssessment, mitigatedRating, finalRating)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)")) {
$stmt->bind_param("sssssdss", $localAuthority, $supplyRef, $supplyName, $estimatedDailyWater, $numberOfConsumers, $dateOfAssessment, $mitigatedRating, $finalRating);
$stmt->execute();
$stmt->close();
}
// show an error if the query has an error
else {
echo "ERROR: Could not prepare SQL statement.";
}
// redirec the user
header("Location: view.php");
}
}
// if the form hasn't been submitted yet, show the form
else {
renderForm();
}
}
// close the mysqli connection
$mysqli->close();
?>
view.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1>View Records</h1>
<p><b>View All</b> | View Paginated</p>
<?php
// connect to the database
include('connect-db.php');
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM supplyDetails ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table border='1' cellpadding='10'>";
// set table headers
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Local Authority</th>";
echo "<th>Supply Reference</th>";
echo "<th>Supply Name</th>";
echo "<th>Estimated Daily Water Usage</th>";
echo "<th>Number of Consumers</th>";
echo "<th>Date of Assessment</th>";
echo "<th>Mitigated Rating</th>";
echo "<th>Final Rating</th>";
echo "<th></th><th></th></tr>";
while ($row = $result->fetch_object())
{
// set up a row for each record
echo "<tr>";
echo "<td>" . $row->id . "</td>";
echo "<td>" . $row->localAuthority . "</td>";
echo "<td>" . $row->supplyRef . "</td>";
echo "<td>" . $row->supplyName . "</td>";
echo "<td>" . $row->estimatedDailyWater . "</td>";
echo "<td>" . $row->numberOfConsumers . "</td>";
echo "<td>" . $row->dateOfAssessment . "</td>";
echo "<td>" . $row->mitigatedRating . "</td>";
echo "<td>" . $row->finalRating . "</td>";
echo "<td><a href='records.php?id=" . $row->id . "'>Edit</a></td>";
echo "<td><a href='delete.php?id=" . $row->id . "'>Delete</a></td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
?>
Add New Record
</body>
</html>
connect-db.php
<?php
// server info
$server = 'localhost:3306';
$user = 'root';
$pass = '*****';
$db = 'test';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
?>
SOLUTION for future references.
OK, I managed to come up with an answer. I implemented a proper error handler, thanks to the suggestions above, into my connect-db.php file
mysqli_report(MYSQLI_REPORT_ALL) ;
try {
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
} catch (Exception $e) {
echo $e->getMessage();
}
After fiddling around with editing a record, I was receiving an error regarding the date, so I changed the date type in my mysql table and from date -> varchar (30). (30 may be a lot for a date but meh)
Then I changed my code a bit to reflect those changes,
$dateOfAssessment = htmlentities($_POST['dateOfAssessment'], ENT_QUOTES);
$displaydate = date("D d M Y", strtotime($dateOfAssessment));
And also changed the $stmt to
if ($stmt = $mysqli->prepare("UPDATE supplyDetails SET localAuthority = ?, supplyRef = ?, supplyName = ?, estimatedDailyWater = ?, numberOfConsumers = ?, dateOfAssessment = ?, mitigatedRating = ?, finalRating = ? WHERE id=?")) {
$stmt->bind_param("ssssssssi", $localAuthority, $supplyRef, $supplyName, $estimatedDailyWater, $numberOfConsumers, $displaydate, $mitigatedRating, $finalRating, $id);
$stmt->execute();
$stmt->close();
}
And the output is something like this:
Sat 06 Aug 2016
Thanks everyone who had the time to reply.
OK, I managed to come up with an answer. I implemented a proper error handler, thanks to the suggestions above, into my connect-db.php file
mysqli_report(MYSQLI_REPORT_ALL) ;
try {
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
} catch (Exception $e) {
echo $e->getMessage();
}
After fiddling around with editing a record, I was receiving an error regarding the date, so I changed the date type in my mysql table and from date -> varchar (30). (30 may be a lot for a date but meh)
Then I changed my code a bit to reflect those changes,
$dateOfAssessment = htmlentities($_POST['dateOfAssessment'], ENT_QUOTES);
$displaydate = date("D d M Y", strtotime($dateOfAssessment));
And also changed the $stmt to
if ($stmt = $mysqli->prepare("UPDATE supplyDetails SET localAuthority = ?, supplyRef = ?, supplyName = ?, estimatedDailyWater = ?, numberOfConsumers = ?, dateOfAssessment = ?, mitigatedRating = ?, finalRating = ? WHERE id=?")) {
$stmt->bind_param("ssssssssi", $localAuthority, $supplyRef, $supplyName, $estimatedDailyWater, $numberOfConsumers, $displaydate, $mitigatedRating, $finalRating, $id);
$stmt->execute();
$stmt->close();
}
And the output is something like this:
Sat 06 Aug 2016
Thanks everyone who had the time to reply.
I have been trying to get the names of users from the database using jQuery and php but I've had no luck so far. It manages to post value in the text field to the name.php file but i can't echo out the names linked with the username in the database.
The HTML page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Retail Management Application</title>
</head>
<body>
Name: <input type="text" id="username">
<input type="submit" id="username-submit" value="Grab">
<div id="username-data"></div>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="js/global.js"></script>
</body>
</html>
The global.js file:
$('input#username-submit').on('click', function() {
var username = $('input#username').val();
if ($.trim(username) != '') {
$.post('ajax/name.php', {username: username}, function(data){
$('div#username-data').text(data);
});
};
});
name.php:
<?php
if (isset($_POST['username']) === true && empty($_POST['username']) === false) {
require '../db/connect.php';
$query = mysqli_query("
SELECT `username`.`name`
FROM `users`
WHERE `users` . `username` ='". mysqli_real_escape_string(trim($_POST['username'])). "'
");
/* $query = DB::getInstance()->query("SELECT `username`.`name` FROM users
WHERE `users` . `username`
= '". mysqli_real_escape_string(trim($_POST['username']))."'"); */
echo (mysqli_num_rows($query) !== 0) ? mysql_result($query, 0, 'name') : 'Name not found!';
//tenary operator.
}
?>
connect.php:
<?php
$con = mysqli_connect("localhost","root","root")
or die("Error " . mysqli_error($con));
mysqli_select_db("retail_management_db");
?>
You must use mysqli_fetch_array to get the result and then echo it.
Put this under your mysql query
if($query)
{
while($query_result = mysqli_fetch_array($query))
{
//This returns an array of the fetched values
$name = $query_result['name'];
}
echo $name;
}
else
{
echo "Query Failed";
}
Name.php then becomes
<?php
if (isset($_POST['username']) === true && empty($_POST['username']) === false) {
require '../db/connect.php';
$query = mysqli_query("
SELECT `username`.`name`
FROM `users`
WHERE `users` . `username` ='". mysqli_real_escape_string(trim($_POST['username'])). "'
");
if($query)
{
while($query_result = mysqli_fetch_array($query))
{
//This returns an array of the fetched values
$name = $query_result['name'];
echo $name;
}
}
else
{
echo "Query Failed";
}
/* $query = DB::getInstance()->query("SELECT `username`.`name` FROM users
WHERE `users` . `username`
= '". mysqli_real_escape_string(trim($_POST['username']))."'"); */
//You should not use mysqli with mysql
echo (mysqli_num_rows($query) !== 0) ? mysql_result($query, 0, 'name') : 'Name not found!';
//tenary operator.
}
?>
Edited Area
Don't use Mysql functions with Mysqli
Your name.php now should be
<?php
if (isset($_POST['username']) === true && empty($_POST['username']) === false) {
require '../db/connect.php';
$query = mysqli_query("
SELECT `username`.`name`
FROM `users`
WHERE `users` . `username` ='". mysqli_real_escape_string(trim($_POST['username'])). "'
");
if($query)
{
//We check if the returned rows are at least one
if(mysqli_num_rows($query) > 0)
{
while($query_result = mysqli_fetch_array($query))
{
//This returns an array of the fetched values
$name = $query_result['name'];
echo $name;
}
}
else
{
echo mysqli_real_escape_string(trim($_POST['username'])) . "Name not Found";
}
}
else
{
echo "Query Failed";
}
/* $query = DB::getInstance()->query("SELECT `username`.`name` FROM users
WHERE `users` . `username`
= '". mysqli_real_escape_string(trim($_POST['username']))."'"); */
//You should not use **mysqli** with **mysql**
/*echo (**mysqli_num_rows**($query) !== 0) ? **mysql_result**($query, 0, 'name') : 'Name not found!';*/
//tenary operator.
}
?>
Edit
Use this temporarily as your html file Check if name.php actually echoes anything If it prints anything then the problem is from your js Make sure the action on the form is linked to the correct name.php file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Retail Management Application</title>
</head>
<body>
<form action = 'name.php' method = 'post'>
Name: <input type="text" id="username">
<input type="submit" id="username-submit" value="Grab">
</form>
<div id="username-data"></div>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="js/global.js"></script>
</body>
</html>
I am creating a page where a user can calculate their BMI and then save this to their profile. First I validate the BMI. However, when I perform this calculation now, it is inserting '0.99' into the database instead of the correct BMI value. I have been debugging and think it has something to do with the connection to the database (have tried moving this around to other areas of the script but it isn't making a difference).
The code is below:
<!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=iso-8859-1" />
<title>Untitled Document</title>
</head>
<link rel="stylesheet" href="css.css" type="text/css" />
<body>
<?php
error_reporting(E_ALL &~ E_NOTICE);
// Start the session
session_start();
// Make sure the browser is transmitting in UTF-8
header('Content-type: text/html; charset=utf-8');
// Clear the error message
$error_msg = "";
if (isset($_SESSION['user_id']))
echo $_SESSION['user_id'];
$dbc = mysqli_connect('localhost', 'root', 'root', 'help_me_be_healthy') or die("Error " . mysqli_error($dbc));
mysqli_set_charset($dbc, "utf8");
if(isset($_POST['submit']))
{
$bmi=0;
$kg=$_POST['kg'];
$mt=$_POST['mt'];
if(empty($kg) || empty($mt))
{
echo "<label class='err'><center>All fields are required</center></label>";
include("index.php");
}
else if(!is_numeric($kg) && !is_numeric($mt) )
{
echo "<label class='err'>Please enter valid data.</label>";
include("index.php");
}
else
{
$bmi = $kg/($mt*$mt);
$bmi=round($bmi,2);
if ( $bmi <= 18.5 )
{
echo "Your BMI is " .$bmi." which means you are underweight";
}
else if ( $bmi>18.5 && $bmi <= 24.9) {
echo "Your BMI is ".$bmi." which means you are normal";
}
else if ( $bmi>29.9 && $bmi> 24.9 ) {
echo "Your BMI is ".$bmi." which means you are overweight";
}
else if ( $bmi >29.9 && $bmi<=39.9 ) {
echo "Your BMI is ".$bmi." which means you are obese";
}
else
{
echo "You are morbidly obese.";
}
include("index.php");
//$query = "UPDATE `users` SET `user_bmi`= '$bmi'
//WHERE `user_id` = ($_SESSION = ['user_id'])";
//echo $_SESSION['user_id'];
//if (!isset($_GET['user_id'])) {
//$query = "SELECT * FROM 'users'";
$query = "UPDATE `users` SET `user_bmi`= '$bmi' WHERE `user_id` = '" . $_SESSION['user_id'] . "'";
//}
//else {
// $query = "UPDATE `users` SET `user_bmi`= '$bmi' WHERE `user_id` = '" . $_GET['user_id'] . "'";
//}
$data = mysqli_query($dbc, $query);
$row = mysqli_fetch_assoc($data);
print "\n----\nLookup:\n";
print "Num rows: " . mysqli_num_rows($data);
print "\n";
print_r($row);
print '</pre>';
return;
}
}
?>
</body>
</html>
Any help would be much appreciated:)
Sarah
Assuming BMI is being calculated correctly/displayed, and the user_bmi column is a float/double/numeric/decimal, the UPDATE doesn't need quotes around the value so the SQL should be:
$query = "UPDATE `users` SET `user_bmi`=$bmi WHERE `user_id`=".
$_SESSION['user_id'];
(user_id my also not need to be escaped, depending if it's a number or a string)
Also, you cannot get a query result (fetch_assoc) from an UPDATE SQL command... if you'd like to know the number of effected rows use mysqli_affected_rows:
print "Num rows: ".mysqli_affected_rows($dbc);
What makes you think the BMI is going in incorrectly, are you sure the user_id is correct, how are you looking into the database to determine what's stored?
Updated Code Printout code:
if (!mysqli_query($dbc,$query)) {
echo "Failed to store";
}
echo "<pre>\n----\nLookup:\nQuery:$query\n".
"Num rows:".mysqli_affected_rows($dbc)."\n</pre>\n";
I don't know why I am receving this error but it keeps stating that I have an undefined index: AudioFile on line 35 in code below:
<?php
ini_set('display_errors',1);
session_start();
?>
<body>
<?php
// connect to the database
include('connect.php');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
unlink("AudioFiles/" . $_SESSION['AudioFile']);
$delete = $mysqli->prepare('DELETE FROM Audio WHERE AudioId = ?');
$delete->bind_param("i",$_SESSION['lastAudioID']);
$delete->execute();
$deleteaud = $mysqli->prepare('DELETE FROM Audio_Question WHERE AudioId = ?');
$deleteaud->bind_param("i",$_SESSION['lastAudioID']);
$deleteaud->execute();
?>
</body>
</html>
I don't quite understnd why I am recieving this index error. Does anyone know why I am receving this error?
I defined the $_SESSION variable in the audioupload.php page which is below
<?php
ini_set('session.gc_maxlifetime',12*60*60);
ini_set('session.gc_divisor', '1');
ini_set('session.gc_probability', '1');
ini_set('session.cookie_lifetime', '0');
require_once 'init.php';
session_start();
?>
<!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" />
</head>
<body>
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
// connect to the database
include('connect.php');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
$result = 0;
if ((($_FILES["fileAudio"]["type"] == "audio/wav")
|| ($_FILES["fileAudio"]["type"] == "audio/wma")
|| ($_FILES["fileAudio"]["type"] == "audio/mp3")
|| ($_FILES["fileAudio"]["type"] == "audio/m3u")
|| ($_FILES["fileAudio"]["type"] == "audio/iff")
|| ($_FILES["fileAudio"]["type"] == "audio/mid")
|| ($_FILES["fileAudio"]["type"] == "audio/m4a")
|| ($_FILES["fileAudio"]["type"] == "audio/mpa")
|| ($_FILES["fileAudio"]["type"] == "audio/aif")
|| ($_FILES["fileAudio"]["type"] == "audio/wa"))
&& ($_FILES['fileAudio']['size'] > 0))
{
if( file_exists("AudioFiles/".$_FILES['fileAudio']['name'])) {
$parts = explode(".",$_FILES['fileAudio']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( file_exists("AudioFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileAudio']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileAudio"]["tmp_name"],
"AudioFiles/" . $_FILES["fileAudio"]["name"]);
$result = 1;
}
else
{
move_uploaded_file($_FILES["fileAudio"]["tmp_name"],
"AudioFiles/" . $_FILES["fileAudio"]["name"]);
$result = 1;
}
$audiosql = "INSERT INTO Audio (AudioFile)
VALUES (?)";
if (!$insert = $mysqli->prepare($audiosql)) {
// Handle errors with prepare operation here
}
//Dont pass data directly to bind_param store it in a variable
$insert->bind_param("s",$aud);
//Assign the variable
$aud = 'AudioFiles/'.$_FILES['fileAudio']['name'];
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
$lastAudioID = $mysqli->insert_id;
$_SESSION['lastAudioID'] = $lastAudioID;
$_SESSION['AudioFile'] = $_FILES["fileAudio"]["name"];
$sessid = $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
$sessionquery = "SELECT SessionId FROM Session WHERE (SessionName = ?)";
if (!$sessionstmt = $mysqli->prepare($sessionquery)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
// Bind parameter for statement
$sessionstmt->bind_param("s", $sessid);
// Execute the statement
$sessionstmt->execute();
if ($sessionstmt->errno)
{
// Handle query error here
echo __LINE__.': '.$sessionstmt->error;
break 1;
}
// This is what matters. With MySQLi you have to bind result fields to
// variables before calling fetch()
$sessionstmt->bind_result($sessionid);
// This populates $optionid
$sessionstmt->fetch();
$sessionstmt->close();
$audioquestionsql = "INSERT INTO Audio_Question (AudioId, SessionId, QuestionId)
VALUES (?, ?, ?)";
if (!$insertaudioquestion = $mysqli->prepare($audioquestionsql)) {
// Handle errors with prepare operation here
echo "Prepare statement err audioquestion";
}
$qnum = (int)$_POST['numaudio'];
$insertaudioquestion->bind_param("iii",$lastAudioID, $sessionid, $qnum);
$insertaudioquestion->execute();
if ($insertaudioquestion->errno) {
// Handle query error here
}
$insertaudioquestion->close();
}
?>
<script language="javascript" type="text/javascript">window.top.stopAudioUpload(<?php echo $result; ?>, '<?php echo $_FILES['fileAudio']['name'] ?>');</script>
</body>
</html>
Undefined index means the key 'lastAudioID' does not exist in $_SESSION. You can check this with:
if(array_key_exists('lastAudioID', $_SESSION)) {
// Key exists
}
Seems you did not set the key (or not correctly) in your Code.
Edit:
It may be because you include your file after you have outputted already something. try to include the file before you output anything. I am pretty sure this is it.