When I type a code into my form I want my PHP code to check on submit that the code exists in the database and then run MySqli query. I have tried to do that but I get error Cannot use isset() on the result of an expression (you can use "null !== expression" instead) I have Googled the problem but not a single one did help me to solve or understand my problem.
FORM
<p><b>Skriv in din laddkod nedan och tryck på "Ladda"</b></p>
<form action="laddaklar.php" method="post">
<input type="text" name="laddkod"/>
<input type="submit" name="submit" value="Ladda" />
</form>
PHP
<?php
session_start();
$mysqli = NEW MySQLI ('localhost', 'root', '', 'ph');
$laddkod = isset($_POST['laddkod']) ? $_POST['laddkod'] : '';
$kod= "SELECT refill from card_refill";
$result = $mysqli->query($kod);
if(isset($_POST['submit'] && $laddkod==$result)){
$resultSet = $mysqli->query ("UPDATE card_credit SET value= value + (select credit from card_refill WHERE refill='" . $_POST['laddkod'] . "') WHERE card_id = '" . $_SESSION['card'] . "' ");
echo "<b>Ditt kort har laddats!</b>";
}
else
{
echo "Fel laddkod";
}
The error that you're getting:
Cannot use isset() on the result of an expression
Is caused by what looks like an attempt to use an expression here:
if(isset($_POST['submit'] && $laddkod==$result)){...
You have to close the isset() properly and remove the spurious extra ):
if( isset($_POST['submit']) && $laddkod==$row['refill'] ){...
-----------------------add^ --------------------remove^
Furthermore you're not fetching any row results for the first query:
$kod= "SELECT refill from card_refill";
$result = $mysqli->query($kod);
$row = $result->fetch_assoc(); // The value will be in the $row array
Then you appear to never execute the UPDATE query.
Additionally it is not clear where you're setting $_SESSION['card'], but you will want to make sure it is set before attempting the UPDATE query.
Related
In my first php file I fetch results from mysql and show them in table. Every row value in one column must have value "Yes" or "No". When adding new request that value is "No". On "No" click I want to open another php (zatvaranje_zadatka.php) and send id_zadatka and broj_zadatka to new php file with form to input solution of request. On Submit in new php file I want to change flag in mysql table1 to "Yes" and write solution to another table in mysql.
In short notes in first php:
while ($row = mysql_fetch_array($result))
{
echo '<tr><td>' .$row["id_zadatka"] .'</td>';
echo '<td>Zatvori</td>';
}
In zatvaranje_zadatka.php I have:
$id_zadatak = isset($_GET['id_zadatka']) ? $_GET['id_zadatka'] : '';
$br_zht = isset($_GET['broj_zadatka']) ? $_GET['broj_zadatka'] : '';
if($id_zadatak != '') {
echo '<form action="zatvaranje_zadatka.php?go.php" method="POST" id="zatv_zad" name="zatv_zad">';
echo '<fieldset>';
echo ' Broj zadatka je:';
echo '<legend>Rješenje zadatka</legend>';
echo ' <textarea id= "rjesenje" name = "rjesenje" rows="4" cols="50"></textarea>';
echo '</fieldset>';
echo '<button type="submit" id="submit_zatv" name="submit_zatv"> Zatvori zadatak </button>';
echo '</form>';
$rjesenje = isset($_GET['rjesenje']) ? $_GET['rjesenje'] : '';
$query2 = "INSERT INTO rjesenje(broj_zadatka, rjesenje_zadatka) VALUES ('$br_zht', '$rjesenje')";
$result2 = mysql_query($query2) or die ("Nije uspio zapis u bazu" .mysql_error());
}
Output to table rjesenje is nothing.
This all code looks messy and questionable, but you might try this for testing in order to figure out how this all is working at the end..
$id_zadatak = $_GET['id_zadatka']; // we set this via URL
//$br_zht = $_GET['id_zadatka']; // id i broj su ista stvar
$rjesenje = $_POST['rjesenje'];
if($id_zadatak != '') {
echo '<form action="zatvaranje_zadatka.php?id_zadatka='.$id_zadatak.'" method="POST" id="zatv_zad" name="zatv_zad">';
echo '<fieldset>';
echo ' Broj zadatka je:';
echo '<legend>Rješenje zadatka</legend>';
echo ' <textarea id= "rjesenje" name = "rjesenje" rows="4" cols="50"></textarea>';
echo '</fieldset>';
echo '<button type="submit" id="submit_zatv" name="submit_zatv"> Zatvori zadatak </button>';
echo '</form>';
if(isset($rjesenje))
{
$query2 = "INSERT INTO rjesenje(broj_zadatka, rjesenje_zadatka) VALUES ('$id_zadatak', '$rjesenje')";
$result2 = mysql_query($query2) or die ("Nije uspio zapis u bazu" .mysql_error());
}
}
This is probably due to a typo. You need to leave a space between your table name and the row names. (e.g. rjesenje_(broj_zadatka, rjesenje_zadatka))
But whats worse is that your database is vulnerable for SQL injections. Please take a look at prepared statements
Your form is method="POST" and you check for $_GET variables. Thus the error rjesenje is empty. This should have resulted in an error, however you checked whether or not $_GET['rjesenje'] was set. It was not, thus the value of the variable is nothing, as specified when you check if it's set.
$rjesenje = isset($_GET['rjesenje']) ? $_GET['rjesenje'] : '';
returns false => $rjesenje = nothing
change the line to the following:
$rjesenje = isset($_POST['rjesenje']) ? $_POST['rjesenje'] : '';
To solve the problem, either change the request method of the form to method="get" or check for $_POST variables instead, as suggested above.
One way to check if this is true, you could try printing out the variables while debugging:
print_r($_GET);
or
print_r($_POST);
Make sure that you have your errors on while debugging
error_reporting(E_ALL);
read more: How to get useful error messages in PHP?
Additionally, I'd like to advise you to use mysqli or pdo functions instead of mysql. As mysql functions are deprecated as of php version 5.5 and completely removed in php 7.0, and because mysql functions are prone to attacks.
http://php.net/manual/en/intro.mysql.php
I have a checkbox in a form which I need to disable based on the value in the database. I searched a lot, but can't find any solution that works. Here's the sample code:
<?php
$server_name='localhost';
$username='root';
$password='';
$db_name='checkbox';
$con= mysqli_connect($server_name, $username, $password, $db_name);
if(mysqli_connect_errno())
{
echo 'Failed..!!'.mysqli_connect_errno();
}
$result= mysqli_query($con, "SELECT * FROM checkbox WHERE status=1");
$display = (mysqli_num_rows($result) == 1);
$disable = $display?'':'disabled="disabled"';
?>
<html>
<body>
<form name="f1" method="post" action="test2.php">
<input type="checkbox" name="A" value="" <?php echo $disable; ?> />
</form>
</body>
</html>
Thanks in advance.
Far as I can tell, it seems that you may have gotten your ternary's order mixed up.
Now this line is redundant:
$display = (mysqli_num_rows($result) == 1);
You're telling it that it always equals TRUE.
Just set this line to:
$display = mysqli_num_rows($result);
Then the ternary operator will take care of if it's found or not:
$disable = $display ? 'disabled="disabled"': '';
...and if found, disable it.
If that isn't what you're looking to do, then change it back to:
$disable = $display ? '': 'disabled="disabled"';
$result= mysqli_query($con, "SELECT * FROM checkbox WHERE status=1");
$display = (mysqli_num_rows($result) == 1);
Is likely the cause of your problems though it can't be 100% without looking in the database. Does that query return something other than one row? If it does your $display variable will always evaluate to false and not add that disable text to the input field.
Wrap the $disable variable in a var_dump() before you get to the rendering of HTML and see what value you are getting. Or do a direct database query with the one you are triggering off of and see if it is something other than one row.
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 am trying to pass a selected checkbox value from one page to another to run a mysql statement on my db.
This is what I have:
HTML
<form method='POST' action='move_compaudit.php'>
<input type='hidden' name='checkbox' value='0'/>
<input type='checkbox' name='checkbox' value='1'/>
PHP (this file called move_compaudit.php)
<?php
include('include/dbConnection.php');
$checkbox = isset($_POST['checkbox']) ? 'Set' : 'NotSet';
//SQL statement
$query = "SELECT * FROM compaudit;";
$results = mysqli_query($dbc,$query) or die('Error querying database');
$row = mysqli_fetch_array($results);
$query1 = "DELETE FROM compaudit WHERE serial_no = $row[7] AND $checkbox = 'Set'";
//Execute prepared MySQL statement
//$results1 = mysqli_query($dbc,$query1) or die('Error querying database');
print_r($query);
print_r($query1);
?>
My badly printed query: I get this everytime, regardless of click or not clicked.
SELECT * FROM compaudit;DELETE FROM compaudit WHERE serial_no = 12345 AND Set = 'Set'
If you are going to keep your HTML as it is, you need to check the actual value of $_POST['checkbox'] instead of checking if it is set. Your hidden field guarantees that even if it is not checked, $_POST will still get a value for "checkbox".
<?php
include('include/dbConnection.php');
$checkbox = ($_POST['checkbox'] == '1') ? 'Set' : 'NotSet';
....
Set is keyword in mysql :) you should escape it with `
If you declare before the checkbox a hidden with same name, this variable will be forever true for isset.
Look to #GameBit tip, escape with backticks the fields and quote/escape all variables before use into a query.