I'm building a validator script for barcode ticketing system. Which needs to check the barcode number against database. The thing is the first 7 numbers of the barcode is customer id and the last 4 numbers are the seat id.
For example:
12345671234
^^^^^^^--Customer ID
^^^^-- Seat ID
As I'll scan the barcode using a barcode scanner and it will
write whole barcode on a single input box I need to seperate these 2 values in that
1 input in order to get proper data from database.
Its now like:
<form action="validator.php" method="post">
Customer ID: <input id="uuid" name="uuid" maxlength="7"><br>
Seat: <input id="hash" name="hash" maxlength="4">
Needs to be like:
Barcode: <input id="barcode" name="barcode" maxlength="11"><input type="submit">
<input type="submit">
</form>
And the PHP Side
<?php
$uuid = $_POST['uuid'];
$hash = $_POST['hash'];
$con=mysqli_connect("localhost","admin","321","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM seat_booking_bookings
WHERE uuid ='$uuid'");
while($row = mysqli_fetch_array($result))
{
echo $row['customer_name'] . " " . $row['customer_phone'];
echo "<br>";
}
$result = mysqli_query($con,"SELECT * FROM seat_booking_bookings_seats
WHERE hash ='$hash'");
while($row = mysqli_fetch_array($result))
{
echo "Seat:";
echo $row['seat_id'] . " " . $row['price'];
}
?>
Thanks for all your help.
You can try this,
$uuid = substr($_POST['barcode'], 0,7);
$hash = substr($_POST['barcode'], 7,4);
Refer this. PHP Substring
$uuid = substr($_POST['barcode'], 0, 7);
$hash = substr($_POST['barcode'], 7, 4);
You just need to add an AND statement in your query. You're trying to validate based on two values, right?
$result = mysqli_query($con,"SELECT * FROM seat_booking_bookings
WHERE uuid ='{$uuid}' AND hash ='{$hash}'");
However, to prevent sql injection you should escape your values first. So this would be better:
$uuid = mysql_real_escape_string($uuid);
$hash = mysql_real_escape_string($hash);
$result = mysqli_query($con,"SELECT * FROM seat_booking_bookings
WHERE uuid ='{$uuid}' AND hash ='{$hash}'");
$uuid = substr($_POST['barcode'],0,7);
$hash = substr($_POST['barcode'],7,4);
i think this is what you are looking for...
Related
In this project, I am making an attendance user interface for the teacher. Here teacher can update student's marks which will directly update into the MYSQL database. Below shows the code that I used to echo out the list of students from the database. Here, I have used array i.e. name="gradeEdit[]" in input section.
teacherGrades.php
<?php
$con=mysqli_connect("#", "#", "", "#");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query ($con,"SELECT ");
echo ' <form method="POST" action="teacherGrades.php">
<table class="tableEchoPupil" border="1">
<tr>
<th>Name</th>
<th>Edit</th>
</tr>';
while($row = mysqli_fetch_array($result))
{
echo "<tr>
<td>" . $row['name'] . "</td>
<td> <input type='text' name='gradeEdit[]' /> </td>
</tr>"; }
echo "<input class='gradeSubmit' type='submit' name='btnSubmit' value='Submit'>";
echo "</table>";
echo "</form> <br/>";
?>
Below shows the code that is stored in the beginning of this page [teacherGrades.php
]. When the teacher inputs new grades and click the submit button from the previous code, the grades has to updated in the database. However the problem is that, I am not able to update it properly. I think there is a few problem behind my code, can you please check and help me. If there are further questions, I am ready to answer.
Thank you in advance.
<?php
$con=mysqli_connect("#","#","","#");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($_POST['btnSubmit']){
$gradeEdit = $_POST['gradeEdit'];
foreach ($gradeEdit as $key => $value) {
$grades = implode(',', $gradeEdit);
$query = "UPDATE classroom_student_teacher SET marks = '$grades'
WHERE teacher_id = $userid AND classroom_id = $id";
$close = mysqli_query($con, $query);
}
}
?>
You should pass student name or id in your input box. Which means row-1_key => row-1_value.
<input type='text' name='gradeEdit[".$row['student_id']."]' />
the above line is for form input. Let me know Are you updating data for teacher or for all students. State me table structure.
If you want to save array value. use the below line
foreach ($gradeEdit as $key => $value) {
//use $key as row id and marks will be your $value. So change your query like this below.
$row_id=$key+1;
$query = "UPDATE classroom_student_teacher SET marks = '$value'
WHERE student_id=$row_id AND teacher_id = $userid AND classroom_id = $id";
AND teacher_id = $userid AND classroom_id = $id why you using this condition
$close = mysqli_query($con, $query);
}
2 methods,
the json_encode is a possibility, but it might decode differently.
one option which sounds better to me would be to use serialize and unserialize, this will return the objects just as you put them.
e.g.
serialize($var);
unserialize($var);
It wil just make a serialized string of your array or objects.
In your case JSON could be fine too.
http://php.net/manual/en/function.serialize.php
To store data in you database you can use php own functions.
$conn=mysqli_connect("example.com","testuser","passwort","your_db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO Your_Table (First, Second, Array)";
$sql .= VALUES ('First', 'Second',Your_Array)";
mysqli_query($conn, $sql);
mysqli_close($con);
To put your array in the database you can user the php function implode.
$array = array('First', 'Second', 'Last');
$comma_separated = implode(",", $array);
Wich will return you a string like this - First, Second, Last
In my database users have a balance, im trying to set up a form that allows them to transfer amounts to each other. So for the from user it would - out of their current balance and update it to the new balance ( existing - amount transferred ) and for the receiver it would update ( existing + amount received ).
Heres my code below but its not updating any of the information:
<?php
if (isset($_POST['submit'])) {
$fromuser = $_POST['fromuser'];
$touser = $_POST['touser'];
$amount = $_POST['amount'];
$balanceto = mysql_query("SELECT `money` FROM `users` WHERE username = '$touser'");
$res1 = mysql_fetch_array($balanceto);
$balancefrom = mysql_query("SELECT `money` FROM `users` WHERE username = '$fromuser'");
$res2 = mysql_fetch_array($balancefrom);
$newmoney1 = ($res1['money'] + $_POST['amount']);
$newmoney2 = ($res2['money'] - $_POST['amount']);
$result1 = mysql_query("UPDATE `users` SET `money`='$newmoney1' WHERE username = '$touser'");
$result2 = mysql_query("UPDATE `users` SET `money`='$newmoney2' WHERE username = '$fromuser'");
}
?>
<form class="reg-page" role="form" action="" method="post">
<center>
Please note: Transfering funds is done at your own risk, please make sure you transfer the funds to the right person.<br><br>
<?php
$query = "SELECT username FROM users";
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<div class='row'><div class='col-sm-6'><label>Transfer $ To<span class='color-red'> *</span></label><select name='touser' class='form-control margin-bottom-20'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['username']}'>{$row['username']}</option>";
}
$dropdown .= "\r\n</select></div><div class='col-sm-6'>
<label>Amount $<span class='color-red'> *</span></label>
<input type='text' name='amount' class='form-control margin-bottom-20'>
</div></div>";
echo $dropdown;
?>
<input type="hidden" value="<?php echo $user_data['username']; ?>" name="fromuser">
<button type="submit" class="btn-u">Transfer</button>
</center>
</form>
All help much appreciated.
$_POST does not contain submit because you never put a NAME tag on the submit button.
Instead of:
<button type="submit" class="btn-u">Transfer</button>
You need:
<button type="submit" class="btn-u" name="submit">Transfer</button>
See here:
How do I post button value to PHP?
On further reflection it's probably a good idea to talk about some of the problems here, let's start with this one:
$balanceto = mysql_query("SELECT `money` FROM `users` WHERE username = '$touser'");
$res1 = mysql_fetch_array($balanceto);
$balancefrom = mysql_query("SELECT `money` FROM `users` WHERE username = '$fromuser'");
$res2 = mysql_fetch_array($balancefrom);
This is duplicated code, you can move this into a function to avoid copying and pasting, which is good practice, and you can use that function in other places in your code when you need to get the balance. Formatting the structure correctly helps in the event that your table changes, and you need to update the SQL. Without this in a single place, you are going to climb all over your code to find all the changes and update them.
<input type="hidden" value="<?php echo $user_data['username']; ?>" name="fromuser">
This is very bad practice, as it makes it easy for someone to slip an extra variable into the header and submit whatever user they want to your code, transferring money out of any other account that they want. Since this page already has access to this variable:
$user_data['username']
You should be using this in the IF statement at the top, instead of submitting it along with the form.
<input type='text' name='amount' class='form-control margin-bottom-20'>
This is another problem. You are asking for an amount, but creating a text field. A better example of this would be:
<input type='number' name='amount' class='form-control margin-bottom-20'>
Again though, these are easily modifiable post values, you have to make sure to check again on the server to make sure you didn't get fooled:
if(!(isNumeric($_POST['amount']) || $_POST['amount'] == 0 || $_POST['amount'] == ''))
The code above checks to make sure you have a numeric value, and that it is not 0 or blank, both of which would be invalid inputs. If either of those values is submitted, then it errors out and sends the user back to the form without processing the update.
Later on in your code, you start a PHP Tag to create the drop down:
<?php
$query = "SELECT username FROM users";
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<div class='row'><div class='col-sm-6'><label>Transfer $ To<span class='color-red'> *</span></label><select name='touser' class='form-control margin-bottom-20'>";
Assigning all of this to the $dropdown variable is completely wasted if you aren't going to use that drop down again (and it seems you are not). I can see that you wrapped it in PHP so you can loop over the options to print them out, but you can do that just as easily with a smaller PHP tag with a loop inside it, like this:
<select name='touser' class='form-control margin-bottom-20'>
<option value="null">Not Selected</option>
<?php
// Loop over all our usernames...
while($row = mysql_fetch_assoc($result)) {
// If we're not the current user...
if($row['username'] != $user_data['username']) {
// Add a drop down option!
echo "<option value='" . $row['username'] . "'>" . $row['username'] . "</option>";
}
}
?>
</select>
Note that this option ALSO includes a default "null" value for the select menu, and filters out the existing user (you can't transfer money to yourself, at least in this example). The null value is necessary because without it your code would automatically select the first user on the drop down list.
This would be my implementation of the same set of code here:
<?php
// If our submit is set...
if (isset($_POST['submit'])) {
// Get the balance for the from user
$fromBalance = getBalance($user_data['username']);
// Get the balance for the to user
$toBalance = getBalance($_POST['touser']);
// Get our new amounts, but don't do anything yet!
$newmoney1 = $toBalance + $_POST['amount'];
$newmoney2 = $fromBalance - $_POST['amount'];
// Check to make sure we have a valid amount
if(!(isNumeric($_POST['amount']) || $_POST['amount'] == 0 || $_POST['amount'] == '')) {
// Or error out!
echo 'ERROR: Bad amount Specified!';
// Check to make sure we have two valid users
} elseif($user_data['username'] == $_POST['touser']) {
// Or error out!
echo 'ERROR: Cannot transfer money to yourself!';
// Check to make sure sufficient funds are available
} elseif($newmoney2 < 0) {
// Or error out!
echo 'ERROR: Insufficient funds!';
// Check for default user selection...
} elseif($_POST['touser'] === 'null') {
// Or Error Out
echo 'ERROR: No username selected!';
// Otherwise we are good...
} else {
// So we call our update functions.
updateMoney($user_data['username'], $newmoney2);
updateMoney($_POST['touser'], $newmoney1);
// Send a success message
echo 'Transfer completed successfully, thank you!<br /><br />';
}
}
/** updateMoney()
*
* This function will take a user name and an amount and update their balance.
* Created to re-use code instead of copy and paste.
*
* #arg $user string
* #arg $amount integer
*/
function updateMoney($user, $amount) {
// Update our database table for this user with this amount
$result1 = mysql_query("UPDATE `users` SET `money`='$amount' WHERE username = '$user'");
}
/** getBalance()
*
* This function will return a balance for a given username.
* Created to re-use code instead of copy and paste.
*
* #arg $user string
* #return $amount integer
*/
function getBalance($user) {
// Execute query to get the result
$result1 = mysql_query("UPDATE `users` SET `money`='$amount' WHERE username = '$user'");
// Assign the result to a value
$res1 = mysql_fetch_array($balanceto);
// Return only the value we care about
return $res1['money'];
}
// Set our query for getting usernames from the DB
$query = "SELECT username FROM users";
// Get the usernames!
$result = mysql_query($query) or die(mysql_error());
?>
<form class="reg-page" role="form" action="" method="post">
<center>
Please note: Transfering funds is done at your own risk, please make sure you transfer the funds to the right person.
<br>
<br>
<div class='row'>
<div class='col-sm-6'>
<label>Transfer $ To<span class='color-red'> *</span></label>
<select name='touser' class='form-control margin-bottom-20'>
<option value="null">Not Selected</option>
<?php
// Loop over all our usernames...
while($row = mysql_fetch_assoc($result)) {
// If we're not the current user...
if($row['username'] != $user_data['username']) {
// Add a drop down option!
echo "<option value='" . $row['username'] . "'>" . $row['username'] . "</option>";
}
}
?>
</select>
</div>
<div class='col-sm-6'>
<label>Amount $<span class='color-red'> *</span></label>
<input type='number' name='amount' class='form-control margin-bottom-20'>
</div>
</div>
<button type="submit" class="btn-u" name="submit">Transfer</button>
</center>
</form>
But you STILL need to go fix the code so that you are NOT using MySQL and switch to MySQLi or PDO so that you can do prepared statements and actually protect yourself from MySQL injection attacks.
See here for more details:
https://wikis.oracle.com/display/mysql/Converting+to+MySQLi
You have posting the form with nameless button and trying to access via $_POST['submit']
<button type="submit" class="btn-u">Transfer</button>
name is missing. Add and try
<button type="submit" name="submit" class="btn-u">Transfer</button>
I think the button is missing tag 'name'. Try add this on your button:
<button type="submit" class="btn-u" name='submit'>Transfer</button>
To optimize your script I suggest do this:
if (isset($_POST['submit'])) {
$fromuser = $_POST['fromuser'];
$touser = $_POST['touser'];
$amount = $_POST['amount'];
$result1 = mysql_query("UPDATE `users` SET `money`= `money` + '$amount' WHERE username = '$touser'");
$result2 = mysql_query("UPDATE `users` SET `money`= `money` - '$amount' WHERE username = '$fromuser'");
}
So, you will eliminate two steps of processing and two hits on database.
start transaction
INSERT INTO power (sender, receiver, amount) VALUES ('$sender', '$receiver', '$amount')
UPDATE users SET power=power-$amount WHERE user_id='$sender'
UPDATE users SET power=power+$amount WHERE user_id='$receiver'
Submit button missing the name tag. use Transfer
Nothing glaringly wrong with the code, I'm assuming this is fake money.
Probably a malformed sql statement, try echoing the attempted sql before hand.
make sure all the queries work for a test example.
I have made a HTML search form which creates a query to a MySql database based on the contents of a form. What I would love to do is ignore the search parameter if the user leaves that specific form field empty. There are lots of answers online, especially on this website, but I can't get any of them to work.
I have stripped down my code as much as possible to paste into here:
The HTML input:
<form action="deletesearchresults.php" method="GET">
<p><b>First Part Of Postcode</b>
<input type="text" name="searchpostcode"></b> </p>
<p><b>Category</b>
<input type="text" name="searchfaroukcat"></b>
<input type="submit" value="Search">
</p>
</form>
The PHP results display:
<?php
mysql_connect("myip", "my_username", "my_password") or die("Error connecting to database: ".mysql_error());
mysql_select_db("my_db") or die(mysql_error());
$sql = mysql_query("SELECT * FROM
GoogleBusinessData
INNER JOIN TblPostcodeInfo ON GoogleBusinessData.BusPostalCode = TblPostcodeInfo.PostcodeFull WHERE PostcodeFirstPart = '$_GET[searchpostcode]' and FaroukCat = '$_GET[searchfaroukcat]' LIMIT 0,20");
while($ser = mysql_fetch_array($sql)) {
echo "<p>" . $ser['BusName'] . "</p>";
echo "<p>" . $ser['PostcodePostalTown'] . "</p>";
echo "<p>" . $ser['PostcodeArea'] . "</p>";
echo "<p>" . $ser['FaroukCat'] . "</p>";
echo "<p> --- </p>";
}
?>
This works great until I leave one field blank, in which case it returns no results as it thinks I am asking for results where that field is empty or null, which I don't wat. I want all of the results where that form field is empty.
I tried combining a like % [myfeild] % etc but I only want the results to display exactly what is on the field and not just the ones that contain what is in the field, for example searching for the postcode "TR1" would return results for TR1, TR10, TR11 etc.
I believe I may need an array but after 3 days of trying, I just don't know how to get this done.
Any help would be amazing.
edit: Also, I will be adding up to ten fields to this form eventually and not just the two in this example so please bear this in mind with any suggestions you may have.
try using isset()
example
if(isset($_GET[searchpostcode]) && isset($_GET[searchfaroukcat])){
$fields = "WHERE PostcodeFirstPart = '$_GET[searchpostcode]' and FaroukCat = '$_GET[searchfaroukcat]'";
}elseif(isset($_GET[searchpostcode]) && !isset($_GET[searchfaroukcat])){
$fields = "WHERE PostcodeFirstPart = '$_GET[searchpostcode]'";
}elseif(!isset($_GET[searchpostcode]) && isset($_GET[searchfaroukcat])){
$fields = "WHERE FaroukCat = '$_GET[searchfaroukcat]'";
}else{
$fields = "";
}
$sql = "SELECT * FROM
GoogleBusinessData $fields
INNER JOIN TblPostcodeInfo ON GoogleBusinessData.BusPostalCode = TblPostcodeInfo.PostcodeFull LIMIT 0,20";
You do however need to escape your $_GET variables however i would highly recommend using PDO/mysqli prepared statements http://php.net/manual/en/book.pdo.php or http://php.net/manual/en/book.mysqli.php
or try a foreach loop
foreach($_GET as $keys=>$value){
$values .= $keys."='".$value."' and";
}
$values = rtrim($values, " and");
if(trim($values) != "" || trim($values) != NULL){
$query = "WHERE ".$values;
}else{
$values = "";
}
$sql = "SELECT * FROM `test`".$values;
I want to query the database according to the input of the amount deposited. In the database the bank minimal amounts are stored. So the query consists in showing all banks with min_amount
The amount is defined $amount, and the row containing the minimum amounts is minimum. So i have done it like this but it tells me: Undefined index for $amount. ???
<form name="test" method="get" action="this.php">
Amount: <input name="amount"/>
<input type="submit"/>
</form>
<?php
$amount = $_GET["amount"];
$result = mysql_query("SELECT * FROM list1 WHERE minimum <= '$amount'");
while($row = mysql_fetch_array($result))
{
echo $row['bank_name'] . " - " . $row['Tariff'];
echo "<br />";
}
?>
You need to check if the form has been submitted or not. Try:
if( isset($_GET['amount'])) { /* your code here */ }
You need to check if the form has been submitted with say isset function.
if (isset($_GET['amount'])){}
Also it is highly advisable that you escape your $_GET variables before placing them into a mysql query as this kind of code allows for SQL injections.
The whole thing should like this:
if (isset($_GET['amount'])){
$amount = $_GET["amount"];
$result = mysql_query("SELECT * FROM list1 WHERE minimum <= '{$amount}'");
while($row = mysql_fetch_array($result))
{
echo $row['bank_name'] . " - " . $row['Tariff'];
echo "<br />";
}
I'm trying to do a simple logon script. That is, accept form content through a POST action. Check the database for a matching record. Pull other information from that row such as Full Name.
The code I have is;
if ( !isset($_POST['loginsubmit']) ) {
//Show login form
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<p>
Account ID:
<input name="AccountID" type="text" />
</p>
<p>
Username:
<input name="userEmail" type="text" />
</p>
<p>Password:
<input name="userPassword" type="password" />
<p>
<input name="loginsubmit" type="submit" value="Submit" />
</p>
</form>
<?php
}
else {
//Form has been submitted, check for logon details
$sql = "SELECT * FROM users WHERE 'accountID'=". $_POST['AccountID']. " AND 'userEmail'=". $_POST['userEmail'] . " AND 'userPassword'=". $_POST['userPassword']. " LIMIT 1";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if ($count == 1){
echo"Correct Username/Password";
}
else {
echo "Wrong Username or Password";
}
}
I have two issues. Firstly with the above code, I keep getting the following error.
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in ...
Second, how do I get the other details fields out of the databse. I presume
$result=mysql_query($sql);
contains an array for the MySQL row, so could I do something like;
echo $result['fullName'];
First sanitize the fields to prevent SQL injection.
$sanitize_fields = array('AccountID','userEmail','userPassword');
foreach( $sanitize_fields as $k => $v )
{
if( isset( $_POST[ $v ] ) )
$_POST[ $v ] = mysql_real_escape_string( $_POST[ $v ] );
}
Then quote the string fields in your query. Initially there was an error in your query. That's why you were getting a boolean value of false.
$sql = "SELECT * FROM users WHERE accountID='". $_POST['AccountID']. "' AND userEmail='". $_POST['userEmail'] . "' AND userPassword='". $_POST['userPassword']. "' LIMIT 1";
I suggest you do the following after running the query to see the error generated by MySQL, if there is one.
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
The MySQL extension is being phased out and there are newer better extensions such as MySQLi and PDO, have a look at those.
In your SQL statement:
$sql = "SELECT * FROM users WHERE 'accountID'=". $_POST['AccountID']. " AND 'userEmail'=". $_POST['userEmail'] . " AND 'userPassword'=". $_POST['userPassword']. " LIMIT 1";
if in the table, the userEmail and userPassword are strings, please add single qoutes:
$sql = "SELECT * FROM users WHERE accountID=". $_POST['AccountID']. " AND userEmail='". $_POST['userEmail'] . "' AND userPassword='". $_POST['userPassword']. "' LIMIT 1";
To get the results:
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
if(mysql_num_rows($result) > 0)
echo $row['COLUMN_NAME'];
}
}
Your codes are very insecure:
Please use MySQLi or PDO to interact with the database
Escape all input data before sending to the database
Try this:
else {
//Form has been submitted, check for logon details
$conn = mysql_connect("db-host-here","db-user-here","db-pass-here");
$sql = "SELECT * FROM users WHERE accountID=". mysql_real_escape_string($_POST['AccountID']). " AND userEmail='". $_POST['userEmail']=mysql_real_escape_string($_POST['userEmail']); . "' AND userPassword='". $_POST['userPassword']=mysql_real_escape_string($_POST['userPassword']);. "' LIMIT 1";
$result = mysql_query($sql,$conn);
$count = mysql_num_rows($result);
if($count == 1){
echo"Correct Username/Password";
}
else {
echo "Wrong Username or Password";
}
}
// Get other information:
$dbInfo = mysql_fetch_assoc(); //If more than one row can be selected, use a while loop.
//Now play with $dbInfo:
echo $dbInfo['some_other_column'];
You have single quotes in your query where you don't need them, and you're missing them where you do. Try the code above.
Replace db-host-here,db-user-here and db-password-here with the correct database information.
I have done some escaping in your code, to prevent injection attacks. But you should really look into using prepared statements.
The problem here is that Your query fails to select any row therefore a boolean FALSE is returned from mysql_query call.
You should repair Your query and always check if the $result = mysql_query($query); returns false or not, like so:
// ...
$result = mysql_query($query);
if($result !== false) {
$count = mysql_num_rows($result);
// ...
}
But I recommend using PDO or at least mysqli http://php.net/mysqli.