MySQL database is updated with empty value when updating using PHP - php

I am new in php, i tried this coding i select a value in my drop down list i want a corresponding value to be updated, i have list of user name in my database and a ID for them, i am displaying the user name and when i want to update i written a sql query to find the member id and update to database but it's inserting a null value. Here is my code.
Dropdown list code
<?
session_start();
if(!isset($_SESSION[''])){
header("location:");
}
?>
<?php include('dbconnect.php'); ?>
<?php
$ed=$_GET['ed'];
$query=mysql_query("select * from table1 where id='$ed'");
$query2= "select * from table2";
$row=mysql_fetch_assoc($query);
if($_POST['Submit'])
{
$mem= $_POST['memid'];
$memname =mysql_query("select memid from table2 where name='$mem'");
$memname1= mysql_fetch_assoc($memname);
$tot_count = mysql_fetch_assoc($ro_count);
$date=date("d-m-Y");
$status="Active";
$onamo=mysql_real_escape_string($_POST['onamo']);
$heid = mysql_real_escape_string($_POST['memname1']);
if($_POST['heid']=='')
{
$namo1="*Required";
$ok=1;
}
if($_POST['onamo']=='')
{
$onamo1="*Required";
$ok=1;
}
$insert=mysql_query("update table1 set oname='$onamo', heid='$heid' where id='$ed'") or die('error');
if($insert)
{
header("Location");
}
}
?>
<body>
<div id="main_container"><br />
<div class="main_content">
<div class="center_content">
<div class="right_content">
<div class="form">
<form action="" method="post" name="fomo" enctype="multipart/form-data" onsubmit="return fall();" class="niceform">
<h1 align="center">Edit Referal Partner </h1>
<?
if($_GET['val']==1) { echo "<h1 class='FeatureBlockHeader' >Member Added Successfully</h1>"; } ?>
<fieldset>
<dl><dt><label for="Owner Name">Referal Partner Name</label></dt><dd><input name="onamo" type="text" size="53" id="onamo" value="<?=$row['oname']?>"/><b style="color:#CA0000"><?=$onamo1?></b></dd></dl>
<dl><dt><label for="">Health Executives</label>
<?php $result1 = mysql_query($query2);
echo'<select name="memid" >';
while($row = mysql_fetch_assoc( $result1 )) {
echo '<option value="'.$row['name'].'">' . $row['name'] . '</option>';
}
echo '</select>'; ?>
</b></dd></dt>
<dl><dt><label for="submit"></label></dt><dd> <input type="submit" name="Submit" value="Submit"></dd></dl></fieldset>
</table>
</form>
'
My database is updated with empty string, if i directly pass the dropdown value Name it's updating fine. But i want to update the corresponding memberid to my table. Please help me.

Stage 1:
You don't do anything if the field is blank. (Plus you have your logic wrong with $ok).
Suggested code would be:
$ok = 1; // assume ok unless we have an error
if($_POST['heid']=='')
{
$namo1="*Required";
$ok=0; // Set to "0" to say "Not Ok"
}
if($_POST['onamo']=='')
{
$onamo1="*Required";
$ok=0; // Set to "0" to say "Not Ok"
}
if ($ok)
{
// Do your update
$insert = mysql_query("update table1 set oname='$onamo', heid='$heid' where id='$ed'") or die('error');
if($insert)
{
header('location: ???');
exit(); // ALWAYS exit after a header redirect, otherwise the rest of the code will continue to work, then the redirect happens!
}
$ok = 0;
$error = 'Failed to update database'
}
// If you get here, you have an error condition.
** Stage 2:**
You should check for isset($_POST['onamo']) before getting the variable. Otherwise it would throw a warning. This will probably give you the error. You have a discrepancy between 'heid' and 'memname1'! :)
$ok = 1; // assume ok unless we have an error
if(!isset($_POST['heid']) || $_POST['heid']=='') // Or is it $_POST['memname1']?
{
$namo1="*Required";
$ok=0; // Set to "0" to say "Not Ok"
}
if(!isset($_POST['onamo']) || $_POST['onamo']=='')
{
$onamo1="*Required";
$ok=0; // Set to "0" to say "Not Ok"
}
if ($ok)
{
$onamo=mysql_real_escape_string($_POST['onamo']);
$heid = mysql_real_escape_string($_POST['memname1']); // Or is it $_POST['heid'] ??
// Do your update
$insert = mysql_query("update table1 set oname='$onamo', heid='$heid' where id='$ed'") or die('error');
if($insert)
{
header('location: ???');
exit(); // ALWAYS exit after a header redirect, otherwise the rest of the code will continue to work, then the redirect happens!
}
$ok = 0;
$error = 'Failed to update database'
}
// If you get here, you have an error condition.

Related

Prevent new rows from being inserted when max records reached?

I have an SQL table where I want the max numbers of records to be 8.
I have a form to capture input via PHP and I thought I had an error handler that operates by counting the number of records in the table and, through an IF statement, punts the user back with an error if there are >= 8 records:
<?php
// Connect to database
include_once 'db_connect.php';
// Check for form action and submitted fields
if (isset($_POST["submit"])) {
$artist = $_POST["artist"];
$song = $_POST["song"];
$link = $_POST["link"];
// Link to external error handling functions
require_once 'functions.php';
// Check for empty fields
if (emptyFields($artist, $song, $link) !== false) {
header("location: index.php?error=empty");
exit();
}
// Check if record already exists
if (songExists($conn, $link, $song) !== false) {
header("location: index.php?error=duplicate");
exit();
}
// Check if link is valid
if (invalidLink($link) !== false) {
header("location: index.php?error=invalidlink");
exit();
}
// Check if table records are greater than or equal to 8
$sql = "SELECT COUNT(*) AS Num FROM songs";
$result = mysqli_query($conn, $sql);
if ($dbName['Num'] >= 8) {
header("location: index.php?error=maxreached");
exit();
}
// If no errors from above, add to table
addSong($conn, $artist, $song, $link);
}
else {
header("location: index.php?error=none");
exit();
}
<?php
include_once 'db_connect.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Song Submission</title>
</head>
<body>
<form action="sb_process2.php" method="POST" autocomplete="off">
<input type="text" name="artist">
<br>
<input type="text" name="song">
<br>
<input type="text" name="link">
<br>
<button type="submit" name="submit">Submit Song</button>
</form>
<?php
if (isset($_GET["error"])) {
if ($_GET["error"] == "empty") {
echo "<p>Please enter all fields.</p>";
}
else if ($_GET["error"] == "duplicate") {
echo "<p>This song has already been submitted.</p>";
}
else if ($_GET["error"] == "invalidlink") {
echo "<p>Please enter a valid URL for the Spotify link.</p>";
}
else if ($_GET["error"] == "none") {
echo "<p>Song added!</p>";
}
}
?>
I tested for my first 3 error cases and all are operating as planned (they route back with an error "code"). However, if I try to submit an entry without any errors, I just get a blank page. I ran the code through a simple PHP syntax checker and it didn't come up with any errors.

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.
....

If there is no $_POST present after a URL, how can I prevent (nothing) from getting passed into a MySQL query, and causing an error?

I have a Delete.php page that deletes records based on their ID.
When there is an ID, i.e., Delete.php?id=3610, all is well, and it functions as expected.
If I just go to "Delete.php" and that's it - no ID, it generates:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1"
From the little I understand, it is doing this because I am trying to pass a nonexistent variable into my query.
I have been trying to put if (empty($_POST['id'])) { } in different places, which removes the error, but breaks something else.
Here is my code:
<?php
require_once 'functions.php';
$conn = mysqli_connect("localhost", "user", "pass",'db');
writeHead("Delete Track");
if (isset($_POST['delete'])) {
$trkid = $_POST['trkid'];
$query = "DELETE FROM track WHERE TrackID=$trkid";
mysqli_query($conn, $query) or die(mysqli_error($conn));
if (mysqli_affected_rows($conn)>0) {
header("Location: Display.php?action=deleted&id=$trkid&status=deleted");
exit();
}
echo "<p class='error'>Unable to update record</p>";
} else {
if (!isset($_GET['id'])) {
echo "<p class='error'>No Track ID provided.<br><a href='Display.php'>Return to display page.</a><p>";
}
$trkid=$_GET['id'];
$query = "SELECT * FROM track WHERE TrackID=$trkid";
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
if (mysqli_num_rows($result)> 0) {
$row = mysqli_fetch_assoc($result);
$Name=$row['Name'];
$Album=$row['AlbumId'];
$Composer=$row['Composer'];
$Milli=$row['Milliseconds'];
$Bytes=$row['Bytes'];
$UnitPrice=$row['UnitPrice'];
} else {
echo "<p class='error'>Unable to retrieve Track $trkid.<br><a href='Display.php'>Return to display page.</a>";
}
}
?>
<p>Track Information:</p>
<p><?php echo "<b>ID: $trkid <br>Title: $Name</b>"; ?></p>
<form method="post" action="Comp3Delete.php">
<p>
<input type="hidden" name="trkid" value="<?php echo $trkid; ?>">
<input type="submit" name="delete" class="btn" value="Confirm Delete">
</p>
</form>
<p>Return to Track Table Display</p>
<?php writeFoot(); ?>
Your post code is fine. it's the GET code that's wrong:
if (!isset($_GET['id'])) {
^^^^^^^^--check if the parameter exists
}
$trkid=$_GET['id'];
^---try to use the parameter ANYWAYS, even if it doesn't exist.
$trkid=$_GET['id']; has no condition so it runs even when no id is passed which generates the error. Your code should go like this:
if(isset($_GET['id'])){
$trkid=$_GET['id'];
$query = "SELECT * FROM track WHERE TrackID=$trkid";
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
if (mysqli_num_rows($result)> 0) {
$row = mysqli_fetch_assoc($result);
$Name=$row['Name'];
$Album=$row['AlbumId'];
$Composer=$row['Composer'];
$Milli=$row['Milliseconds'];
$Bytes=$row['Bytes'];
$UnitPrice=$row['UnitPrice'];
} else {
echo "<p class='error'>Unable to retrieve Track $trkid.<br><a href='Display.php'>Return to display page.</a>";
}
}

Delete confirm only using PHP

I want to delete links to delete images on an SQL database. I am tasked with creating a delete confirm option not using JavaScript just PHP.
require_once("photoalbum-common.php");
$pdo = connect();
if ( isset( $_GET['deletionid'])) {
$errorMessage = deletePhotograph( $pdo, $_GET['deletionid']);
if ( $errorMessage != "") {
print "<div class='errormessage'>$errorMessage</div>\n";
} else {
print "<div class='message'>Image deleted.</div>\n";
}
}
The code below is in "photoalbum-common.php".
<?php
function deletePhotograph( $pdo, $deletionid) {
$errorMessage = "";
// retrieve name of image file so we can delete it
$stmt = $pdo->prepare("SELECT `image` FROM `photographs` WHERE `photoid`=?");
$stmt->execute( array( $deletionid));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ( count( $rows) == 1) {
// delete file
unlink( "images/".$rows[0]['image']);
// delete database record
$stmt = $pdo->prepare("DELETE FROM `photographs` WHERE `photoid`=?");
$stmt->execute( array( $deletionid));
$affected_rows = $stmt->rowCount();
} else if (count( $rows) > 1) {
$errorMessage .= "ID matches more than one record. ";
} else {
$errorMessage .= "ID not found: nothing to delete. ";
}
return $errorMessage;
}
?>
Use something like this. An interstitial page, that accepts a GET request:
GET Request GET /delete.php?id=123
Are you sure you wanna delete?
POST Request POST /delete.php?id=123
Execute the PDO.
You are supposed to write the code for the PHP. If the answer is not enough for this, well, here we go:
<?php
if (count($_POST)) {
// POST Request
deletePhotograph();
} else {
// GET Request
?>
<p>Are you sure you wanna delete?</p>
<!-- Empty action will POST to the same page. -->
<form action="" method="POST"><input type="submit" value="I confirm, Delete" /></form>
<?php
}
?>

Using PHP to add numeric values to two MySQL database rows

I have a site in which logged in users can accumulate points which they can later buy with via a shopping cart. The page below is an admin php feature in which an Admin can give points to an individual user (one user at a time for now).
There are three tables involved with this script:
users: contains the users details
tally_point: stores all of the points transactions, both incoming and ordering
reward_points: stores the total amount of points that the user has
The script retrieves the users’ details via a drop down menu and adds the points to the tally point table ok but....
<?php # add-points-ind.php
// This is the main page for the site.
// Include the configuration file for error management and such.
require_once ('./includes/config.inc.php');
// Set the page title and include the HTML header.
$page_title = 'Add Points to User';
include ('includes/header_admin_user.html');
// If no dealer_code variable exists, redirect the user.
if (!isset($_SESSION['admin_int_id'])) {
// Start defining the URL.
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
// Add the page.
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
?>
<h1>Add Points to User</h1>
<div id="maincontent_inner">
<div id="maincontent_inner2">
<?php //add-points-ind.php
// This page allows the admin to add points to an individual user
require_once ('mydatabase.php'); // Connect to the database.
if (isset($_POST['submitted'])) { // Check if the form has been submitted.
// Check if points were submitted through the form.
if (is_numeric($_POST['tally_points_in'])) {
$p = (float) $_POST['tally_points_in'];
} else {
$p = FALSE;
echo '<p><font color="red">Please enter the pointås!</font></p>';
}
// Validate the User has been selected
if ($_POST['selected_user'] == 'new') {
// If it's a new categories, add the categories to the database.
$query = 'INSERT INTO tally_points (users_id) VALUES (';
// Check for a last_name.
if (!empty($_POST['users_id'])) {
$query .= "'" . escape_data($_POST['users_id']) . "')";
$result = mysql_query ($query); // Run the query.
$a = mysql_insert_id(); // Get the categories ID.
} else { // No last name value.
$a = FALSE;
echo '<p><font color="red">Please enter the Dealers name!</font></p>';
}
} elseif ( ($_POST['selected_user'] == 'existing') && ($_POST['existing'] > 0))
{ // Existing categories.
$a = (int) $_POST['existing'];
} else { // No categories selected.
$a = FALSE;
echo '<p><font color="red">Please select a registered Dealer!</font></p>';
}
if ($p && $a) { // If everything's OK.
// Add the print to the database.
$query = "INSERT INTO tally_point (users_id, tally_points_in, order_id, total, tally_points_entry_date) VALUES ('$a', '$p', '0', '0', NOW())";
if ($result = mysql_query ($query))
{
// Worked.
echo '<p>The reward product has been added.</p><br />Go back<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
} else {
// If the query did not run OK.
echo '<p><font color="red">Your submission could not be
processed due to a system error.</font></p>';
}
} else { // Failed a test.
echo '<p><font color="red">Please click "back" and try again.</font></p>';
}
} else { // Display the form.
?>
<form enctype="multipart/form-data" action="add-points-ind.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="524288" />
<fieldset>
<legend>Add Points Individually:</legend>
<p><b>Select User:</b></p>
<p>
<select name="existing"><option>Select One</option>
<?php // Retrieve all the users details and add to the pull-down menu.
$query = "SELECT users_id, users_sale_id, users_first_name, users_surname FROM users ORDER BY users_surname ASC";
$result = #mysql_query ($query);
while ($row = #mysql_fetch_array ($result, MYSQL_ASSOC)) {
echo "<option value=\"{$row['users_id']}\">{$row['users_sale_id']}: {$row['users_first_name']} {$row['users_surname']} </option>\n";
}
#mysql_close($dbc); // Close the database connection.
?>
</select></p>
<span class="extras"><input type="radio" name="selected_user" value="existing" /> Please confirm this is the correct user</span>
<p><b>Points:</b> <br />
<input type="text" name="tally_points_in" size="10" maxlength="10" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
<input type="hidden"name="submitted" value="TRUE" />
</form>
<?php
} // End of main conditional.
?>
<br class="clearboth" />
End text
</div>
<?php // Include the HTML footer file.
include ('includes/footer_admin_user.html');
?>
... Im having trouble with getting the new points added to the points total field (reward_user_points) in the reward_points table, I have some code below but Im not sure where I am supposed to put it, if anyone has any suggestions please let me know.
<?php
$query = "SELECT reward_user_points FROM reward_points WHERE users_id = $a";
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$TotalPoints = $row['reward_user_points'];
if (#mysql_affected_rows($dbc) == 1) { // Whohoo!
$new_credit = $TotalPoints + $p;
$query = "UPDATE reward_points SET reward_user_points ='$new_credit' WHERE users_id = $a";
$result = #mysql_query($query);
}
?>
Ok, I have to say that I don't understand very well what your trouble is. You say you're having trouble with getting the new points added to the points total field, but could you be a little more specific? Is there any error message returned by php or mysql?

Categories