I'm currently struggling with a page that allows a user to complete one of two options. They can either update an existing item in the SQL database or they can delete it. When the customer deletes an option everything runs perfectly well, however whenever a customer updated an item it displays the Query failed statement from the delete function before applying the update.
It seems obvious to me that the problem must be in my IF statement and that the DeleteButton function isn't exiting if the $deleteno variable isn't set. Any help would be appreciated. Excuse the horribly messy code PHP isn't a language I am familiar with. (I have not included the connect information for privacy reasons)
function DeleteButton(){
#mysqli_select_db($con , $sql_db);
//Checks if connection is successful
if(!$con){
echo"<p>Database connection failure</p>";
} else {
if(isset($_POST["deleteID"])) {
$deleteno = $_POST["deleteID"];
}
if(!isset($deleteno)) {
$sql = "delete from orders where orderID = $deleteno;";
$result = #mysqli_query($con,$sql);
if((!$result)) {
echo "<p>Query failed please enter a valid ID </p>";
} else {
echo "<p>Order $deleteno succesfully deleted</p>";
unset($deleteno);
}
}
}
}
That is the code for the delete button and the following code is for the UpdateButton minus the connection information (which works fine).
if(isset($_POST["updateID"])) {
$updateno = $_POST["updateID"];
}
if(isset($_POST["updatestatus"])) {
if($_POST["updatestatus"] == "Fulfilled") {
$updatestatus = "Fulfilled";
} elseif ($_POST["updatestatus"] == "Paid") {
$updatestatus = "Paid";
}
}
if(isset($updateno) && isset($updatestatus)) {
$sql ="update orders set orderstatus='$updatestatus' where orderID=$updateno;";
$result = #mysqli_query($con,$sql);
if(!$result) {
echo "<p>Query failed please enter a valid ID</p>";
} else {
echo "<p>Order: $updateno succesfully updated!</p>";
}
}
Once again these are incomplete functions as I have omitted the connection sections.
if(!isset($deleteno)) {
$sql = "delete from orders where orderID = $deleteno;";
Are you sure you want to execute that block if $deleteno is NOT set?
P.S. You shouldn't rely on $_POST['deleteId'] being a number. Please read about SQL injections, how to avoid them and also about using prepared statements.
I've update your code, but you need to write cleaner code ( spaces, indents, etc ) this won't only help you to learn but to find your errors easily.
<?php
function DeleteButton()
{
#mysqli_select_db($con , $sql_db);
/*
Checks if connection is successful
*/
if(!$con){
echo"<p>Database connection failure</p>";
} else {
/*
Check if $_POST["deleteID"] exists, is not empty and it is numeric.
*/
if(isset($_POST["deleteID"]) && ! empty($_POST["deleteID"]) && ctype_digit(empty($_POST["deleteID"]))
$deleteno = $_POST["deleteID"];
$sql = "delete from orders where orderID='$deleteno'";
$result = #mysqli_query($con,$sql);
if(!$result){
echo "<p>Query failed please enter a valid ID </p>"
} else {
echo "<p>Order $deleteno succesfully deleted</p>";
unset($deleteno);
}
} else {
echo "<p>Please enter a valid ID </p>" ;
}
}
}
/*
Part 2:
===========================================================================
Check if $_POST["updateID"] exists, is not empty and it is numeric.
Check if $_POST["updatestatus"] exists, is not empty and equal to Paid or Fullfilled
*/
if( isset($_POST["updateID"]) &&
! empty($_POST["updateID"]) &&
ctype_digit(empty($_POST["updateID"]) &&
isset($_POST["updatestatus"]) &&
! empty($_POST["updatestatus"]) &&
( $_POST["updatestatus"] == "Fulfilled" || $_POST["updatestatus"] == "Paid" ) )
{
$updateno = $_POST["updateID"];
$updatestatus = $_POST["updatestatus"];
$sql ="update orders set orderstatus='$updatestatus' where orderID=$updateno;";
$result = #mysqli_query($con,$sql);
if(!$result){
echo "<p>Query failed please enter a valid ID</p>";
} else {
echo "<p>Order: $updateno succesfully updated!</p>";
}
}
There is an error in MySQL Syntax
$sql = "delete from orders where orderID = $deleteno;";
$deleteno after orderID must be inside single quotes.
change it to this $sql = "delete from orders where orderID = '$deleteno';";
Related
We'll get to the point...
I have a simple form (2 of them) that relies off the previous filled out.
The intention of these forms are to sign, post to db, validate email. After the user validates their email their permission will change to be able to see the next form.
These forms work great, and everything is functional in exception to this last bit.
I am having difficulty with the form applying the values to the db table when there is existing user.
What I would like to do is only have it update the keys for that user where users session-ed API key =$API AND form_ica_initials is NULL in the roster table. If it does then will INSERT INTO
Here is what I have cleaned up. (originally wrote for the first phase of the forms to be filled out, trying to tweak to work for last half of forms)
if (empty($_POST['initials'])) { $error[] = 'You must enter your initials in every box below.'; }
else { $initials = $_POST['initials']; }
$API = $_SESSION['API'];
if (empty($error)) {
$query_verify_form = "SELECT * FROM roster WHERE API ='$API'";
$result_verify_form = mysqli_query($dbc, $query_verify_form);
if (!$result_verify_form) {
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_form) == 0) {
$form_icaauth = md5(uniqid(rand(), true));
error_reporting(E_ALL);
$query_insert_user = "UPDATE `roster`
(
`fullname`, `form_ica_initials`, `form_icaauth`,`form_ica_ip`
)
VALUES (
'$fullname', '$initials', '$form_icaauth','$DOCSIGNEDBYIP'
)
";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) {
...
echo '<br><center><div class="success">...</div>';
}
else {
echo '<center><div class="error">...</div></center>';
}
}
else {
echo '<center><div class="warning" >...</div></center>';
}
}
else {
echo '<center><div class="info"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ol></div></center>';
}
mysqli_close($dbc); //Close the DB Connection
}
If I change the if (mysqli_num_rows($result_verify_form) == 0) { to ==1 It will post the values to the table by creating a new record, and not update the existing users fields as specified. However, by doing that it will circumvent the errors that I have structured.
I know my way around PHP a bit... but having difficultly with this one
I was able to get it to work with the following.
if (empty($error)) {
$query_verify_form = "SELECT * FROM roster WHERE API='$API' AND form_ica_initials IS NULL";
$result_verify_form = mysqli_query($dbc, $query_verify_form);
if (mysqli_num_rows($result_verify_form) == 1) {
$form_icaauth = md5(uniqid(rand(), true));
error_reporting(E_ALL);
$query_insert_user = "UPDATE roster SET fullname='$fullname', form_ica_initials='$initials', API='$API', form_icaauth='$form_icaauth', form_ica_ip='$DOCSIGNEDBYIP'";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo '<center><div class="error">Query Failed </div></center>';
}
First I had to change if (mysqli_num_rows($result_verify_form) == 1) from 0 to 1 to return Yes we've found that record.
I then had to change the INSERT INTO ... VALUES to UPDATE ... SET. I added also added AND form_ica_initials IS NULL to validate that the user hasn't completed this form yet. IF they have, then we'd prompt with a message to check their email. If they havent then we'd run the UPDATE
This is a really simple one, I just can't get my head around it sorry. I have this PHP code which picks up my form value, then compares it with the value stored in the database. That works fine.
However I am not sure how to write this logic in terms of this query:
If posted value = database value {
// do something } else { // do something else }
if (empty($_POST['order_id']) === false) {
// prepare data for inserting
$order_id = htmlentities(trim($_POST['order_id']));
$order_id = preg_replace("/[^0-9]/","", $order_id);
$result = mysqli_query($con,"SELECT * FROM listings WHERE order_id = $order_id");
$row = mysqli_fetch_assoc($result);
echo $row['order_id'];
}
SOLVED:
Solved the question, was a silly one I know! Just needed this at the end of the code:
if($order_id === $row['order_id']) {
echo 'found';
} else {
echo 'not found';
}
Try
If ($result->num_rows === 1) { do something } else { do something else }
Since you did the business logic in your query you can just use
if( ! is_null($row)) {
// do
} else {
// nothing
}
Did I read too much into "If posted value = database value "? Are you just referring to the order_id?
if ($row['listingName'] == $_POST['frm_listingName']) {
// something
}
else {
//something else
}
Check this code:
if (empty($_POST['order_id']) === false) {
// prepare data for inserting
$order_id = htmlentities(trim($_POST['order_id']));
$order_id = preg_replace("/[^0-9]/","", $order_id);
$result = mysqli_query($con,"SELECT * FROM listings WHERE order_id = $order_id");
if(mysqli_num_rows($result)>0)
{
//Match found. do something.
}
else
{
//No match found. do something.
}
}
N.B. In place of mysqli_num_rows($result) you can also use $result->num_rows
I am new in PHP and need help with my below code. When I am entering wrong userid instead of giving the message "userid does not exist" it is showing "password/id mismatch. Please guide me where I am wrong.
<?php
session_start();
$id = $_POST['userid'];
$pwd = $_POST['paswd'];
$con = mysqli_connect("localhost", "????", "????", "??????");
if ($con) {
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
if ($result) {
$row = mysql_fetch_array($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist !!!";
}
} else {
echo "Connection failed - ".mysqli_error()." -- ".mysqli_errno();
}
?>
The main problem you have is that you're mixing up between the mysqli and mysql functions. These two libraries are not compatible with each other; you must only use one or the other.
In other words, the following line is wrong:
$row=mysql_fetch_array($result);
It needs to be changed to use mysqli_.
While I'm here, going off-topic for a moment I would also point out a few other mistakes you're making:
You aren't escaping your SQL input. It would be extremely easy to hack your code simply by posting a malicious value to $_POST['userid']. You must use proper escaping or parameter binding. (since you're using mysqli, I recommend the latter; it's a better technique).
Your password checking is poor -- you don't appear to be doing any kind of hashing, so I guess your passwords are stored as plain text in the database. If this is the case, then your database is extremely vulnerable. You should always hash your passwords, and never store the actual password value in the database.
I've gone off topic, so I won't go any further into explaining those points; if you need help with either of these points I suggest asking separate questions (or searching here; I'm sure there's plenty of existing advice available too).
else
{
echo "ID/Password Mismatch";
}
is connected with the
if($row["userid"]==$id && $row["paswd"]==$pwd)
{
So since you are giving a wrong id. It echo's: ID/Password Mismatch
Also the else at if ($result) { wont ever show since
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
You need some additionnal checks:
select * return 1 row (not 0, and not more)
you need to protect the datas entered by the html form (for example someone could enter 1 or 1 to return all rows
<?php
session_start();
$con = mysqli_connect("localhost", "????", "????", "??????");
$id = mysqli_real_escape_string($_POST['userid']);
$pwd = mysqli_real_escape_string($_POST['paswd']);
if ($con) {
// don't even do the query if data are incomplete
if (empty($id) || empty($pwd)
$result = false;
else
{
// optionnal : if userid is supposed to be a number
// $id = (int)$id;
$result = mysqli_query($con, "SELECT * FROM users WHERE userid='$id'");
}
if (mysqli_num_rows($result) != 1)
$result = false;
if ($result) {
$row = mysqli_fetch_assoc($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist, or incomplete input";
}
} else {
echo "Connection failed - " . mysqli_error() . " -- " . mysqli_errno();
}
?>
Try with isset() method while you are checking if $result empty or not.
that is in line
if ($result) {.......}
use
if (isset($result)) { .......}
$result is always true, because mysqli_query() only returns false if query failed.
You could check if $result has actual content with empty() for example.
You can use this sql compare password as well with userid
$sql= "SELECT * FROM users WHERE userid='".$id.", and password='".$pwd."'";
so I have searched this problem and found similar ones, but I'm not sure of how to translate their solutions into mine - mainly because I'm a noob in PHP. I'm working on it. Bear with me. I appreciate the help!
Right now, I am trying to make it so my form will not allow duplicate entries for the email column in phpmysql. So far, I went into the structure tab there, and made it unique. Pretty much viola. However, I would like the error message to display on the same page when the form is submitted, instead of reloading it and giving the message. Also, I would like to customize the message. Seeing as its a phpmysql related error, I'm not sure if I would do that with PHP coding, or somewhere in there.
Thanks guys. I appreciate the help.
<?php
function checkField($v){
return (isset($v) && $v === false) ? true: false;
}
function startMysql(){
$con=mysqli_connect("localhost", "shiftedr_admin", "passwerd", "shiftedr_whosthedeeusers");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return null;
}
return $con;
}
// function closeMySql($connection){
// mysqli_close($connection);
// }
function formcheck(){
$con=mysqli_connect("localhost", "shiftedr_admin", "shithead1", "shiftedr_whosthedeeusers");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
if (isset($_POST['submitted'])){
$form = null;
if (empty($_POST['fullname'])){
$form['fullnameflag'] = false;
}
if (empty($_POST['email'])){
$form['emailflag'] = false;
}
if (empty($_POST['password'])){
$form['passwordflag'] = false;
}
if (empty($_POST['pwc'])){
$form['pwcflag'] = false;
}
if (empty($_POST['userbday'])){
$form['userbday'] = false;
}
if (empty($_POST['gender'])){
$form['genderflag'] = false;
}
if ($_POST['password'] != $_POST['pwc']){
$form['fixpasswordconfirm'] = false;
}
/*$query = mysql_query ("SELECT * FROM users2 WHERE email = '". Email'" ."'");
if (mysql_num_rows($query) > 0)
{
echo 'Email Address is Already In Use.';
}*/
if (empty($form)) { // all fields correct at this point, do database stuff
$sql="INSERT INTO Users2 (fullname, Email, Password, userbday, Gender) VALUES ('".$_POST['fullname']."','".$_POST['email']."','".$_POST['password']."','".$_POST['userbday']."','".$_POST['gender']."')";
if (!mysqli_query($con,$sql)){
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
}
mysqli_close($con);
return $form;
}
}
//// / include("myfunctions.php");
?>
I am guessing you have two pages - myform.php and process.php or something similar so try doing this
<?php
$error = null;
if( isset( $_POST['submitted'] ) ) // Same as your check is submitting if
{
// Below is an example fail
if( empty( $_POST['fullname'] ) ) $error = 1;
// So for the email address failing you would put
if( mysql_num_rows($query) > 0 ) $error = 2;
if(! $error )
{
// all good no errors here so do database stuff....
}
else
{
header("Location: form.php?error=$error"); // return the error code to previous page
}
}
?>
Were one could be an empty field or could be fullname is empty and two is used email address or something similar and on your myform.php page have
<?php
if( isset( $_GET['error'] ) )
{
switch ( $_GET['error'] )
{
case 1 : echo "One of the fields is empty"; break;
case 2 : echo "Your email address has already been used"; break;
default : echo "Unknown error occured";
}
}
?>
I have a database with a 'status' column which either reads 'active' or 'inactive'.
I'd like to return different text depending on whether the status is 'active' or 'inactive', and I'm using if... and elseif... for this.
If the status is 'active', the message is displaying perfectly. This also prompts the database to update the status field to 'inactive' - again, this is working perfectly.
But if I reload the page, using a key for which I know the status is 'inactive', nothing displays.
<?php
if (isset($_GET['key'])) {
$key = $_GET['key'];
include("db.php");
$download_query="SELECT * FROM sales WHERE key='$key'";
$download_result=#mysql_query($download_query);
$download_row=#mysql_fetch_array($download_result, MYSQL_ASSOC);
$productid=$download_row['productid'];
$datecreated=$download_row['datecreated'];
$dateaccessed=$download_row['dateaccessed'];
$status=$download_row['status'];
if ($status=="active") {
$download_updatestatus_query="UPDATE `sales` SET `status`='inactive' WHERE `key`='$key'";
$download_updatestatus_result=#mysql_query($download_updatestatus_query) or die (mysql_error());
echo "Go ahead and download file.";
}
else if ($status=="inactive") {
echo "You may have downloaded this before.";
}
}
else {
echo "Sorry, no key provided.";
}
?>
You have an extra } after your elseif. try:
else if ($status=="inactive") {
echo "You may have downloaded this before.";
}
else {
You suppose to make sure that mysql_query is not false and contains some results by running mysql_num_rows before you start fetching data.
Also passing $_GET value to MySQL Query without validation is very bad idea.
if (isset($_GET['key']))
{
//You have to make sure that provided value is safe to use in mysql query
$key = mysql_real_escape_string($_GET['key']);
include("db.php");
$download_query = "SELECT * FROM sales WHERE key='$key'";
$download_result = mysql_query($download_query);
// Check result
if (!$download_result)
die('Invalid query: ' . mysql_error());
if($download_result && mysql_num_rows($download_result) > 0)
{
$download_row = mysql_fetch_assoc($download_result);
$productid = $download_row['productid'];
$datecreated = $download_row['datecreated'];
$dateaccessed = $download_row['dateaccessed'];
$status = $download_row['status'];
if ($status == "active")
{
$download_updatestatus_query = "UPDATE `sales` SET `status`='inactive' WHERE `key`='$key'";
$download_updatestatus_result = mysql_query($download_updatestatus_query) or die (mysql_error());
echo "Go ahead and download file.";
}
else if ($status == "inactive")
{
echo "You may have downloaded this before.";
}
}
else
{
echo 'No results found';
}
}
else
{
echo "Sorry, no key provided.";
}