Insert Foreign Key value from PHP using SELECT option - php

I creating an inventory web-base system by using php and php myadmin (InnoDB). I want to insert the value in inventory when I inserting the record, I can see the data of the (FK) in the dropdown but when I submit the form the data to the db, it returns as no input value in the field and the dropdown not there anymore. Is the way I'm using the foreign key in the dropdown wrong?
I have a table that contains multiple foreign keys.
Table Inventory(
id (pk),
name,
condition_(fk),
producttype (fk))
Table condition_type(
condition_ (pk))
Table producttype(
producttype(fk))
<?php
// Include config file
require_once "../config.php";
// Define variables and initialize with empty values
$name = $condition_ = $producttype = "";
$name_err = $condition_err = $producttype_err = "";
$sql2 = "SELECT * FROM condition_type";
$sql4 = "SELECT * FROM producttype";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
$input_name = trim($_POST["name"]);
if(empty($input_name)){
$name_err = "Please enter a name.";
}else{
$name = $input_name;
}
// Validate condition
$input_condition = trim($_POST["condition_"]);
if(empty($input_condition)){
$condition_err = "Please choose the condition.";
} else{
$condition_ = $input_condition;
}
// Validate producttype
$input_producttype = trim($_POST["prodcuttype"]);
if(empty($input_producttype)){
$producttype_err = "Please enter the product type..";
} else{
$producttype = $input_producttype;
}
// Check input errors before inserting in database
if(empty($name_err) && empty($condition_err) && empty($producttype_err)){
// Prepare an insert statement
$sql = "INSERT INTO inventory (name, condition_, producttype) VALUES (?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("sss", $param_name, $param_condition, $param_producttype);
// Set parameters
$param_name = $name;
$param_condition = $condition;
$param_producttype = $producttype;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header("location: ../application");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
// Close connection
$mysqli->close();
}
?>
-------> This is the form
<div class="form-group <?php echo (!empty($condition_err)) ? 'has-error'
: ''; ?>">
<label>Condition</label>
</br>
<select id="condition_" name="condition_" class="form-control" value="<?
php echo $condition_ ;?>">
<option>Please Select Product Condition</option>
<?php
if($result2 = $mysqli ->query($sql2)){
while($row = $result2->fetch_array()){
echo "<option value=".$row['condition_'].">" .$row['condition_']. "
</option>";
}
}
?>
</select>
<span class="help-block"><?php echo $condition_err;?></span>
</div>
<div class="form-group <?php echo (!empty($producttype_err)) ? 'has-
error' : ''; ?>">
<label>Product</label>
</br>
<select name="producttype" class="form-control" value="<?php echo
$producttype ;?>">
<?php if($result4 = $mysqli ->query($sql4)){
while($row = $result4->fetch_array()){
echo "<option value=".$row['producttype'].">" .$row['producttype']. "
</option>";
}
}
?>
</select>
<span class="help-block"><?php echo $manufacturer_err;?></span>
</div>
So when I submit it return as the condition and producttype are empty. I think the error is because of
}
// Close connection
$mysqli->close();
}
statement that already close. But I don't know to place it.
PHP Warning: mysqli::query(): Couldn't fetch mysqli in /home/my-path/application/create_new.php on line 173

You should debug the html form first by right click with 'Inspect element' and make sure that the 'Select' value is getting?

Related

PHP code inserts into sql db with text box inputs but not with select options (dropdowns)

Through hours of research and looking through code in questions submitted on this site, I was finally able to get the select options (dropdowns) to pull data from my database tables into the dropdown lists on my html form.
However, my issue is that when the fields on the form were inputs they inserted the new information into the database just fine. Unfortunately, now that I've implemented the dropdown lists as part of the form, none of the information from the form inserts into the database anymore. Clicking on the 'submit' button returns the response that it was successful, but when I check the table in the database, the new information is not there.
I'm sorry I haven't been able to figure this piece of functionality out by myself. I noticed my last question received negative feedback, so I'm leary to even submit this one, but I really need some help.
Will you please look through the following code and let me know what I'm missing or have coded incorrectly? I just need to know what I need to do to make the selected values from the dropdown lists insert into the 'dvd' table and 'categoryname' and 'genretype' fields, respectively.
<?php
session_start();
//include the header
include ('../main/header.php');
// Check if the form has been submitted.
if (isset($_POST['submitted'])) {
require_once ('../../../mysqli_connect.php'); // Connect to the db.
$errors = array(); // Initialize error array.
// Check for a first name.
if (empty($_POST['title'])) {
$errors[] = 'You forgot to enter a title.';
} else {
$title = mysqli_real_escape_string($dbc, $_POST['title']);
}
// Check for a category.
if (empty($_POST['numavail'])) {
$errors[] = 'You forgot to enter quantity purchased.';
} else {
$numavail = mysqli_real_escape_string($dbc, $_POST['numavail']);
}
// Check for a category.
if (empty($_POST['categoryname'])) {
$errors[] = 'You forgot to enter a category.';
} else {
$categoryname = mysqli_real_escape_string($dbc, $_POST['categoryname']);
}
// Check for a genre.
if (empty($_POST['genretype'])) {
$errors[] = 'You forgot to enter a genre.';
} else {
$genretype = mysqli_real_escape_string($dbc, $_POST['genretype']);
}
if (empty($errors)) { // If everything's OK.
// Add the movie to the database.
// Check for existing record.
$query = "SELECT id FROM dvd WHERE title='$title'";
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
if ($result) { // If it ran OK.
echo "<p><b>Success! The new movie has been added.</b></p>";
echo ('<p><div style="margin-top:30px;">');
echo ('<span style="float:left;">');
echo ('<FORM METHOD="LINK" ACTION="../dvd/index.php"><INPUT TYPE="submit" VALUE="Back to DVDs" STYLE="margin:0px 15px 0px 0px;"></form></span></div></p>');
echo ('<br style="clear:both;"></br>');
exit();
} else { // If it did not run OK.
$errors[] = 'The movie could not be added due to a system error. We apologize for any inconvenience.'; // Public message.
$errors[] = mysqli_error($dbc); // MySQL error message.
}
} else { // Title is already taken.
$errors[] = 'The movie title entered already exists.';
}
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} else { // Form has not been submitted.
$errors = NULL;
} // End of the main Submit conditional.
// Begin the page now.
if (!empty($errors)) { // Print any error messages.
echo '<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo "$msg<br />";
}
echo '</p>';
echo '<p style="color:red; font-weight:bold;"><em>Please try again.</em></p></br>';
}
// Create the form.
?>
<h1>Add a Movie</h1>
<h2>Please complete all of the fields below:</h2>
<form action="../dvd/add.php" method="post">
<p>Title: <input type="text" name="title" size="15" maxlength="15" value="<?php echo $_POST['title']; ?>"></p>
<p>Quantity Purchased: <input type="text" name="numavail" size="15" maxlength="30" value="<?php echo $_POST['numavail']; ?>"></p>
<p>
<?php
include ('../../../mysqli_connect.php'); // Connect to the db.
$ddlquery = "SELECT categoryname FROM category ORDER BY categoryname ASC";
$ddlresult = mysqli_query($dbc, $ddlquery) or die("Bad SQL: $ddlquery");
echo 'Category: <select name="categoryname" size="1">';
while($ddlrow=mysqli_fetch_array($ddlresult, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow['categoryname']."'>" . $ddlrow['categoryname'] . "</option>";
}
echo "</select>";
?>
<p>
<?php
$ddlquery2 = "SELECT genretype FROM genre ORDER BY genretype ASC";
$ddlresult2 = mysqli_query($dbc, $ddlquery2) or die("Bad SQL: $ddlquery");
echo 'Genre: <select name="genretype" size="1">';
while($ddlrow2=mysqli_fetch_array($ddlresult2, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow2['genretype']."'>" . $ddlrow2['genretype'] . "</option>";
}
echo "</select>";
?>
<p>
<input type="submit" name="submit" value="Submit">
<input type=reset value=Reset>
<input type="hidden" name="submitted" value="TRUE"></p>
</form>
<?php
// Include footer.php
include("../../includes/footer.php");
?>
You forgot to actually run the insert into database
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
$result = mysqli_query($dbc, $query); // <---- ADD HERE
if ($result) { // If it ran OK.
....

PHP MySQL row editor showing in wrong order

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=?"));

bind_param(): variables != parameters [duplicate]

This question already has answers here:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 1 year ago.
I've just been trying to get this working for about 2 hours now, I can't understand what I'm doing wrong.
This is the error I'm getting :
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement in /demo/records.php on line 117
also here:
<?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($emri = '', $cmimi ='', $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>vEmri: *</strong> <input type="text" name="vEmri"
value="<?php echo $emri; ?>"/><br/>
<strong>vCmimi: *</strong> <input type="text" name="vCmimi"
value="<?php echo $cmimi; ?>"/>
<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'];
$vEmri = htmlentities($_POST['vEmri'], ENT_QUOTES);
$vCmimi= htmlentities($_POST['vCmimi'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($vEmri == '' || $vCmimi == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($vEmri, $vCmimi, $error, $id);
}
else
{
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE veturat SET vEmri = ?, vCmimi= ?
WHERE id=?"))
{
$stmt->bind_param("ssi", $vEmri, $vCmimi, $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 veturat WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $vEmri, $vCmimi);
$stmt->fetch();
// show the form
renderForm($vEmri, $vCmimi, 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
$vEmri= htmlentities($_POST['vEmri'], ENT_QUOTES);
$vCmimi = htmlentities($_POST['vCmimi'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($vEmri == '' || $vCmimi == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($vEmri, $vCmimi, $error);
}
else
{
// insert the new record into the database
if ($stmt = $mysqli->prepare("INSERT veturat (vEmri, vCmimi) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $vEmri, $vCmimi);
$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();
?>
Define the columns fetched explicitly. This should work (line 112):
// get the record from the database
if($stmt = $mysqli->prepare("SELECT id, vEmri, vCmimi, vNgjyra, vLenda, vTransmisioni, vKilometra, vProdhimi, vVellimi FROM veturat WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $vEmri, $vCmimi, $vNgjyra, $vLenda, $vTransmisioni, $vKilometra, $vProdhimi, $vVellimi);
$stmt->fetch();
// show the form
renderForm($vEmri, $vCmimi, NULL, $id);
$stmt->close();
}
You must have the same number of arguments in $stmt->bind_result() as the number of columns your SELECT query is fetching.

Updating SQL with form and PHP. Values resetting to 0 on submit?

I am attempting to create a simple form that updates a row in a MYSQL database based on what ID the row is.
I have managed to get the form and updating values working, but for one of my variables I need its new value to be added to it, based on the values of two other variables. (So like $currPoints = $currPoints+$addPoints-$remPoints;).
The problem I am facing is that whenever the form is submitted, $currPoints is either resetting to 0, then adding and subtracting the other values, or the value of $cuurPoints isn't being found so that it cannot add to it's original value.
I am not sure where specifically in my code I am going wrong so I will paste the whole page if that is okay!
My form function. This get's called on page load:
// creates the form
function renderForm($name = '', $currPoints = '', $addPoints = '', $remPoints = '', $reason = '', $error = '', $id = '')
{ ?>
<title>
<?php if ($id != '') { echo "Edit Punk"; } else { echo "New Punk"; } ?>
</title>
<h1><?php if ($id != '') { echo "Edit Punk"; } else { echo "New Punk"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
} ?>
<form name="pointsForm" action="" method="post" style="margin-top:50px;">
<?php if ($id != '') { ?>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<p>Name: <?php echo $name; ?> / <?php echo $currPoints; ?></p>
<?php } ?>
<input type="number" name="addPoints" placeholder="Add Punk Points">
<input type="number" name="remPoints" placeholder="Remove Punk Points">
<input type="text" name="reason" placeholder="Reason">
<input type="submit" name="submit" value="Update Punk Points">
</form>
</body>
</html>
<script>
$(function() {
$('form[name="pointsForm"]').submit(function(e) {
var reason = $('form[name="pointsForm"] input[name="reason"]').val();
if ( reason == '') {
e.preventDefault();
window.alert("Enter a reason, fool!")
}
});
});
</script>
<?php
}
Then my PHP for editing a record:
Where I get the variables from the URL/form I have added $currPoints = $currPoints+$addPoints-$remPoints;
Then on my bind_param is just add $currPoints.
I believe I am going wrong somewhere around these lines... or where I SET currPoints = ? . should that be something else?
Forgive me I am just learning 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'];
$addPoints = htmlentities($_POST['addPoints'], ENT_QUOTES);
$remPoints = htmlentities($_POST['remPoints'], ENT_QUOTES);
$reason = htmlentities($_POST['reason'], ENT_QUOTES);
$currPoints = $currPoints+$addPoints-$remPoints;
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE points SET currPoints = ? , addPoints = ?, remPoints = ?, reason = ?
WHERE id=?"))
{
$stmt->bind_param("iiisi", $currPoints, $addPoints, $remPoints, $reason, $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: index.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 record from the database
if($stmt = $mysqli->prepare("SELECT * FROM points WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $name, $currPoints, $addPoints, $remPoints, $reason, $date);
$stmt->fetch();
// show the form
renderForm($name, $currPoints, $addPoints, $remPoints, $reason, 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: index.php");
}
}
}
?>
Sorry If I have been too vague. Please let me know if you need more information.
Thank you!
Oh found the error I think, you are never defining $currPoints before you try and use it, so you can't have $currPoints = $currPoints+.. because it isn't created yet. PHP more or less so will read line by line, so you have to query the SQL table and set $currPoints equal to the value from your database before you do $currPoints = $currPoints+$addPoints-$remPoints;
Ok, this probably won't work, but you should be able to figure out what I changed and adapt your code to work with it. I wouldn't say it's the 'proper' way, but it is a little easier to read and see what the code is doing when you have the if statements at the top to deal with what data is submitted vs not submitted.
if (!isset($_GET['id'] || !isset($_POST['submit'])))
{
echo "No Data!"
return;
}
if (!is_numeric($_POST['id']))
{
echo "Invalid ID!";
header("Location: index.php");
return;
}
// get variables from the URL/form
$id = $_POST['id'];
$addPoints = htmlentities($_POST['addPoints'], ENT_QUOTES);
$remPoints = htmlentities($_POST['remPoints'], ENT_QUOTES);
$reason = htmlentities($_POST['reason'], ENT_QUOTES);
$currPoints = 0;
//Check what the current points are first
// make sure the 'id' value is valid also
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the record from the database
if($stmt = $mysqli->prepare("SELECT * FROM points WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $name, $currPoints, $addPoints, $remPoints, $reason, $date);
$stmt->fetch();
// show the form
renderForm($name, $currPoints, $addPoints, $remPoints, $reason, NULL, $id);
$stmt->close();
}
else
echo "Error: could not prepare SQL statement";
}
//Now update currPoints
$currPoints += $addPoints-$remPoints;
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE points SET currPoints = ? , addPoints = ?, remPoints = ?, reason = ?
WHERE id=?"))
{
$stmt->bind_param("iiisi", $currPoints, $addPoints, $remPoints, $reason, $id);
$stmt->execute();
$stmt->close();
}
else
echo "ERROR: could not prepare SQL statement.";
// redirect the user once the form is updated
header("Location: index.php");

Radio Button not storing the value in database?

I got a problem this is simple form i have to submit the data through radio buttons problem is that no value is displayed in database neither of disases name nor for yes,no option I have created database with name doctor with fields id ,dis_name,and ans.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
if (!empty($_POST)) {
// keep track validation errors
$disError = null;
$ansError = null;
// keep track post values
$dis_name = isset($_POST['dis_name']);
$ans=isset($_POST['ans']);
// validate input
$valid = true;
if (empty($dis_name)) {
$disError = 'Please enter Diseases Name';
$valid = false;
}
if (empty($ans)) {
$ansError = 'Please check one of option';
$valid = false;
}
// insert data
if ($valid) {
if(isset($_POST['dis_name'])){
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO diseases (dis_name) values(?)";
$q = $pdo->prepare($sql);
$q->execute(array($dis_name));
Database::disconnect();
//header("location: diseases.php");
}
}
}
?>
//some html code here
<div class="control-group <?php echo !empty($ansError)?'error':'';?>">
<label class="check">Have you suffered pain preiviously???</label>
<div class="controls">
<input type="radio" name="choice" <?php if (isset($ans) && $ans=="yes") echo "checked";?>
value="Yes">Yes
<input type="radio" name="choice"<?php if (isset($ans) && $ans=="no") echo "checked";?>
value="No">No
<?php
//if(isset($_POST['submit'])){
if(!empty($_POST['choice'])){
$ans=isset($_POST['ans']);
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO diseases (question) values(?)";
$q = $pdo->prepare($sql);
$q->execute(array(isset($_POST['choice'])));
Database::disconnect();
}
//}
?>
`isset() it gives undefined index warning.`
I suppose ans stands for answer which is filled by the radio control value. And this is how you fetch it on server side:
$ans=isset($_POST['ans']);
In your html it is actually choice
Shouldn't you be getting it like this?
$ans=isset($_POST['choice']);
EDIT:
And why would you use isset function to fetch post value?
isset() returns boolean and the input is named 'choice'.
Perhaps you mean:
if( isset($_POST['choice']) ){
$ans = $_POST['choice'];
// Optionally you may want $ans to be boolean:
if($ans == 'Yes') {
$ans = TRUE;
} else {
$ans = FALSE;
}
}
then (if the table column is properly defined to store the boolean/integer/enum):
$q->execute(array($ans));
will store 1 (True) or 0 (False)

Categories