PHP/mySQLi update values where user exists - php

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

Related

MySQL matching and non-matching combinations

I'm trying to create conditional statements for license validating. I have 3 parameters purchase code, item id and website URL. I want to check if they together or partially matches data in my database rows and insert if it does not exist. So I have to create SQL query or queries to do this, but I couldn't figure out what is the cleanest/efficient way. Look at the code itself and you will understand what I'm trying to do.
<?php
if (isset($_GET['purchasecode']) && isset($_GET['itemid']) && isset($_GET['website'])) {
$purchasecode = $mysqli->real_escape_string($_GET['purchasecode']);
$website = $mysqli->real_escape_string($_GET['website']);
$itemid = $mysqli->real_escape_string($_GET['itemid']);
require_once 'class-verify.php';
$access_token = 'MyAccessTokenHere';
$purchase = new EnvatoPurchaseCodeVerifier($access_token);
$verified = $purchase->verified($purchasecode);
// Verified that user have purchased one of our items
if ($verified) {
$item_id = $verified->item->id;
$item_name = $verified->item->name;
$buyer = $verified->buyer;
$license = $verified->license;
$amount = $verified->amount;
$sold_at = $verified->sold_at;
$supported_until = $verified->supported_until;
$query = $mysqli->query("SELECT * FROM PurchaseCodes WHERE Code='".$purchasecode."' AND ItemID='".$item_id ."' AND Website='".$website."'");
if (/* puchase code, item id and website URL exist/matches */) {
echo 'License is already active!';
} elseif (/* puchase code and item id matches but website URL is different */) {
echo 'License is already actived on another website!';
} elseif ($item_id != $itemid) {
echo 'This purchase code is for our another item';
}else {
// insert into database if not already exists
$mysqli->query("INSERT IGNORE INTO PurchaseCodes (Code, ItemID, Website) VALUES ('$purchasecode', '$item_id', '$website')");
echo 'License is successfully activated!';
}
} else {
echo 'Purchase code is invalid!';
}
}
?>
Maybe smt like this would help:
$valid_license_sql = "SELECT
CASE WHEN Code='".$purchasecode."' THEN 1 ELSE 0 END as purchasecode,
CASE WHEN ItemID='".$item_id ."' THEN 1 ELSE 0 END as itemid,
CASE WHEN Website='".$website."' THEN 1 ELSE 0 END as website,
CASE WHEN Code='".$purchasecode."' AND ItemID='".$item_id ."' AND Website='".$website."' THEN 1 ELSE 0 END as license
FROM PurchaseCodes";
$query = $mysqli->query($valid_license_sql);
$proper= $query->fetch_assoc();
if ( $proper['license'] ) {
echo 'License is already active!';
} elseif ( $proper['purchasecode'] && $proper['itemid'] && !proper['website']) {
echo 'License is already actived on another website!';
} elseif ( !$proper['itemid'] ) {
echo 'This purchase code is for our another item';
}else {
// insert into database if not already exists
$mysqli->query("INSERT IGNORE INTO PurchaseCodes (Code, ItemID, Website) VALUES ('$purchasecode', '$item_id', '$website')");
echo 'License is successfully activated!';
}
If you have more rows at table simply loop through result set.

Data Not inserting into table PHP

The data is not inserting into another table, here's the code below :
if (isset($_POST))
{
$job = $_POST['jobtitle'];
$dur = $_POST['duration'];
$deg = $_POST['requireddegree'];
$exp = $_POST['experiance'];
$sal = $_POST['salary'];
$mark = $_POST['marks'];
if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
{
$dur = mysql_real_escape_string($dur);
$deg= mysql_real_escape_string($deg);
$exp = mysql_real_escape_string($exp);
$sal = mysql_real_escape_string($sal);
$mark = mysql_real_escape_string($mark);
$job = mysql_real_escape_string($job);
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.
However, i have written the same logic while inserting data in my another table and it inserts successfully.But there I put '$dur'.
I can't find the problem.Will be glad for your suggestions :)
I can't seem to find any other error by seeing this code expect for
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";
//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.
// Adding this always helps
if(!mysqli_query($con,$query))
{
die('error'.mysqli_error($con));
}
// in $con = $con=mysqli_connect("localhost","root","");
else
{
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.

PHP If statement returning early(amateur)

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

No results returned for elseif PHP query

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.";
}

Help on how to continue with code that verifies a registered user and updates mySQL

When a user registers, the script sends an email to verify his account. Clicking on the link, the script gets the token
$token = mysql_real_escape_string($_GET["token"]);
and what I thought to do is
if($token != '') {
mysql_query("UPDATE members SET verified = '' WHERE verified = '$token'");
}
or
if($token != '') {
$result = mysql_query("UPDATE members SET verified = '' WHERE verified = '$token'");
if($result) { }
else { }
}
What is my purpose is to echo a success or failed message on the user. When it will be success then the verified will be empty.
What is the appropriate way of doing this with my examples above?
Should I check if there is the token in the DB before updating it?
Thank you.
Your current method updates a record if it exists but does not take into account that which does not exist or match. You should run something similar to:
if($token != '') {
$result = mysql_query("SELECT COUNT(*) FROM members WHERE verified = '$token'");
while($row = mysql_fetch_row($result)) {
$records = $row[0];
}
if($records == 0) { echo 'no results'; }
elseif($records ==1) { echo 'you matched'; then update the record. }
}
edit
changed BACK to the while loop, wasn't thinking of the count returning 0 rows

Categories