MySQL matching and non-matching combinations - php

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.

Related

Update a mysql table with session generated information

I'm currently doing a Web Programming module at university and have been having trouble with some of the homework set. We are meant to insert code that updates our current mysql table with new information (gender, age, email, comment). This information needs to be inserted into the row of each persons session generated ID (currID). How do we code for the updated information to be inserted into a session-specific row?
<?php
session_start();
include('muqHeader.html');
include('commonSrc.php');
include('../shareCode/mysqlLink.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST'):
// update the mf record
if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)){
}else{
echo "Not a valid email address";
}
if(filter_var($_POST['comment'], FILTER_SANITIZE_STRING)){
}else{
echo "Text includes invalid characters";
}
$gender = $_POST['gender'];
$age = $_POST['age'];
$email = $_POST['email'];
$comment = $_POST['comment'];
$currID = $_SESSION['currID'];
if ($_POST['submit']){
$sql = "UPDATE muq
SET (gender='$gender', age = '$age', email = '$email', comment = '$comment')
WHERE (muqID = '$currID')";
}
if (#mysqli_query($link, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . #mysqli_error($link);
}
else:
$useTime = implode(',', $_SESSION['useTime'] );
$usedM = implode( ',', $_SESSION['usedM'] );
$tmp = array();
for($i=0; $i < count($_SESSION['freqRate']); $i++) {
$tmp[$i] = implode( '', $_SESSION['freqRate'][$i] ); // empty string as 'glue'
}
$freqRate = implode( ',', $tmp );
$dateTime = $_SESSION['dateTime'];
$taskTime = (time() - $_SESSION['startTime']) / 60; //in minutes
$sql = "INSERT INTO muq
(dateTime, taskTime, useTime, usedM, freqRate)
VALUES ('$dateTime', '$taskTime', '$useTime', '$usedM', 'freqRate')";
$link = connectDB();
#mysqli_query( $link, $sql );
$_SESSION['currID'] = #mysqli_insert_id($link);
#mysqli_close($link);
?>
Well, before answearing your question, here is some coding rules you need to respect:
1- You don't have to use more lines than what you need. This means you don't have to do an an empty "if" using 4 lines if you can do it in 2 lines.
Example:
Instead of:
if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)){
}else{
echo "Not a valid email address";
}
You can do:
if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
echo "Not a valid email address";
Second thing, to update a row in a database, you need an ID. This the key you are going to use to tell your db engine which row you are going to update because if not "he" will not know which row "he" should update (I'm considering the db engine as a person like me and you :D )
So, you need to inject that key (account ID or whatever) in your session so that you can use later when updating your database by telling you db engine that "he" needs to update that row identified by that key.

PHP/mySQLi update values where user exists

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

create two DB updates and one insert with one button

I have been fighting with this. Hope this helps others as well. I have a page for an invoice display, it populates and displays perfectly, I want to do major DB changes with the "Pay" button.
If there is an OrderIn_id, it should update the order_instate column of paid to "Yes", or if there is an OrderOut_id it should update the order_outstate column of paid to "Yes", there can be an instance where there is one or the other Id's or could have both. Then it inserts values into an invoice table.
The insert works perfectly, I am not getting any error messages, and it goes to the next page as if it all works, but it does NOT update the order tables to paid = "Yes", it keeps the field the same. Can you advise me of what I may not be seeing in this code. This is the php code that is called when the submit button is pressed.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($row['orderIn_id'])) {
$orderIn_id = $row['orderIn_id'];
$ip_id = $row['ip_id'];
$orderIn_quantity = $row['orderIn_quantity'];
$orderIn_total = $row['orderIn_total'];
$orderIn_paid = "Yes";
$changeVal="UPDATE order_instate
SET user_id = '$user_id', ip_id = '$ip_id', orderIn_quantity = '$orderIn_quantity', orderIn_total = '$orderIn_total',
orderIn_paid = '$orderIn_paid'
WHERE orderIn_id = '$orderIn_id'; " ;
$changeCheck=mysqli_query($dbhandle, $changeVal)
or die(mysqli_error($dbhandle));
}
if (mysqli_affected_rows($dbhandle) == 1) {
echo "<span class = 'errorlog'><br />The Order update was successful.<br /></span>";
}
if(isset($row2['orderOut_id'])) {
$orderOut_id = $row2['orderOut_id'];
$op_id = $row2['op_id'];
$orderOut_quantity = $row2['orderOut_quantity'];
$orderOut_total = $row2['orderOut_total'];
$orderOut_paid = "Yes";
$changeVals="UPDATE order_outstate
SET user_id = '$user_id', op_id = '$op_id', orderOut_quantity = '$orderOut_quantity', orderOut_total = '$orderOut_total',
orderOut_paid = '$orderOut_paid'
WHERE orderOut_id = '$orderOut_id'; " ;
$changeCheck2=mysqli_query($dbhandle, $changeVals)
or die(mysqli_error($dbhandle));
}
if (mysqli_affected_rows($dbhandle) == 1) {
echo "<span class = 'errorlog'><br />The Order update for out of state was successful. <br /></span>";
}
$invoice_total = 0;
$invoice_total = $gtotal;
$invoice_shipped = "No";
$add ="INSERT INTO invoice(user_id, invoice_total, invoice_shipped)
VALUES ('$user_id', '$invoice_total', '$invoice_shipped')";
$addCheck=mysqli_query($dbhandle, $add)
or die(mysqli_error($dbhandle));
if($addCheck == NULL){
echo "<span class = 'errorlog'><br />Your Payment was not successful. Please try again. <br /></span>";
} else {
header("location: userOrders.php");
}
}
?>

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

how to prevent same record to be inserted twice in mysql using php

The following is my code that I have written for not inserting same data
I would like if the record exist in mysql then it should show me error message that the record already exist the else part should insert record to database but it not working
can any one help me plz
the help would be highly appreciated
function addcontact()
{
if(isset($_POST['addContact']))
{
$officeName = strip_tags($_POST['office_name']);
$contactName = strip_tags($_POST['contactName']);
$contactNo = strip_tags($_POST['contactNo']);
$digitalNo = strip_tags($_POST['digitalNo']);
$mobileNo = strip_tags($_POST['mobileNo']);
$check="SELECT * FROM contacts WHERE office_name = '$officeName'";
if(mysql_num_rows($check) != 0)
{
echo "Already in Exists<br/>";
}else
{
$sql = mysql_query("INSERT INTO contacts (office_name, contact_no,
digital_no, mobile_no) VALUES
('$contactName','$contactNo','$digitalNo','$mobileNo')") or die(mysql_error());
if($sql)
{
header("Location: index.php?admin&done"); exit;
}
else
{
header("Location: index.php?admin&failed"); exit;
}
}
}
}
you did mistake here.
$check="SELECT * FROM contacts WHERE office_name = '$officeName'";
if(mysql_num_rows($check) != 0)
{
echo "Already in Exists<br/>";
}
just add mysql_query like
$check=mysql_query("SELECT * FROM contacts WHERE office_name = '$officeName'");
if(mysql_num_rows($check) != 0)
{
echo "Already in Exists<br/>";
}
or you can also use like
$name=$_POST['username'];
$q="select * from login where name='$name' ";
$rs=mysql_query($q);
if(mysql_fetch_row($rs)>0)
{
echo "already exist";
}
else
{
$msg="done";
}
Add the ON Duplicate KEY Update. This way you don't need to check if the record already exists, which means you don't need an extra select query just to check. If it exists, nothing happens.
INSERT INTO contacts (office_name, contact_no, digital_no, mobile_no)
VALUES ('$contactName','$contactNo','$digitalNo','$mobileNo')
ON DUPLICATE KEY UPDATE office_name = office_name
And set the office_name to be the primary key or a unique index.
There is missing one step, your first query is not executed, please try this:-
function addcontact()
{
if(isset($_POST['addContact']))
{
$officeName = strip_tags($_POST['office_name']);
$contactName = strip_tags($_POST['contactName']);
$contactNo = strip_tags($_POST['contactNo']);
$digitalNo = strip_tags($_POST['digitalNo']);
$mobileNo = strip_tags($_POST['mobileNo']);
$check= mysql_query("SELECT * FROM contacts WHERE office_name = '{$officeName}'");
if(mysql_num_rows($check) != 0)
{
echo "Already in Exists<br/>";
}else
{
$sql = mysql_query("INSERT INTO contacts (office_name, contact_no,
digital_no, mobile_no) VALUES
('$contactName','$contactNo','$digitalNo','$mobileNo')") or die(mysql_error());
if($sql)
{
header("Location: index.php?admin&done"); exit;
}
else
{
header("Location: index.php?admin&failed"); exit;
}
}
}
}
you can handle it from database side. write a stored procedure such a way that first check weather the record is in database or not if exist then ignore it and get back the text "Record already exist", if not exist then insert it to table. use conditional statements in mysql.

Categories