I get confused for post variable to sql query,
here is sample of my report.php code
<form action="report.php">
<select id="status" name="status">
<option value="MARRIED">married</option>
<option value="SINGLE">Single</option>
<option value="ALL">ALL</option>
</select>
<input type="submit" value="Seach">
</form>
<?php
$status= $_GET['status'];
// Create DB connection
$sql = "SELECT * FROM member WHERE status ='$status'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<B>id: </B>" . $row["user_id"]. " -- <b>Date Record:</b> " . $row["created"]. " -- <b>Last Seen</b> " . $row["last_seen"]. " -- <b>Status: </b> "
}
} else {
echo "0 results";
}
$conn->close();
?>
How do i Query If "ALL" condition is Selected?
I dont know the PHP so this is not the exact code but concept should be like this
if( $status == 'ALL' )
$sql = "SELECT * FROM member";
else
$sql = "SELECT * FROM member WHERE status ='$status'";
It would be very wise in this case to store the $status variable in POST instead, since the SQL query depends on what value is stored in the URL, and is thus exposed to the user.
Another thing, since you are dealing with legacy code here is to make extra sure that you filter the user input and SQL query as much as possible. The thing with using older and obsolete functionality is that you will still be vulnerable to XSS and SQL injection attacks regardless of the precautions you take so it is highly recommended you go with either the MySQLi or PDO (PHP Data Objects) extension instead as these offer more stable and advanced functionality.
$status = htmlspecialchars($_GET['status'], ENT_QUOTES);
$where = '';
if ($status != 'ALL') {
$where = 'WHERE status = "$status"';
}
$sql = mysql_real_escape_string('SELECT * FROM member ' . $where);
$results = mysql_query($sql);
In PHP file
<?php
$status= $_GET['status'];
if($status == 'ALL'){
$where = '';
}else{
$where = 'status = '".$status."' ';
}
// Create DB connection
$sql = "SELECT * FROM member WHERE ".$where." ";
?>
Related
I have dropdown menu with 3 values.
and here is my table (table name is Sms)
What I want to do? Example : If I choose 2,49 and press submit, then I get sonum value.
This is my form
<div class="col_12" style="margin-top:100px;">
<div class="col_6">
<label for="asukoht">Vali Hind</label>
<form class="vertical" method="GET">
<select name="hind">
<option value="1">-- Vali --</option>
<?php
// Tegin dropdown menüü, kust saab valida komponendi, mille alla see pilt läheb
$andmed = mysql_query("SELECT * FROM Sms");
// Dropdown menüü
while($rida = mysql_fetch_array($andmed)){
echo '<option value="'.$rida['id'] . '">'.utf8_encode($rida['hind'] ). '</option>';
}
?>
<input type="submit" name="add" id="add">
</form>
I tried something like this
if(mysql_query("DESCRIBE `Sms`")) {
$sql = "SELECT sonum FROM `Sms`";
echo $sql;
}
I think it should be pretty easy, but I'm looking for a solution and I didnt found it.
Thank you for helping !
You need to work on SQL and Loop.
Based on your code:
if(mysql_query("DESCRIBE `Sms`")) {
$sql = "SELECT sonum FROM `Sms`";
echo $sql;
}
First we do change the query including $_GET parameter.
So this:
$sql = "SELECT sonum FROM `Sms`";
Will become:
$sql = "SELECT sonum FROM `Sms` WHERE id = ".$_GET['hind'];
It will be better if you check that the var exist and is setted with something like:
if(isset($_GET['hind']) && is_numeric(trim($_GET['hind']){//Code here}
But it is off-topic.
Now let's change echo $sql; with a loop, we need to loop and fetch the data.
while($result = mysql_fetch_array($sql)){
echo '<option value="'.$result ['id'] . '">'.utf8_encode($result ['hind'] ). '</option>';
}
I've only changed what i know, you know your system ^_^
You should do:
$sql = "SELECT sonum FROM Sms WHERE id = ".$_GET['hind'];
Then do :
echo mysql_query($sql);
$sql = "SELECT sonum FROM Sms WHERE id = ".$_GET['hind'];
while($rida = mysql_fetch_array($sql)){
echo '<option value="'.$rida['id'] . '">'.utf8_encode($rida['hind'] ). '</option>';
}
Do not use MYSQL queries...try MySQLi or PDO with prepared statement.
I have a dynamic drop down menu on a PHP form which is working fine in that it retrieves/inputs the right id and will not process the form if no option is collected.
However, I am not sure how to make it sticky. I can do it on a static drop down with no problems but obviously I am missing something, can anyone help?
Below is the drop down menu:
echo '<div align="left">
<select name="dealership_id">
<option value="NULL">Choose a Dealer:</option>';
$query = 'SELECT * FROM dealership ORDER BY users_dealer_name ASC';
$result = mysql_query ($query);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "<option value=\"$row[0] \" <?php if (isset($_POST['dealership_id']) && $_POST['dealership_id'] == '$row[0]') {echo 'selected=\"selected\"';} ?> >$row[3]</option>";
}
// Complete the dropdown
echo '</select>
</div>
';
Below is the validation code
if (isset($_POST['dealership_id'])) {
$dealer_id = (int) $_POST['dealership_id'];
} else {
$dealer_id = 0;
}
if ($dealer_id > 0) {
$query = "SELECT dealership_id FROM dealership WHERE dealership_id=$dealer_id";
$result = mysql_query ($query); }
else {
echo '<p><font color="red">Please select your Dealership</font></p>';
}
BTW, row 0 is the primary key, row 3 is the name.
I don't think there should be single quotes around $row[0] in the following:
$_POST['dealership_id'] == '$row[0]'
By using single quotes you are literally comparing the string $row[0] instead of the variable value
Here's your code with some changes that are at least valid syntax; I didn't test to see if it works, but it should. It would be helpful for you to research string concatenation in php, some useful info here: http://www.php.net/manual/en/language.operators.string.php
echo '<div align="left">
<select name="dealership_id">
<option value="NULL">Choose a Dealer:</option>';
$query = 'SELECT * FROM dealership ORDER BY users_dealer_name ASC';
$result = mysql_query ($query);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "<option value=\"$row[0]\"";
if (isset($_POST['dealership_id']) && $_POST['dealership_id'] == $row[0]){
echo ' selected=\"selected\"';
}
echo ">$row[3]</option>";
}
// Complete the dropdown
echo '</select>
</div>
';
I have a form with a select multiple like this:
<select name="states[]" size="5" multiple>
<option value="2">state 1</option>
<option value="3">state 2</option>
<option value="4">state 3</option>
<option value="5">state 4</option>
<option value="6">state 5</option>
</select>
I want to have the possibility to choose more than one state, and then make the query to my database and show the description of each state chosen.
So this is what I have to make the query using PHP and MySQL:
$state = $_POST['states'];
$data = mysql_query("SELECT * from states WHERE id_state = '$state'",$db);
while($row = mysql_fetch_array($data)){
$result=$row['description'];
}
echo $result;
I have that code and it doesn't show anything.
How can I fix this problem?
Try this
$state = $_POST['states']; // return Array
$count_states = count( $state );
if( $count_states > 0) {
$states = implode( ',', $state);
$data = mysql_query("SELECT * from states WHERE id_state IN ($states)",$db);
while($row = mysql_fetch_array($data)){
echo $row['description'];
}
}
This would require a simple foreach to go through the array and get results based on each value as such,
foreach($_POST['states'] as $state) {
$data = mysql_query("SELECT * from states WHERE id_state = '$state'",$db);
$row = mysql_fetch_array($data);
echo $row['description'];
}
Also since you're not protecting your query in some sort and are using mySQL which has been deprecated as of PHP 5.5.0, I suggest you looking into PDO or mySQLi Prepared statements
$_POST['states'] holds an Array with all the ID's of the selected states.
Off course you can query your database for every posted state_id, but way nicer (and faster) would it be to make a query which looks like this and uses only one query:
SELECT description FROM states WHERE id_state=1 OR id_state=2 etc etc
This also might be a good point to start using a database abstraction layer like PDO.
As the number of posted states is variable, we need to make the statement also variable:
// The [connection setup][2] by PDO is done in $conn, with some proper exception handlers
// e.g. $conn = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// Fill an array with count() number of elements with value 'id_state=?'
$place_holders = array_fill(0, count($_POST['state']), 'id_state= ?');
//implode the array
$place_holders = implode(' OR ', $place_holders);
// prepare the query
$st = $conn->prepare("SELECT description FROM state WHERE $place_holders");
// execute to above prepared query with the $_POSTED states
$st->execute($_POST['state']);
// traverse the result
foreach($st->fetchAll() AS $r){
// do some magic
}
You could build the string by iterating through the array:
$state = "";
foreach($_POST['states'] AS $s)
{
// Sanitize $s here
$state .= "`id_state` = " . $s . " OR";
}
if($state)
{
$state = substr($state, 0, -3);
$data = mysql_query("SELECT * from states WHERE $state",$db);
while($row = mysql_fetch_array($data)){
echo $row['description'];
}
}
Of course, you should use something like MySQLi or PDO to handle database interaction. They will have ways to sanitize input easily so you can avoid obvious SQL injection.
Tamil has a pretty good IN select method as well. This is just one option.
Example (pages for edit):
//On select_multiple.php (Form):
<?php
//Conn
include('incl_config.php');
//Multiple data to bring
$sql = " select COD_DXS,VALOR_DXS from hc_dxsindromico where ESTADO_DXS='1' ";
$result=#mysql_query($sql);
?>
//In the form select:
<select multiple="multiple" size="7" name="dxsindromico[]"> //look yes or yes brackets []
<option value="" selected="selected">Choose one or more options</option>
<?php
while($row=mysql_fetch_array($result)){
?>
<option value="<?php echo $row['COD_DXS']; ?>" style="color:#F00;"><?php echo $row['VALOR_DXS'];?></option>
<?php } ?>
</select>
//////////// On grabar_mtr.php ///////////////
<?php
include('incl_config.php');
/*Multiple selection form in HTML5, PHP and Bootstraps
Created by: www.nycsoluciones.com
Version: 1.1*/
//we use a foreach to traverse the array (values of our select and save them in the table dxsindromico_data)
if(isset($_POST['dxsindromico'])){
foreach( $_POST['dxsindromico'] as $insertar ) {
//echo $insertar;
$sqli="insert into dxsindromico_data(DXSINDROMICO_HC) values('$insertar')";
//echo $sqli;
//exit;
$resulti=mysql_query($sqli);
}
} else{
foreach( $_POST['dxsindromico'] as $insertar ) {
//echo $insertar;
$sqli="insert into dxsindromico_data(DXSINDROMICO_HC) values('$insertar')";
$resulti=mysql_query($sqli);
}
}
?>
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.
I'm learning PHP from reading the php manual and studying different tutorials. I hit a snag with the mysql_query. I'm trying to insert user data into a database from a form using PHP. The mysql_query should return false because the username doesn't exist in the database yet but according to the result I am getting it is returning true and nothing is being entered into the database. Am I using mysql_query wrong or is using !result incorrect?
$sql = "SELECT * FROM users WHERE username='".$_POST["name"]."'";
$result = mysql_query($sql)
if (!$result) {
$sql = "INSERT INTO USERS (username, email, password) VALUES
('".$_POST["name"]."', '".$_POST["email"]."', '".$passwords[0]."')";
$result = mysql_query($sql);
if ($result) {
echo "It's entered!";
} else {
echo "There's been a problem: " . mysql_error();
}
} else {
echo "There's already a user with that name: <br />";
$sqlAll = "SELECT * FROM users";
$resultsAll = mysql_query($sqlAll);
$row = mysql_fetch_array($resultsAll);
while ($row) {
echo $row["username"]." -- ".$row["email"]."<br />";
$row = mysql_fetch_array($result);
}
}
Jason, you're checking to see if the query has failed or not - not whether it has returned the value 'false' or 'true'. You need to call mysql_fetch_row or similar, then compare the result.
Alternatively you could use the following:
if (mysql_num_rows($result) == 0) {
/* User doesn't exist */
} else {
/* User exists */
}
This will detect if any users have been chosen by your query and - if they have - your user exists already.
Also, you should learn about input sanitisation and SQL Injection. It's a very critical security issue and your script is vulnerable to it. More info here.
A select query which has no result rows STILL returns a result handle. msyql_query() will ONLY return a 'false' value if the query fails due to a syntax error, constraint violation, etc...
Your code should be
$sql = "...";
$result = mysql_query($sql);
if ($result === false) {
die("QUery failed: " . mysql_error());
}
if (mysql_num_rows($result) == 0) {
... user does not exist ...
}
And please please please read up about SQL injection vulnerabilities. Your code has holes wide enough for a truck to drive through.
In this case, $result will be a resource. You should check the number of results with mysql_num_rows().
Never, really, NEVER, use $_POST or any direct user input in a query. Always escape the input, BEFORE using it in a query, with mysql_real_escape_string(), or you'll have opened a serious security issue with SQL Injection.
Ex:
$safe_name = mysql_real_escape_string($_POST["name"]);
$sql = "SELECT * FROM users WHERE username='$safe_name'";
It's not exact.
mysql_query() will also fail and return FALSE if the user does not
have permission to access the table(s) referenced by the query.
In your case you have the permission but the user doesn't exist. So it will return true but the result set returned is empty.
mysql_query will return an empty set if the query returns no data. The query will however not fail.
i solve my problem :
like this
<?php
$username = $_POST['username'];
include('config.php');
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
while($row = mysqli_fetch_array($result)){
echo $row['username'];
echo "</br>";
echo "</br>";
echo "<p><b>Secret Question</b></p>";
echo $row['secret'];
}
?>
</br>
</br>
<form action="forgetaction.php" method="POST">
<p><b>Answer is :</b><p>
<input type="hidden" name="username" value="<?php echo $username; ?>">
<input type="text" name="answer">
</br>
</br>
<input type="Submit" value="Submit">
</form>
and forget action.php like this :
<?php
include('config.php');
$username = $_POST['username'];
echo $username;
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
$row = mysqli_fetch_array($result);
if($row['answer'] == $_POST['answer']) {
echo $row['password'];
} else {
echo 'wrong!';
}
?>
thank you all for help .