How to check if an order has been placed - php

I have a pretty simple thing going here. Basic query, but I threw a curve at myself when I decided to go one step further.
Basically it goes like this:
Check if the user entered a value in the form
If not, kick out and display a basic error
If they did then check that value against the database to make sure it is valid/exists
If it's valid/exists, set a session variable and go the order form
If not, kick out and display a basic error
What I want to do now is add another check in there, if the user id exists, then I need to check the order status, if they have already order then I want to kick out and Display a simple message letting them know they have already placed the order and it is being processed. If they have not already ordered then I want to proceed to the order form as above.
The database has a field called "ordered" which has a 1 if they have ordered and a 0 if they haven't ordered yet.
Here is my code that is working, I have tried several things but it keeps blowing up:
<?php
session_start();
$db_host = 'localhost';
$db_username = 'xxxxxx';
$db_password = 'xxxxxxxx';
$db_name = 'xxxxxxxx';
mysql_connect( $db_host, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_name);
if ($_SERVER['REQUEST_METHOD'] == "POST") {
/** Check whether the user has filled in the text field "employee_id" */
if ($_POST['employee_id'] == "") {
$IdIsEmpty = true;
}else{
$employee_id = $_POST['employee_id'];
if(mysql_num_rows(mysql_query("SELECT employee_id FROM TABLE_2 WHERE employee_id = '$employee_id'"))){
// if userid exists
$_SESSION['emp_id'] = $employee_id;
header('Location: orderform.php');
exit;
}
$IdNotFound = true;
}
}?>
<head>
</head>
<body>
<b>Please enter your Employee ID: </b><br><br>
<form class="" action="index.php" method="post" enctype=
"multipart/form-data" name="test_form" id="test" accept-charset=
"utf-8"><input type="text" name="employee_id">
<?php
/** Display error messages if "employee_id" field is empty or if ID does not exist */
if ($IdIsEmpty) {
echo ("<br>");
echo ("<b>Enter your employee ID, please!</b>");
echo ("<br>");
}?>
<?php
/** Display error messages if "employee_id" field is empty or if ID does not exist */
if ($IdNotFound) {
echo ("<br>");
echo ("<b>Your employee ID not found!</b>");
echo ("<br>");
}?>
<input type="submit" value="Submit">
</form>
</body>
</html>

Besides swapping out mysql_ functions for mysqli_ like Shivan suggested, you should do this:
Escape any input - you can never trust data provided by users, so do
$employee_id = mysql_real_escape_string($_POST['employee_id']);
In case it is a number, you could also do
$employee_id = intval($_POST['employee_id']);
Just keep this in mind whenever you use input.
Now for your problem:
Simply select your ordered field in the same query:
$order_qry = mysql_query("
SELECT employee_id, ordered
FROM TABLE_2 WHERE employee_id = '$employee_id'
");
if(mysql_num_rows($order_qry)) {
$order = mysql_fetch_object($order_qry);
if( ! $order->ordered) { // If not ordered
// ... do something
} else { // If already ordered
// ... tell the client
}
} else {
// No record found ... error message here
}

Related

Run two completely different sqli queries inside one script

I'm new to php.
I have this page:
<?php
function renderForm($id, $StaffFullName, $StaffJobPosition, $error)
{
?>
<!doctype html>
<html>
<head><title></title></head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div>'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p>ID: <?php echo $id; ?></p>
Name: * <input type="text" name="StaffFullName" value="<?php echo $StaffFullName; ?>"/><br/>
Job Position: * <select name="JobPosition">
<?php
$query = "SELECT * FROM LUT_JOBPOS";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
if ($StaffJobPosition == $row['JobposID'])
{
echo "<option value='{$row['JobposID']}' selected='selected'>{$row['JobposTitle']}</option>";
}
else {
echo "<option value='{$row['JobposID']}'>{$row['JobposTitle']}</option>";
}
}
$result->close();
?>
</select><br/>
<input type="submit" name="submit" value="Update">
<input type="button" onClick="parent.location='view.php'" value="Back">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
require_once('../../authenticate.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// do some funky stuff
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checking that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$query = "SELECT * FROM STAFF WHERE StaffID=$id";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$result->close();
// check that the 'id' matches up with a row in the database
if($row)
{
// get data
$StaffFullName = $row['StaffFullName'];
$StaffJobPosition = $row['StaffJobPosition'];
// show form
renderForm($id, $StaffFullName, $StaffJobPosition, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
So, what happens here is this:
When you open the page like edit.php?id=1, it fetches the data of the associated record from STAFF table and shows them on page for the user to edit them.
This part of the code works fine.
I also want the user to be able to select "Job Position" possible values from a drop down box. The drop down box should get its data from another table in database, LUT_JOBPOS.
This is the part of the code that doesn't work.
I was using mysql_query commands before on this page and it worked perfectly. However I was told to switch on mysqli_query instead.
Since I did the conversion I can't find how to run these two queries on the same script.
I messed a little bit with the require_once command and depending on where I call it I can run one query or another, but never both of them.
Looking at the logs of my web host the only thing I can see that may be relevant to my issue is:
"mod_fcgid: stderr: PHP Notice: Undefined variable: connection in /var/www/vhosts/myhostdomain.com/httpdocs/prod15/admin/staff/edit.php on line 24"
The connection variable comes from authenticate.php and it holds the connection parameters to the database. I'm sure it's set otherwise the first query (that gets the user data) wouldn't work.
I read somewhere that you can't run two sqli queries on the same script.
Then how I'm supposed to use a LUT table (lookup table)?
PS: I know that for showing the data I can use a UNION and that's what I do.
But when I edit the data I want the user to be able to select only from the possible values that exist on the LUT table (drop down select box)
Any help?
You have a lot of issues in your code. You really need to review it before use it in some real application, but for your specific problem, here is my guess.
You are calling the line $result = mysqli_query($connection, $query); in the line 24 and only after taht you call require_once('../../authenticate.php');.
As you said, the $connection var is defined in the authenticate.php, so in the line 24 is undefined.
Try to use require in the first line of your php script.

Making a column row that is empty from database table not appear in my quiz?

I'm trying to make it so that whenever there are empty cells in columns in my database table, they will not show up in my quiz application.
The way that the quiz is built up is that there are groups of four answers that share the same question ID (qid). When you press the next button you will get to see a set of four new questions and so on.
Right now there are empty spaces in quiz that are given a radiobutton on the side, How do I make it so that empty (answer) cells in my table column in mysql wont show up in my quiz?
My SQL table columns: qid(int), answers(varchar), points(int)
My code (PHP/HTML)
<html>
<head>
<meta charset="utf-8">
<script>
function goBack() {
window.history.go(-1);
}
</script>
</head>
<body>
<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) or die ("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
$qid = 1;
if(count($_POST) > 0){
$qid = intval($_POST['qid'])+1;
}
?>
<form method="post" action="">
<input type="hidden" name="qid" value="<?=$qid?>">
<?php
$sql1 = mysqli_query($connect,"SELECT * FROM question where answer IS NOT NULL && qid =".intval($qid));
while($row1=mysqli_fetch_assoc($sql1)){
?>
<input type='radio' name='answer1' value="<?php echo $row1['Point'];?>"><?php echo $row1['answer'];?><br>
<?php
}
?>
<button type="button" onclick="history.back();">Tillbaka</button>
<input type='submit' name='forward' value='Nästa'>
</form>
</body>
</html>
In your SQL you have excluded results where the answer is NULL.
Is this how you are storing an empty answer field in your db table; as NULL?
If so you should not get any results for where the field 'answer' is set to NULL.
Maybe you are storing a string instead of NULL. You can use this code to see what is returned from an empty answer cell:
if($row['answer'] == '')
{
echo "Answer is an empty string.";
}
else if(is_null($row['answer'])){
echo "Answer is NULL value.";
}
else if($row['answer'] == "NULL")
{
echo "Answer is the string 'NULL'.";
}
At least now, you will know what the empty answer field in your table are being stored as, and then you can go about removing them from your quiz.
You could also use your Database Management System (PHPMyAdmin) to check how data is being stored.
Hope this Helps

PHP: Display a form only if database value equals X

I have added a form into an admin panel with a yes (1) and no (0) option.
I have changed the Db so that on submit, the value gets added to the Db with the value "seller" 1 or 0, which works fine.
I have a form on my site. I only want it to display to a logged in person if they have a value in the Db of "1" for seller. If they have a value of 0 I want to print a message.
I am guessing I need to query the database, then construct a function and apply it in the page where the form code is to display it if the condition of "1" is met?
I have tried searching but cannot grasp how I can construct it.
<?php
// insert your DB Data
$user = "";
$pass = "";
$host = "";
$dbdb = "";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
mysqli_set_charset($connect, 'utf8');
$query = mysqli_query($connect, "SELECT `seller` FROM `nameTable` WHERE `user` = 'userName'");
$record = mysqli_fetch_array($query);
if($record['seller'] == 1){
echo "Seller is 1";
}else{
echo "Seller is 0";
}
?>
I am using if else condition for my solution here:
<?php
$userLoggedIn = $_SESSION['userName'];//session created while login is stored in variable
//Search table `tbl` for field `SELLER` where field `user` matches with loggedin user
$searchSeller = mysql_query("SELECT `SELLER` from `tbl` WHERE `user`='$userLoggedIn'");
$searchSellerArray = mysql_fetch_array($searchSeller);
//Setting variable to be used in css depending on value in table
if($searchSellerArray['seller']==1){
$displayForm="block";//displays form
$displayMessage="none";//hides message
}
elseif ($searchSellerArray['seller']==0){
$displayForm="none";//hides form
$displayMessage="block";//displays message
}
?>
<form style="display:<?php echo $displayForm;?>;">
//Form content goes here...
</form>
<p style="display:<?php echo $displayMessage;?>;">
//Message content goes here
</p>

PHP help: Follow System in Microblogging

I'm making a site similar to Instagram. I am very new to php. I created a follow button in the user's profile.
How do you make the follow button disappear when you already followed the user?
How do you replace it with unfollow button?
// my php code for following
if (isset($_POST['addfriend'])){
$fromuser = $user;
$touser = $username;
if($fromuser == $username){
$Msg = "You cannot follow yourself<br/>";
}
else
{
$getID= mysql_query("SELECT userID FROM user WHERE username='$user'");
$get_ID_row = mysql_fetch_assoc($getID);
$ID_db = $get_ID_row['userID'];
$sql = "insert into following (userID, fromUser, toUser)
values ('$ID_db','$fromuser', '$touser')";
$result = mysql_query($sql);
$Msg= "Success! <br/>";
}
}
else{
//Do nothing
}
//my code for the follow button
<form action="<?php $user;?>" method ="POST">
<?php echo $Msg; ?>
<input type = "submit" name ="addfriend" value = "Follow"/>
</form>
On the page where you are going to show the Follow or Unfollow button, first run a MySQL query to find out if you are already following the person:
$sql = "select * from following
where userID = $user
and fromUser = $fromUser
and toUser = $toUser";
$result = mysql_query($sql);
if( $result) {
if( mysql_num_rows($result) > 0) {
// if we get here we know we are already following that person
....[see below]
Now dynamically create whichever button you need:-
if( mysql_num_rows($result) > 0) {
// if we get here we know we are already following that person
echo '<input type = "submit" name ="removefriend" value = "Un-follow"/>';
}
else
{
echo '<input type = "submit" name ="addfriend" value = "Follow"/>';
}
And on the following page where you are getting the form results, check for both buttons:
if (isset($_POST['addfriend'])) {
...[do what you already have]
}
else
if (isset($_POST['removefriend'])) {
...[do SQL to remove the record from the following table]
}
Please be aware also that as of PHP v5.5 this style of MySQL is deprecated. At some stage in the future you will have to convert your programs to the MySQLi or PDO_MySQL extensions, before they eventually discontinue support. See the PHP manual about this at eg http://php.net/manual/en/mysqlinfo.api.choosing.php.
Would be easier with OO PHP. However, if you chose procedural, let's assume we have a table of friends. Which keeps the id of each of my friends.
e.g.: Smith follows John
Then you do something like
$following = mysql_query("SELECT COUNT(*) FROM followers WHERE followerid = ".$_SESSION['id']." AND followeeid = ".$username);
Check if You follow the person already:
if($following){//$following == true
}

submit one or another query

I'm continuing to hack away at my newbie php/mySQL 'Invoicer' app.
I now have a form page in which I want to run one of two queries - either an INSERT or an UPDATE, depending on whether an ID is present. When present,
the ID is used to retrieve the record and pre-populate the form accordingly, which I have working. My problem now is that my conditional bits are
obviously not right because in either case when submitting the form the INSERT query is run, can't get the UPDATE to run, and I've exhausted my
understanding (and guess-ology).
I'd love to know why this ain't working, even if it's not the best approach, and I'm definitely open to suggestions to move the queries to a process.php,
etc. I'm also wondering if I should use 'if(isset($_GET['ID'])' to simply include one block or the other.
Many thanks in advance for any help or suggestions. (p.s. my intention is to overhaul for best practices/security once I've got the broad strokes wired up)
cheers, s
<?php
// CASE I: 'EDIT RECORD':
// If there's an ID ...
if (isset($_GET['ID']) && is_numeric($_GET['ID'])) {
$id = $_GET['ID'];
echo "<p class=\"status\"><strong>ID IS SET ... ergo we're editing/UPDATING an existing record</strong></p>";
// ... retrieve the record ....
$query = sprintf("SELECT * FROM Invoices WHERE ID = %s", $id);
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
// ... assign variables to pre-populate the form
$id = $row['ID'];
$invNumber = $row['invNumber'];
$invDate = $row['invDate'];
// [ snip: more variables > field data ]
// on submit: get the form values ...
// no worky: if (isset($_GET['ID']) && isset($_POST['submit'])) {
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
// ... and UPDATE the db:
$qUpdate = "UPDATE Invoices SET invNumber='$invNumber', invDate='$invDate', projNumber='$projNumber', client='$client', task='$task', issueDate='$issueDate', subTotal='$subTotal', tax='$tax', invTotal='$invTotal', datePaid1='$datePaid1', datePaid2='$datePaid2', comments='$comments' WHERE ID='3'";
$result = mysql_query($qUpdate) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: RECORD UPDATED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE I: ID present
// CASE II: 'NEW RECORD'; query = INSERT
elseif (empty($_GET['ID'])) {
echo "<p class=\"status\"><strong>No ID ... ergo we're INSERTING a new record:</strong></p>";
// on submit: get the form values ...
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
$qInsert = "INSERT INTO Invoices (invNumber,invDate,projNumber,client,task,issueDate,subTotal,tax,invTotal,datePaid1,datePaid2,comments)
VALUES('$invNumber','$invDate','$projNumber','$client','$task','$issueDate','$subTotal','$tax','$invTotal','$datePaid1','$datePaid2','$comments')";
$result = mysql_query($qInsert) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: NEW RECORD INSERTED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE II: No ID present
?>
and:
<form id="invoiceData" method="post" action="/html/form.php">
When you submit the form, you need to include the ID again, otherwise it is silently dropped off since you are posting to the hard-coded value /html/form.php (with ID removed). This will cause the empty($_GET['ID']) part to match and run, causing the INSERT. You can simply include the ID value back into the action of every form post like this:
<form
id="invoiceData"
method="post"
action="/html/form.php?ID=<?php echo $_GET['ID']; ?>"
>
This should work in both the cases of the UPDATE and the INSERT, because if there was no ID to begin with, this will render as /html/form.php?ID=, which will match the case of ID being empty, I believe. You may want to test this logic out for sure.
Hope this helps!
$_GET[ID] will be set if you pass it as a URL parameter. So if you change your <form> action to
<form id="invoiceData" method="post" action="/html/form.php?ID=12">
Where 12 is whatever ID you want, you should be getting the results you're wanting -- as long as you do have a <input type="hidden" name="submit" value="1" /> (value can be whatever) in your form somewhere as well.

Categories