I have a search function which matches keywords from a database and echo's out some html but I'm missing how to enable the handling of empty searches. Can I use an else statement or do I have to redefine the same parameters and use !isset for if not set?
<?php
$con = mysqli_connect("localhost", "database", "password", "table");
if (isset($_GET['search'])) {
$search_query = $_GET['search_query'];
global $con;
$get_item = "select * from database where keywords like '%$search_query%'";
$run_item = mysqli_query($con, $get_item);
while ($row_item = mysqli_fetch_array($run_item)) {
$item_keywords = $row_item['item_keywords'];
echo "Search found for $search_query";
} // working fine up to here
} else {
echo "Search not found for $search_query";
}
?>
You can use isset() and mysqli_num_rows() to check empty result. ANd use mysqli_real_escape_string for fire your query
if (isset($_GET['search'])) {
if (isset($_GET['search_query']) && $_GET['search_query'] != "") {/// check variable is set or not
$search_query = $_GET['search_query'];
$$search_query = mysqli_real_escape_string($con, $search_query);//
$get_item = "select * from `database` where `keywords` like '%$search_query%'";
$run_item = mysqli_query($con, $get_item);
$row_cnt = mysqli_num_rows($run_item); // count number of rows
if ($row_cnt > 0) {
while ($row_item = mysqli_fetch_array($run_item)) {
$item_keywords = $row_item['item_keywords'];
echo "Search found for $item_keywords";
}
} else {
echo "Search not found for $item_keywords";
}
} else {
echo "Search not found for $item_keywords";
}
}
Change your condition to:
if (isset($_GET['search']) && trim($_GET['search_query']) != '') {
}
You can set condition for empty search like this.
if (isset($_GET['search']) && trim($_GET['search']) !='') { ... }
Modify your if condition
if (isset($_GET['search']) && !empty($_GET['search_query'])) {
}
You can do it by using the empty function:
if (!empty($_GET['search'])) {
//your code
}
Related
This script is selecting data based on optional fields in a HTML form. Although they are optional fields, at least 1 must be entered with the idea being that the more fields entered, the more likely you are to get a single result. For test I have two records with the same first and last name but different ID's and mobile numbers. At the moment when entering a name, 2 fields are given... Correct but when entering a mobile or ID, two results are still displayed.
Ive tried reading into passing missing variables in an SQL query but haven't got very far. Anything blindingly obviously wrong?
Thanks
<?php
include "checkmysqlconnect.php";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$mobile = $_POST['mobile'];
$attendid = $_POST['attendid'];
$search = $_POST['search'];
if ($search == "Search") {
if ($firstname == '' AND $lastname == '' AND $attendid == '' AND $mobile == '') {
header("Location: searchattendform.php?result=1");
$error = true;
}
if($error != true) {
$sql = "SELECT * FROM `attend` WHERE `firstname` = '".$firstname."' AND `lastname` = '".$lastname."' AND `attendid` = '".$attendid."' AND `mobile` = '".$mobile."'";
$query = mysql_query($sql);
$count = mysql_num_rows($query);
if ($count > 1) {
while($value = mysql_fetch_assoc($query)) {
echo "More than one attendee with this name. Entering more details will help narrow down results.";
echo "<tr><td>".$value['attendid']."</td><td>".$value['wristband']."</td><td>".$value['firstname']."</td><td>".$value['lastname']."</td><td>".$value['telephone']."</td><td>".$value['mobile']."</td><td>".$value['address1']."</td><td>".$value['address2']."</td><td>".$value['town']."</td><td>".$value['postcode']."</td><td>".$value['email']."</td><td>".$value['medical']."</td></tr>";
} } else {
if ($count == 0) {
header("Location: searchattendform.php?result=2");
} else {
if ($count == 1) {
($value = mysql_fetch_assoc($query));
echo "<tr><td>".$value['attendid']."</td><td>".$value['wristband']."</td><td>".$value['firstname']."</td><td>".$value['lastname']."</td><td>".$value['telephone']."</td><td>".$value['mobile']."</td><td>".$value['address1']."</td><td>".$value['address2']."</td><td>".$value['town']."</td><td>".$value['postcode']."</td><td>".$value['email']."</td><td>".$value['medical']."</td></tr>";
} else {
echo "The was an issue searching attendees. Please contact SOFia Admin.";
} }
}
}
}
?>
One issue you have is that your query always checks all the variables:
$sql = "SELECT * FROM `attend` WHERE `firstname` = '".$firstname."' AND `lastname` = '".$lastname."' AND `attendid` = '".$attendid."' AND `mobile` = '".$mobile."'";
You probably want to break it up, and build it dynamically, something like this:
$sql = "SELECT * FROM `attend` WHERE ";
$whereArray = [];
if ($lastName){
$whereArray[] = "`lastname` = '".$lastname."'";
}
if ($firstname){
$whereArray[] = "`firstname` = '".$firstname."'";
}
//etc...
$sql .= join(" AND ", $whereArrray);
You will need to modify this to use parametrization, but this should see you in the right direction:
include "checkmysqlconnect.php";
((isset($_POST['firstname']) && $_POST['firstname'] != '') ? $firstname = '%'.$_POST['firstname'].'%' : null); //prevents unneeded variables
...
if (!(isset($firstname) or isset($lastname) or isset($attendid) or isset($mobile))) { //checks that at least one variable has been provided
...
$sql = "SELECT * FROM `attend` WHERE 1=1"; //returns all; necessary for building the query since you have an unknown number of parameters
(isset($firstname) ? $sql .= " AND `firstname` like '".$firstname."': null); //adds to the query only if the variable exists
...
?>
I highly recommend using some kind of database wrapper class. This will help generate the SQL for you. There are many other reasons why this is a good idea.
There are plenty of MySQL wrappers and most frameworks have one. You could try for example, CodeIgniter, which is very simple framework to install and work with. Then, to create the query you would do something like:
<?php
if(isset($_POST['firstname']) && !empty($_POST['firstname'])) {
$this->db->where('firstname', $_POST['firstname']);
}
if(isset($_POST['lastname']) && !empty($_POST['lastname'])) {
$this->db->where('lastname', $_POST['lastname']);
}
...
$results = $this->db->>get('attend');
foreach($results->result() as $row)
{
echo $row->firstname;
}
?>
Try to place var_dump($sql); die(); after the $sql statement and test what that returns.
/MY CODE/
The if part is working properly but else is not working.
i even tried $variable instead of direct echo but still it is not working 'else'
Updated
<?php
$db = new mysqli('localhost', 'root' ,'', 'timeline');
if(!$db) {
echo 'Could not connect to the database.';
} else {
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
if(strlen($queryString) >0) {
$query = $db->query("SELECT collegename FROM college WHERE collegename LIKE '$queryString%' LIMIT 10");
if(isset($query)) {
echo '<ul>';
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.addslashes($result->collegename).'\');">'.$result->collegename.'</li>';
}
echo '</ul>';
} else {
echo 'create some'; // this part is not working
}
} else {
// do nothing
}
} else {
echo 'There should be no direct access to this script!';
}
}
?>
help me out.....
even read lots of like problem on stackoverflow but no real return
If you are using mysqli::query then your if(isset($query)) statement will always be evaluated as true, as $query would be either FALSE or a mysqli_result object. isset returns TRUE for both these values, so your else code will never be called.
Documentation on isset:
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
Use if($query !== false) instead.
Update
It also seems like you are checking $query to see whether or not there was a hit in the database. You need to check the number of rows in the result for that, e.g:
if ($query !== false && $query->num_rows > 0) {
// Query was ok and at least one row was returned
}
else {
// Will be reached if query was bad or there were no hits
}
Try
if($query_run = $db->query("SELECT collegename FROM college WHERE collegename LIKE '$queryString%' LIMIT 10")){
echo '<ul>';
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.addslashes($result->collegename).'\');">'.$result->collegename.'</li>';
}
echo '</ul>';
} else {
echo 'create some';
}
all this code is work, what left is I try to echo a message if query not find anything..
include("config.php");
$search = $_POST['search'];
$sql = mysql_query("SELECT * FROM barangtbl WHERE nama LIKE '%$search%' ") or die(mysql_error());
while ($res=mysql_fetch_array($sql)) {
echo $res['nama'].'<br>';
}
?>
Write this:
if(mysql_num_rows($sql)) {
while ($res=mysql_fetch_array($sql)) {
echo $res['nama'].'<br>';
}
}
else
{
echo "Not found";
}
Try this:
include("config.php");
$search = $_POST['search'];
$sql = mysql_query("SELECT * FROM barangtbl WHERE nama LIKE '%$search%' ") or die(mysql_error());
if(mysql_num_rows($sql))
{
while ($res=mysql_fetch_array($sql)) {
echo $res['nama'].'<br>';
}
}
else
{
echo "The query resulted in an Empty Set";
}
Here,
mysql_num_rows($sql) will output the total no of rows in the result. If the query's output is zero rows, the value of mysql_num_rows($sql) is zero which will lead to the if condition being false and hence executing the else part.
John V is right.
But i would suggest you to use mysqli instead of the deprecated mysql function
(deprecated since version 5.5)
http://php.net/manual/en/book.mysqli.php
try this:
if($sql)
{
echo "success";
}
else
{
echo "Error";
}
I'm trying to convert from an old MySQL library to PDO.
In order to read the data with my old MySQL code I use:
$assoc = mysql_fetch_assoc($exeqr);
With PDO I'm trying to do that with a foreach like I have on my code using PDO, but its not working...
Can you see something wrong here??
My OLD ode using MySQL:
<?php
if(isset($_POST['sendLogin']))
{
$f['email'] = mysql_real_escape_string($_POST['email']);
$f['pass'] = mysql_real_escape_string($_POST['password']);
if(!$f['email'] || !valMail($f['email']))
{
echo 'Email empty or invalid';
}
else if(strlen($f['pass']) <8 || strlen($f['pass'])>12)
{
echo 'pass must have between 8 and 12 chars!';
}
else
{
$autEmail = $f['email'];
$autpass = $f['pass'];
$query = "SELECT * FROM users where email= '$autEmail'";
$exeqr = mysql_query($query) or die(mysql_error());
$assoc = mysql_fetch_assoc($exeqr);
if(mysql_num_rows($exeqr) == 1 )
{
if($autEmail == $assoc['email'] && $autpass == $assoc['pass'])
{
$_SESSION['assoc'] = $assoc;
header('Location:'.$_SERVER['PHP_SELF']);
}
else
{
echo ' wrong password';
}
}
else
{
echo 'email does no exist';
}
}
}
And the new code I am trying to convert using PDO:
<?php
if(isset($_POST['sendLogin']))
{
$f['email'] = mysql_real_escape_string($_POST['email']);
$f['pass'] = mysql_real_escape_string($_POST['password']);
if(!$f['email'] || !valMail($f['email']))
{
echo 'Email empty or invalid';
}
else if(strlen($f['pass']) <8 || strlen($f['pass'])>12)
{
echo 'pass must have between 8 and 12 chars!';
}
else
{
$autEmail = $f['email'];
$autpass = $f['pass'];
$searchEmail = $pdo->prepare("SELECT * FROM users where email=:email");
$searchEmail->bindValue(":email,$autEmail");
$searchEmail->execute;
$num_rows = $searchEmail->fetchColumn();
$result = $searchEmail->fetch(PDO::FETCH_OBJ);
if($num_rows == 1)
{
if($autEmail == $result['email'] && $autpass == $result['pass'])
{
$_SESSION['result'] = $result;
header('Location:'.$_SERVER['PHP_SELF']);
}
else
{
echo ' wrong password';
}
}
else
{
echo 'email does no exist';
}
}
}
Warning: PDOStatement::bindValue() expects at least 2 parameters, 1 given in $searchEmail->bindValue(":email,$autEmail");
You need to move your ", currently it's including the variable as well as the parameter name resulting in you not passing in the variable to bind to said parameter (which is why you are getting the error telling you you haven't passed in enough arguments).
$searchEmail = $pdo->prepare("SELECT * FROM users where email = :email");
$searchEmail->bindValue(":email", $autEmail);
Notice: Undefined property: PDOStatement::$execute in $searchEmail->execute;
You've forgotten the () brackets from execute(), so PHP is looking for the property of the PDO class called execute instead of the function call.
$searchEmail->execute();
(thanks Prix)
Edit
Your question is now about how to replace this:
$assoc = mysql_fetch_assoc($exeqr);
... with a PDO equivalent. In the manual, there is an example:
$assoc = $searchEmail->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
Note: fetchAll() is for fetching multiple results. If you're expecting only one result (which you might be, but you aren't limiting your query so it's feasible to return multiple results), you should just use fetch():
$assoc = $searchEmail->fetch(PDO::FETCH_ASSOC);
This is a really simple one, I just can't get my head around it sorry. I have this PHP code which picks up my form value, then compares it with the value stored in the database. That works fine.
However I am not sure how to write this logic in terms of this query:
If posted value = database value {
// do something } else { // do something else }
if (empty($_POST['order_id']) === false) {
// prepare data for inserting
$order_id = htmlentities(trim($_POST['order_id']));
$order_id = preg_replace("/[^0-9]/","", $order_id);
$result = mysqli_query($con,"SELECT * FROM listings WHERE order_id = $order_id");
$row = mysqli_fetch_assoc($result);
echo $row['order_id'];
}
SOLVED:
Solved the question, was a silly one I know! Just needed this at the end of the code:
if($order_id === $row['order_id']) {
echo 'found';
} else {
echo 'not found';
}
Try
If ($result->num_rows === 1) { do something } else { do something else }
Since you did the business logic in your query you can just use
if( ! is_null($row)) {
// do
} else {
// nothing
}
Did I read too much into "If posted value = database value "? Are you just referring to the order_id?
if ($row['listingName'] == $_POST['frm_listingName']) {
// something
}
else {
//something else
}
Check this code:
if (empty($_POST['order_id']) === false) {
// prepare data for inserting
$order_id = htmlentities(trim($_POST['order_id']));
$order_id = preg_replace("/[^0-9]/","", $order_id);
$result = mysqli_query($con,"SELECT * FROM listings WHERE order_id = $order_id");
if(mysqli_num_rows($result)>0)
{
//Match found. do something.
}
else
{
//No match found. do something.
}
}
N.B. In place of mysqli_num_rows($result) you can also use $result->num_rows