SQL query according to submit form - php

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

Related

insert value from drop down box to the database

I am missing something from my code and I don't know how to make it work. I may have programed it wrong and that could be giving me my troubles. I am new at php and things have been going slowly. please understand that the code my not be organized as it should be. After creating about 12 pages of code I found out that I should be using mysqli or pod. Once I get everything working that will be the next project. Enough said here is my issue. I was able to populate my drop down box and there shows no errors on the page. Also all the data does get inserted into the database except for the section made on the drop down box. Here is my code. I will leave out all of the input fields except the drop down.
<?php
{$userid = $getuser[0]['username'];}
// this is processed when the form is submitted
// back on to this page (POST METHOD)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
# escape data and set variables
$tank = addslashes($_POST["tank"]);
$date = addslashes($_POST["date"]);
$temperature = addslashes($_POST["temperature"]);
$ph = addslashes($_POST["ph"]);
$ammonia = addslashes($_POST["ammonia"]);
$nitrite = addslashes($_POST["nitrite"]);
$nitrate = addslashes($_POST["nitrate"]);
$phosphate = addslashes($_POST["phosphate"]);
$gh = addslashes($_POST["gh"]);
$kh = addslashes($_POST["kh"]);
$iron = addslashes($_POST["iron"]);
$potassium = addslashes($_POST["potassium"]);
$notes = addslashes($_POST["notes"]);
// build query
// # setup SQL statement
$sql = " INSERT INTO water_parameters ";
$sql .= " (id, userid, tank, date, temperature, ph, ammonia, nitrite, nitrate, phosphate, gh, kh, iron, potassium, notes) VALUES ";
$sql .= " ('', '$userid', '$tank', '$date', '$temperature', '$ph', '$ammonia', '$nitrite', '$nitrate', '$phosphate', '$gh', '$kh', '$iron', '$potassium', '$notes') ";
// #execute SQL statement
$result = mysql_query($sql);
// # check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
print "<h3><font color=red>New Water Parameters Were Added</font></h3>";
}
?>'
Here is the drop down
<tr><td><div align="left"><b>Tank Name: </b> </div></td><td><div align="left">
<?php
echo "<select>";
$result = mysql_query("SELECT tank FROM tank WHERE userid = '$userid'");
while($row = mysql_fetch_array($result))
{
echo "". $row["tank"] . "";
}
echo "";
?>
</div></td></tr>
You missed some code in while loop.
while($row = mysql_fetch_array($result))
{
echo "<option>".$row['tank']."</option>";
}
echo "</select>";
are you able to build drop down menu or box. if not try this query
$sql="SELECT `tank` FROM `tank` WHERE user_name='$user'";
$result=mysqli_query($dbc,$sql)
//here $dbc is a variable which you use to connect with the database.
Otherwise leave that only read from here why you need to change your code. in the while loop
one one more thing you have to give your select attribute a name, because it will return the value through name so give a name to your select attributes as you are using tank while building your drop down menu so i will give a same name tank. Than you dont have to change anything.
and you have to give value to your option as well, thanks
echo "<select name='age'>";
while($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['tank'] . "' >" . $row['tank'] . "</option>";
}
echo "</select>";

Set amounts in database using php + form

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.

POST method and arrays

This is my first php project. I have created a website where users can upload their picture and then view the pictures of other users, one person at a time (similar to the old hotornot.com). The code below works as follows:
I create an array (called $allusers) containing all members except for the user who is currently logged in ($user).
I create an array (called $usersiviewed) of all members who $user has previously either liked (stored in the likeprofile table) or disliked (stored in the dislikeprofile table). The first column of likeprofile and dislikeprofile has the name of users who did the liking/disliking, second column contains the name of the member they liked/disliked.
I use the array_diff to strip out $usersiviewed from $allusers. This is the list of users who $user can view (ie, people they have not already liked or disliked in the past).
Now the problem is when I click the like button, it updates the likeprofile table with the name of the NEXT person in the array (i.e., not the person who's picture I am currently looking at but person who's picture appears next). Additionally, if I refresh the current page, the person who's profile appears on the current page automatically gets 'liked' by me. I would really appreciate any advice on this.
<?php
// viewprofiles.php
include_once("header.php");
echo $user.' is currently logged in<br><br>';
echo <<<_END
<form method="post" action="viewprofiles.php"><pre>
<input type="submit" name ="choice" value="LIKE" />
<input type="submit" name ="choice" value="NEXT PROFILE" />
</pre></form>
_END;
$allusers = array();
//Create the $allusers array, comprised of all users except me
$result = queryMysql("SELECT * FROM members");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
if ($row[0] == $user) continue;
$allusers[$j] = $row[0];
}
//Create the $i_like_these_users array, comprised of all users i liked
$result = queryMysql("SELECT * FROM likeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_like_these_users[$j] = $row[1];
}
//Create the $i_dislike_these_users array, comprised of all users i disliked
$result = queryMysql("SELECT * FROM dislikeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_dislike_these_users[$j] = $row[1];
}
//Create the $usersiviewed array, comprised of all users i have either liked or disliked
if (is_array($i_like_these_users) && is_array($i_dislike_these_users))
{
$usersiviewed = array_merge($i_like_these_users,$i_dislike_these_users);
}
elseif(is_array($i_like_these_users))
{
$usersiviewed = $i_like_these_users;
}
else
{
$usersiviewed = $i_dislike_these_users;
}
// this removes from the array $allusers (i.e., profiles i can view) all $usersviewed (i.e., all the profiles i have already either liked/disliked)
if (is_array($usersiviewed))
{
$peopleicanview = array_diff($allusers, $usersiviewed);
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
else {
$peopleicanview = $allusers;
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
$current_user_profile = $peopleicanview[0];
echo 'check out '.$current_user_profile.'s picture <br />';
if (file_exists("$current_user_profile.jpg"))
{echo "<img src='$current_user_profile.jpg' align='left' />";}
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['choice']) && $_POST['choice'] == 'LIKE')
{
$ilike = $current_user_profile;
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$ilike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['choice']) && $_POST['choice'] == 'NEXT PROFILE')
{
$idontlike = $current_user_profile;
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$idontlike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
?>
Because when you refresh page it sends previus value of
Form again...and problem when u like a user it being liked next user.. There there is something in yor for loop while fetching row ...insted of for loop try once while loop ...i hope it will solve ur problem
You are calculating the $iLike variable with the currently loaded user and then updating the database with that user.
You should probably change your application logic a bit:
pass the user ID of the user you liked or did not like as a POST parameter in addition to the like/didn't like variable
move the form processing logic to the top of your page (or better yet separate out your form processing from HTML display)
Also, it's best not to use the mysql_* extensions in PHP. Use mysqli or PDO.
Try to make two different forms. One with "LIKE", another with "NEXT" to avoid liking from the same form
When you submit your form - your page refreshes, so in string $current_user_profile = $peopleicanview[0]; array $peopleicanview doesn't have user from previuos page (before submitting) you have to attach it, e.g. in hidden field
<form method="post" action="viewprofiles.php">
<input type="hidden" name="current_user" value="$current_user_profile" />
<input type="submit" name ="choice" value="like" />
</form>
<form method="post" action="viewprofiles.php">
<input type="submit" name ="go" value="next" />
</form>
and INSERT it later
"INSERT INTO likeprofile VALUES" . "('$user', '".$_POST['current_user']."')"
ps remove <pre> from your form
Lets start by simplifying and organizing the code.
<?php
// viewprofiles.php
include_once("header.php");
//if form is sent, process the vote.
//Do this first so that the user voted on wont be in results later(view same user again)
//use the user from hidden form field, see below
$userToVoteOn = isset($_POST['user-to-vote-on']) ? $_POST['user-to-vote-on'] : '';
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['like']))
{
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['dislike']))
{
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
//now we can create array of available users.
$currentProfileUser = array();
//Create the $currentProfileUser array,contains data for next user.
//join the 2 other tables here to save php processing later.
$result = queryMysql("SELECT `user` FROM `members`
WHERE `user` NOT IN(SELECT * FROM `likeprofile` WHERE user='$user')
AND `user` NOT IN(SELECT * FROM `dislikeprofile` WHERE user='$user')
and `user` <> '$user'
LIMIT 1");
//no need for a counter or loop, you only need the first result.
if(mysql_num_rows > 0)
{
$row = mysql_fetch_assoc($result);
$current_user_profile = $row['user'];
}
else
$current_user_profile = false;
echo $user.' is currently logged in<br><br>';
//make sure you have a user
if($current_user_profile !== false): ?>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="like" value="LIKE" />
</form>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="dislike" value="NEXT PROFILE" />
</form>
check out <?=$current_user_profile?>'s picture <br />
<?php if (file_exists("$current_user_profile.jpg")): ?>
<img src='<?=$current_user_profile.jpg?>' align='left' />
<?php endif; //end check if image exists ?>
<?php else: //no users found ?>
Sorry, there are no new users to view
<?php endif; //end check if users exists. ?>
You'll notice I changed the code a lot. The order you were checking the vote was the main reason for the issue. But over complicating the code makes it very difficult to see what's happening and why. Make an effort to organize your code in the order you expect them to run rather a vote is cast or not, I also made an effort to separate the markup from the logic. This makes for less of a mess of code to dig through when looking for the bug.
I also used sub queries in the original query to avoid a bunch of unnecessary php code. You could easily have used JOIN with the same outcome, but I think this is a clearer representation of what's happening. Also please use mysqli instead of the deprecaded mysql in the future, and be aware of SQL injection attacks and makes use of real_escape_string at the very least.
Hope it works out for you. Also I didn't test this code. Might be a few errors.

Search Form Ability To Ignore Blank Fields

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;

2 values from 1 input, PHP MySQL

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...

Categories