seat reservation not working - php

I've been doing a lot of research but I guess I still didn't find the answers. This is a seat reservation and I'm not so good in php and mysql. So here's my code:
reservation.php code:
<?php
mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db('seat_reservation') or die (mysql_error());
$insert = mysql_query("INSERT INTO reservation (chair_status, room_id, chair_number) VALUES (0, 400, 05)");
?>
</td>
<div id="popupContact">
<a id="popupContactClose">x</a>
<center><form method = "POST" action="reserve.php">
<?php
$query = mysql_query("SELECT chair_status FROM reservation WHERE room_id = '400' AND chair_number = '05'");
while($row = mysql_fetch_array($query)) {
$_SESSION['roomno'] = $row['room_id'];
$_SESSION['chairnum'] = $row['chair_number'];
}
?>
reserve.php code:
<?php
$name = $_POST['student_name'];
$stud_id = $_POST['stud_id'];
$room_id = $_SESSION['roomno'];
$chair_num = $_SESSION['chairnum'];
mysql_connect("localhost", "root", "") or die (mysql_error());
mysql_select_db('seat_reservation') or die (mysql_error());
$query = mysql_query("SELECT chair_status FROM reservation WHERE room_id = '$room_id' AND chair_number = '$chair_num'");
if($query == 0)
{
$insert = mysql_query("UPDATE reservation SET chair_status = 1, student_name = '$name', stud_id = '$stud_id' WHERE room_id = '$room_id' AND chair_number = '$chair_num'");
}
else
die ("Sorry, seat taken! <br />Redirecting...<meta http-equiv='refresh' content=2;reservation.php>");
?>
my problem is that, when I reserve a seat, it tells me that the seat is taken even if the chair_status field is 0. When I checked the DB, it successfully inserted with chair_status of 0. I don't know which part is wrong. I really need your help, thank you!

In reservation.php, you SELECT only chair_status but then try to access $row['room_id'] and $row['chair_number']: neither are in the resultset. However, both are already known since they were fixed in the WHERE clause of the query, therefore one could use those values without resorting to the MySQL query.
Even if you wanted to use such a query to set the $_SESSION variables, it is daft to loop over the resultset overridding those variables with each result. Better to LIMIT the query and use only one resulting record.
However, you probably wanted to output form elements rather than set $_SESSION variables in order that the user can then choose which of the available seats they wish to reserve? In which case, you probably meant to include chair_status = 0 in your filter criteria.
The return value of the mysql_query function is a resource identifier; comparing this against 0 in reserve.php is probably not what you had intended. Perhaps you wanted mysql_num_rows instead?
Please stop writing new code with the ancient MySQL extension: it is no longer maintained and the community has begun the deprecation process. Instead you should use either the improved MySQLi extension or the PDO abstraction layer.
Please avoid putting variables (and especially those which come from your user) into your SQL, which makes you vulnerable to SQL injection. You should instead use prepared statements, with which your variables can be passed to MySQL as parameters that do not get evaluated for SQL. Read about Bobby Tables for more information.

You probably mean if (mysql_num_rows($query) == 0) {. The way it is your are checking if there is an error with the query, not the number of rows returned. Check the docs for more information.
Also, this might be optional, but use braces to enclose your else statement. And it might be better to use mysqli instead of mysql_... functions as mentioned in your comments. Or just escape the user input before adding it to the query string.

use mysql_num_rows for checking if records exist..
$query = mysql_query("SELECT chair_status FROM reservation WHERE room_id = '$room_id' AND chair_number = '$chair_num'");
$rows = mysql_num_rows($query);
if($rows == 0)
{
$insert = mysql_query("UPDATE reservation SET chair_status = 1, student_name = '$name', stud_id = '$stud_id' WHERE room_id = '$room_id' AND chair_number = '$chair_num'");
}

Related

If Else Statement Not Working - PHP

I'm making a simple auction website and I'm trying to keep the user from bidding on an item if they are already the highest bidder. At the moment, however, my code still allows the highest bidder to continue bidding and I get an error saying that mysql_fetch_array() expects paramater 1 to be resource.
Any idea where I'm going wrong? Here is my code:
<html>
<head></head>
<body>
<?php
session_start();
require_once("dbconnect.inc");
$accountid=$_SESSION['accountid'];
$itemid=$_POST['itemid'];
$result = mysql_query("SELECT accountid FROM bidhistory
WHERE biditem = '$itemid' ORDER BY bidhistoryid DESC");
while($row = mysql_fetch_array($result)){ //
$checkaccountid = $row['accountid'];
if($checkaccountid == $accountid){ /* THEN COMPARE IT WITH THE CURRENT USER */
echo "You are the highest bidder!";
}
else { // they can still bid
$sql="INSERT INTO bidhistory (accountid, biditemid)
VALUES ($accountid, $itemid)";
mysql_query("
UPDATE bidhistory
SET bidprice = bidprice + 1
WHERE biditemid = " .
#mysql_escape_string($itemid));
$result=mysql_query($sql) or die("Error in adding bid for item: ".mysql_error());
}
}
echo "Bid accepted!";
?>
<p>Back to auction</p>
</body>
</html>
Your query is incorrect for your first select.
biditem =
should be
biditemid
$result = mysql_query("SELECT accountid FROM bidhistory
WHERE biditemid = '$itemid' ORDER BY bidhistoryid DESC");
You also are open to SQL injections with this code. User input and SQL queries should be separated. To do this use prepared statements. The mysql_ functions don't have support for this and are outdated. You should switch DB drivers either the PDO or mysqli should suffice.
One approach you could take is casting the itemid to an int (presuming it is an int).
$itemid= (int)$_POST['itemid'];
Then
$result = mysql_query("SELECT accountid FROM bidhistory
WHERE biditemid = $itemid ORDER BY bidhistoryid DESC");
Additional information on injection prevention.
How can I prevent SQL injection in PHP?
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
An example using PDO and the query parameterized (http://php.net/manual/en/pdo.prepared-statements.php).
$parameterize = $dbh->prepare('SELECT accountid FROM bidhistory
WHERE biditemid = ? ORDER BY bidhistoryid DESC');
$parameterize->execute(array($itemid));
The ? here is a placeholder for the user provided value.
You need to check to confirm that $result contains a successful query result. If it failed it will be 'false' and your request to fetch the data will fail as reported.
From PHP documentation:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on
error.
Check your SQL query. There may be an error, or no matching data were found on the database.
Also, mysql_query is deprecated as of PHP 5.5.0, and will be removed in the future. You should start thinking about using mysqli_query or PDO.
The problem is not in if and else statement but in the query. If you see this error ("mysql_fetch_array() expects parameter 1") directly think about your query.
Before my answer I advise you to use mysqli not mysql, your query should be like this:
$query="SELECT 'accountid' FROM `bidhistory`
WHERE 'biditem' = '".$itemid."' ORDER BY 'bidhistoryid' DESC"

mysql_num_rows() is not returning properly value

After a search here I couldn't see anyone with the same (strange) problem as me.
I have a very simple task which is to check whether some name already exists on a table, but the thing is the mysql_num_rows is returning wrong values.
I'm sorry, I forgot to mention that this only happens when I try to look for words with special chars. Bebês, Câmeras, Calção are examples.
$sql = "
SELECT cattitle as category
FROM categories
WHERE cattitle = '$title'
";
$res = mysql_query($sql, $con) or die(mysql_error());
$num = mysql_num_rows($res);
I even have tried with mysql_result
$sql = "
SELECT count(cattitle) as category
FROM categories
WHERE cattitle = '$title'
";
$res = mysql_query($sql, $con) or die(mysql_error());
$num = mysql_result($res,0);
The worst thing is, when I run the query directly, I get the correct results ($num > 0).
I'm not that experienced programmer and, at first, I thought it was returning values from other queries, but I've checked and changed the name of those vars and the problem persisted.
Could be some kind of conflict? Can someone help me with this error?
Kind regards,
Your example is basic one, and it should work. It is even in PHP manual as example.
Try this way:
$sql = "
SELECT cattitle
FROM categories
WHERE cattitle = '$title'
LIMIT 1
";
$res = mysql_query($sql, $con) or die(mysql_error());
if ($row = mysql_fetch_assoc($res)) {
# category already exists, do smth?
}
I think your problem may be in wrong charsets for your mysql database and for string in your PHP script.
When you use mysql console then it convert symbols in correct charset.
Check charset and collate for your table and field cattitle.
Best solution will change it to UTF8
Also use UTF8 when write your script

How to INSERT in one table and UPDATE in another in single QUERY?

I'm currently creating some sort of inventory system.
I have master_tbl where in I save the items. In master_tbl, I have column qty_left or the available stock left.
I also have the table issuance_tbl where in I save all the transaction in issuing items.
In this table there is issued_qty.
My problem is how can I INSERT a row into issuance_tbl at the same time UPDATE the master_tbl.qty_left. (master_tbl.qty_left - issuance_tbl.issued_qty).
Is it possible?
I think the best way is using Stored Procedure. You can have bunch of SQL statements with error handling and ACID transactions in one place. This is because if your first query executes and the second fails, you may need to rollback transactions. Stored procedures allow all this fancy but reliable stuff.
You can start here: http://forums.mysql.com/read.php?98,358569
I'm not completely confident that 'If there's any way to do such thing':
You need to do it in steps, LIKE THIS:
$result = $this->db->insert($table);//Example function to insert inventory item
$insert_id = $this->db->insert_id();//Example function to get the id of inserted item
if($result)
$res = $this->db->update($id,$data,$table);//Example function to update data of quantity table
if(!$res)
{
$this->db->delete($insert_id,$table);s
$result = '-1';
}
return $result;
Hope this might help
here is the example:
<form method="post">
QTY:<input type="text" name="qty_left"></input>
<input type="submit" name="submit" value="update"></form>
<?php
////////your config db
$qty = $_POST['qty_left'];
if(isset($_POST['submit']);
$sql = mysql_query("insert into issuance_tbl (issued_qty) values (".$qty.") ");
$sql1 = mysql_query("update master_table set qty_left= ".$qty."");
?>
$con = mysqli_connect($host, $user, $password, $database);
...
$issued_qty = '10'; //some value
$insert_query = "insert into issuance_table (issued_qty, ...) values ('$issued_qty', ... ) ;";
$update_query = "update master_tbl set qty_left = (qty_left - ".$issued_qty.") where ....";
mysqli_multi_query($con, $insert_query.$update_query);

php query-loop does not work

I have this code:
public function updateOrder($num, $ufood, $uquan) {
$response = array();
mysql_query("SET NAMES 'utf8'");
foreach ($ufood as $index => $f) {
$result = mysql_query("SELECT food, quantity, uquantity FROM table1 WHERE food ='".$f."'") or die(mysql_error());
$no_of_rows = mysql_num_rows($result);
$response['number rows'] = $no_of_rows;
if ($no_of_rows>0) {
while ($row = mysqli_fetch_array($result)); {
if (!$row['uquantity']) {
$w = "INSERT INTO table1(uquantity) VALUES ('$uquan[$index]')";
mysql_query($w);
$e = (int)$row['quantity'];
$q = (int)$uquan[$index];
$sum = $e+$q;
$s = (string)$sum;
$d = "UPDATE table1 SET quantity = '$s' WHERE food = ".$row['$food']." ";
mysql_query($d);
} else if($row['uquantity']) {
$c = (int)$row['uquantity'];
$q = (int)$uquan[$index];
$sumq = $c+$q;
$sq = (string)$sumq;
$d = "UPDATE table1 SET uquantity = '$sq' WHERE food = ".$row['$food']." ";
}
}
} else {
$string ="INSERT INTO table1(food,uquantity) VALUES ('".$f."','".$uquan[$index]."')";
$z = mysql_query($string);
}
}
}
Well i can not make this work, and i am trying all kinds of things put still it doesn't work.
So i have some questions:
Is this structure of foreach and while valid?
Though the $result query returns some rows from the database, when i try to use $row['quantity'], as a value, i get null.
In this code i receive some data from an android app, and i try to "see", if there are already entries for the type food of my db_table(table1). If there are entries i want the db to sum the quantity entry of the android sent, data with the one that are inside my db, and update the field. This is the basically it. But as i said when i try to use the data that comes from the database, i get null values.
Please if someone could give me some hint, cause I'm really stuck..
There are many problems with your code. I'm marking this answer as Community Wiki, and I invite others to edit and add things as they find them.
You may also consider posting to https://codereview.stackexchange.com/ instead, when you have so many mistakes, until you have a more specific question.
Bad variable interpolation
This line won't do what you want it to:
$w = "INSERT INTO table1(uquantity) VALUES ('$uquan[$index]')";
This is not quite valid PHP syntax. You can either concatenate expressions:
$w = "INSERT INTO table1(uquantity) VALUES ('".$uquan[$index]."')";
Or you can embed expressions in curly braces:
$w = "INSERT INTO table1(uquantity) VALUES ('{$uquan[$index]}')";
Or you can use a query parameter placeholder:
$w = "INSERT INTO table1(uquantity) VALUES (?)";
$stmt = mysqli_prepare($w) or die(mysqli_error());
$uqi = $uquan[$index];
mysqli_stmt_bind_param($stmt, "i", $uqi);
mysqli_stmt_execute($stmt);
Mixing MySQL APIs
You can't mix mysql_query() with mysqli_fetch_array(). PHP has more than one API for MySQL, and you can't mix them. You should standardize on using the mysqli API, because the older mysql API is now deprecated.
Semicolon defeats while loop
The semicolon after the while statement makes the loop a no-op, and when it terminates, the $row contains nothing.
while ($row = mysqli_fetch_array($result)); {
Should be:
while ($row = mysqli_fetch_array($result)) {
Using variables inappropriately
Referencing a $row key with a single-quoted variable is probably not what you mean, in multiple ways:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = ".$row['$food']." ";
The column name in the select-list of your earlier SELECT query is 'food', not '$food'.
Also, even if you meant to use a variable name $food as the key, putting it in single quotes would not use the value of the variable, it would be the literal string '$food'.
Failure to quote string literal?
Furthermore, you use a quoted literal for comparing to the food column in your SELECT query, which makes me think it might be a string.
So the UPDATE should be something like:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = '".$row['food']."' ";
Or:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = " . intval($row['food']);
Or preferably use parameters and a prepared query, then you don't need to worry about quotes or types:
$d = "UPDATE table1 SET quantity = ? WHERE food = ?";
. . .
Failure to check for errors
Every query might fail, either because you have a syntax error (e.g. a string without quoting), or because the table doesn't have a column by the name you reference, or privileges issues, etc.
Always check the return status of the query function when you run a SQL query. The function returns false if there's an error, and if that happens you must check the error message.
mysqli_query($mysqli, $d) or trigger_error(mysqli_error($mysqli), E_USER_ERROR);
Failure to execute the UPDATE
Your second update assigns a SQL query string to the variable $d, but then does not execute that update query at all!

mysql_query(INSERT ...) function not working in my code

I've create database, which basically accept name and Id and answer string of
length 47,and my php code will grade the incoming results against the answer key I provided and number containing the count of correct answers will stored in database. this is information of my database.
database name is marking
and table called 'answer', which has 5 fields as follow
1) answer_id :int , not null, auto increament.
2) name: text
3)id : text
4)answers : text
5)correct : int
my question and problem is the function is working
// setup query
$q = mysql_query("INSERT INTO `answer` VALUES
(NULL,'$name', '$id','$answers','$correct')");
// run query
$result = mysql_query($q);
or in another way , nothing storing in my database ???
Thanks in advance.
this is the whole program.
<?php
error_reporting(E_ALL ^ E_STRICT);
// to turn error reporting off
error_reporting(0);
$name =$_POST['name'];
$id = $_POST['id'];
$answers = $_POST['answers'];
// check the length of string
if(strlen($answers) !=10)
{
print'your answer string must be 10';
return;
}
mysql_connect("localhost","root","");
mysql_select_db("marking");
$name = addslashes($name);
$id = addslashes($id);
$answers = addslashes($answers);
$answer_key = "abcfdbbjca";
$correct = 0;
for($i=0;$i<strlen($answer_key);$i++)
{
if($answer_key[$i] == $answers[$i])
$correct++;
}
// Setup query
$q = mysql_query("INSERT INTO `answer` VALUES ('$name', '$id','$answers','$correct')");
$result = mysql_query($q);
print 'Thnak you. You got' + $correct + 'of 10 answers correct';
?>
Try this:
// setup query
$q = "INSERT INTO `answer` (`name`, `id`, `answers`, `correct`) VALUES
('$name', '$id','$answers','$correct')";
//Run Query
$result = mysql_query($q) or die(mysql_error());
Also, you should avoid using mysql_ functions as they are in the process of being deprecated. Instead, I recommend you familiarize yourself with PDO.
Also, note, the or die(mysql_error()) portion should not be used in production code, only for debugging purposes.
Two things.
You are actually executing the query twice. mysql_query executes the query and returns the result resource. http://php.net/manual/en/function.mysql-query.php
And also, you are quoting the int column correct in your query, as far as I know, you can't do that (I could be wrong there).
$result = mysql_query("INSERT INTO `answer` VALUES (NULL,'$name', '$id','$answers',$correct)");
EDIT: Turns out I'm actually wrong, you may disregard my answer.

Categories