- Edited
Weedpacket
When I keep one search condition off other options work course but when both options run only title field working and location filed not work.
Weedpacket
When I keep one search condition off other options work course but when both options run only title field working and location filed not work.
So when you are filling in both fields, you're still making two queries and throwing one away?
Weedpacket
getting last query
actually working only last onewhile($items = mysqli_fetch_assoc($result)){
while($items = mysqli_fetch_assoc($query)){
and when I setup while($items = mysqli_fetch_assoc($query)){
while($items = mysqli_fetch_assoc($result)){
Then last one
So let's go through this.
kumerbakul if(ISSET($_GET['search'])){
if(ISSET($_GET['search'])){ $keyword = $_GET['title']; $query = mysqli_query($conn, "SELECT * FROM `products` WHERE `title` LIKE '%$keyword%' OR `company` LIKE '%$keyword%' OR `category` LIKE '%$keyword%' OR `description` LIKE '%$keyword%' OR `time` LIKE '%$keyword%' ORDER BY id DESC") or die(mysqli_error()); if(ISSET($_GET['search'])){ $word = $_GET['location']; $query = mysqli_query($conn, "SELECT * FROM `products` WHERE `city` LIKE '%$word%' OR `state` LIKE '%$word%' OR `address` LIKE '%$word%' OR `country` LIKE '%$word%'OR `job` LIKE '%$word%' ORDER BY id DESC") or die(mysqli_error()); while($items = mysqli_fetch_assoc($query)){
if(isset($_GET['search'])) {
If the search
field is set then:
$keyword = $_GET['title'];
Get the title
field and put it in $keyword
. Then
$query = mysqli_query($conn, ...) or die(...);
Do a query. Then
if(isset($_GET['search'])) {
If the search
field is set (and we know it is because we just checked and never finished that part of the code) then:
$word = $_GET['location'];
Get the location
field and put it in $word
. Then
$query = mysqli_query($conn, ...) or die(...);
Do a second query. Then
while($items = mysqli_fetch_assoc($query)){
Go through the results of the last query made.
You're not seeing the logical failure here? You make two queries but you are only fetching results from one of them.
NogDog
Not working both queries at a time
actually working only last onewhile($items = mysqli_fetch_assoc($result)){
while($items = mysqli_fetch_assoc($query)){
and when I setup while($items = mysqli_fetch_assoc($query)){
while($items = mysqli_fetch_assoc($result)){
Then last one
Weedpacket
You are right, Please help me how can I get both result
Trying to D.R.Y. things up a bunch, but totally untested, so buyer beware:
<?php
include 'config.php';
if(isset($_GET['search'])) {
$wheres = [];
foreach(['title', 'location'] as $search) {
if($value = safe_value($conn, $seardh)) { // something was entered for that search
foreach(['title', 'company', 'category', 'description', 'time'] as $column) {
$wheres[] = "`$column` LIKE '%$value%'";
}
}
}
if(count($wheres)) { // at least one of the search fields was set
$sql = "SELECT * FROM `products` WHERE\n".implode(" OR\n", $wheres)."\nORDER BY id DESC";
// uncomment the following if you want to debug the query:
// die("<pre>$sql</pre>");
$query = mysqli_query($conn, $sql) or die(mysqli_error());
while($items = mysqli_fetch_assoc($query)) {
// do stuff with result
}
} else {
// whatever you want to do if neither search field was supplied
}
}
function safe_value(mysqli $conn, string $name) {
if(!isset($_GET[$name]) or trim($_GET[$name]) === '') {
return false;
}
// might want to add strtolower() or strtupper to this?
return mysqli_escape_string($conn, trim($_GET[$name]));
}
If you want to force the search term to lower-case, for example, change the last line of that function to:
return mysqli_escape_string($conn, strtolower(trim($_GET[$name])));
(I need one of those "buy me a coffee" links or something. )
It's difficult to assess from your code whether you understands HTML.
Where is your form tag?
Here is an example of what I think you are tyrying to do.
The form passes control to an action url adminpage.php which displays the inputs
<?php
session_start();
date_default_timezone_set("Europe/London");
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<script type="text/javascript">
function subForm(){
subfrm = true;
if (name1Obj.value == ""){
alert("Please enter Name Part 1");
name1Obj.focus();
subfrm=false;
return;
}
if (name2Obj.value == ""){
alert("Please enter Name Part 2");
name2Obj.focus();
subfrm=false;
return;
}
if (pwordObj.value == ""){
alert("Please enter Password");
pwordObj.focus();
subfrm=false;
return;
}
if (subfrm==true){
// post to next page
formObj.action="adminpage.php";
formObj.submit();
}
}
</script>
</head>
<body>
<form name="form1" method="post" action="adminpage.php" id="form1">
<div>
<span id="Label1" style="display:inline-block;height:16px;width:50px;left: 305px; position: absolute;
top: 109px; padding-left: 0px; padding-bottom: 0px; margin: 0px; vertical-align: middle; text-indent: 0px; padding-top: 0px; text-align: left;">Part 2</span>
<span id="Label1" style="display:inline-block;height:16px;width:173px;left: 73px; position: absolute;
top: 109px; padding-left: 0px; padding-bottom: 0px; margin: 0px; vertical-align: middle; border-top-style: none; text-indent: 0px; padding-top: 0px; border-right-style: none; border-left-style: none; letter-spacing: normal; text-align: left; border-bottom-style: none;">Username Part 1</span>
<input name="username1" type="text" value="" maxlength="16" id="username1" tabindex="1" style="width:100px;left: 190px; vertical-align: middle;
direction: ltr; text-indent: 3px; letter-spacing: normal; position: absolute;
top: 104px; height: 20px; text-align: left; z-index: 105;" />
<input name="username2" type="text" value="" maxlength="16" id="username2" style="width:100px;left:350px; vertical-align: middle;position: absolute;
top: 104px; height: 20px; text-align: left;" />
<input name="pword" type="text" value="" maxlength="1000" id="pword" tabindex="2" style="width:100px;left: 190px; vertical-align: middle;
direction: ltr; text-indent: 3px; letter-spacing: normal; position: absolute;
top: 132px; height: 20px; text-align: left; z-index: 103; bottom: 305px;" />
<button id="loginButton" onclick="javascript:subForm();return false;" style="left: 190px; position: absolute; top: 170px; z-index: 107; width:200px; height:25px;">Log in</button>
<span id="Label2" style="display:inline-block;height:16px;width:71px;left: 73px;
vertical-align: middle; text-indent: 0pt; letter-spacing: normal; position: absolute;
top: 135px; text-align: left; z-index: 104;">Password</span>
</div>
</form>
<script type="text/javascript">
formObj = document.getElementById("form1");
name1Obj = document.getElementById("username1");
name2Obj = document.getElementById("username2");
pwordObj = document.getElementById("pword");
</script>
</body>
</html>
Heres tha admipage.php
<?php
session_start();
date_default_timezone_set("Europe/London");
$username1 = "NOT SET";
$username2 = "NOT SET";
$password = "NOT SET";
$contlen = $_SERVER['CONTENT_LENGTH'];
if ($contlen > 0){
$username1 = $_REQUEST['username1'];
$username2 = $_REQUEST['username2'];
$password = $_REQUEST['pword'];
}
?>
<!DOCTYPE html>
<html>
Admin Page
<table>
<tr><td>User name Part 1</td><td><?=$username1 ?></td></tr>
<tr><td>User name Part 2</td><td><?=$username2 ?></td></tr>
<tr><td>Password</td><td><?=$password ?></td></tr>
<tr><td colspan="2">Do what you need to do with this data</td></tr>
</table>
</html>
I suggest you master this task first and then add your database access code and work on that.
NogDog
Many many thanks for your effort, it's working...
NogDog
Sorry for disturb you. I have a problem when insert pagination. below the error
Fatal error: Uncaught Error: Call to undefined function safe_value() in
All that tells me is that somewhere you are trying to call that function in a context where it is not defined; so either you need to define it in that context, or add it to some file that gets included wherever you might need it, or...?
kumerbakul
I think the error might be misleading.
The line
if($value = safe_value($conn, $seardh))
is an assignment.
I believe the code is supposed to be a comparison and so should use the == operator
if($value == safe_value($conn, $seardh))
Try that.
RayPooley think the error might be misleading.
The line
if($value = safe_value($conn, $seardh))
is an assignment.
I believe the code is supposed to be a comparison and so should use the == operator
if($value == safe_value($conn, $seardh))
Try that.
That wouldn't make a difference. The value of the assignment is still either whatever safe_value()
returns, so the if()
statement still takes the same branch. The only difference is that $value
is also assigned the same value, which is a good thing, since it is then used later in the then branch.
Using ==
wouldn't fix anything because now you're comparing the return value of safe_value()
with the value of a variable that doesn't even have a value yet. (You'd get an Undefined variable warning, and take the "safe value" branch only in the situation when safe_value()
returns false.)
And, of course, it wouldn't fix the reported problem that the safe_value
function wasn't even found in the first place.
I do notice another bug, though: safe_value()
will return a falsy value if $_GET[$name]
is '0'
. It may not be relevant in this instance (what does the "time
" column contain if time LIKE '%$value%'
is useful?) but since we're retrieving every record that contains a 1
in the description it would be churlish to not be doing the same for 0
. I think the return value should be checked more carefully:
if(($value = safe_value($conn, $search)) !== false)
or even separate testing-for-content and escaping-for-query into two separate functions.
But yes, like @NogDog says, if your pagination thing is on a different page then you'll need to get the function there as well, preferably by putting it another file and including it on every page you need it. If that's not what you're doing you'll need to explain what you are doing.
Weedpacket
I'm talking about logic.
If the code is performing an assignment when it should be performing a comparison
then the outcome may well be unpredictable.
This is clearly questionable and therefore warrants attention.
if($value = safe_value($conn, $seardh)){
Because the next step in the process depends on the outcome of that statement ie: true or false.
A statement of the nature
if ($x = 88){
echo "true";
} else {
echo "false";
}
is ALWAYS going to evaluate TRUE and therefore the code in the first curly brackets in this case
foreach(['title', 'company', 'category', 'description', 'time'] as $column) {
$wheres[] = "`$column` LIKE '%$value%'";
}
is always going to be executed whether it's logically appropriate or not.
A statement of the nature
if ($x == 88){
echo "true";
} else {
echo "false";
}
will evaluate TRUE OR FALSE depending on whether $x has a value 88 and therefore the code in the
first curly brackets in this case
foreach(['title', 'company', 'category', 'description', 'time'] as $column) {
$wheres[] = "`$column` LIKE '%$value%'";
}
may be executed or it may not depending on the value of $x.
The fact that this block of code is encapsulated within an IF statement suggests that it should only
be executed conditionally.
If this code needs to be executed UNCONDITIONALLY then there's actually no logical reason in having
it subject to an IF condition at all.
RayPooley If you look at the definition of the safe_value()
function you'll see it can return a string and it can also return false
. If it returns false the second branch will be taken and the contents of $value
(which would be false
per the assignment) is ignored. If it returns a non-false value that value will be assigned to $value
and the first branch taken, where $value
is used.
Notice that $value
doesn't get assigned a value otherwise, so trying to compare its value to any other would be a mistake.
In addition to my previous.
Try moving the safe_value() function definition up to the top of the program.
Like this..
<?php
include 'config.php';
function safe_value(mysqli $conn, string $name) {
if(!isset($_GET[$name]) or trim($_GET[$name]) === '') {
return false;
}
// might want to add strtolower() or strtupper to this?
return mysqli_escape_string($conn, trim($_GET[$name]));
}
if(isset($_GET['search'])) {
$wheres = [];
foreach(['title', 'location'] as $search) {
if($value == safe_value($conn, $seardh)) { // something was entered for that search
foreach(['title', 'company', 'category', 'description', 'time'] as $column) {
$wheres[] = "`$column` LIKE '%$value%'";
}
}
}
if(count($wheres)) { // at least one of the search fields was set
$sql = "SELECT * FROM `products` WHERE\n".implode(" OR\n", $wheres)."\nORDER BY id DESC";
// uncomment the following if you want to debug the query:
// die("<pre>$sql</pre>");
$query = mysqli_query($conn, $sql) or die(mysqli_error());
while($items = mysqli_fetch_assoc($query)) {
// do stuff with result
}
} else {
// whatever you want to do if neither search field was supplied
}
?>
Weedpacket
You don't get what I am saying here.
I am talking about the statement ...
if($value = safe_value($conn, $seardh)) {
The IF statement is a CONDITIONAL statement.
It requires a COMPARISON expression that evaluates to a boolean value.
A boolean has two and only two possible values. true or false.
A COMPARISON expression contains COMPARISON operators.
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type
Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
<=>
Note that the "=" operator IS NOT IN the COMPARISON operators list.
That's because it is an ASSIGNMENT operator
x = y x = y The left operand gets set to the value of the expression on the right
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus
Note that the "=" operator IS IN the ASSIGNMENT operators list.
An ASSIGNMENT returns only ONE value if tested. That would be TRUE. As I demonstrated
in a previous post. An ASSIGNMENT does not return FALSE. It may return an error code
if the data types of the operands are incompatible in a heavily typed environment in which
case the program would abend. But an ASSIGNMENT doesn't return FALSE if the statement
is valid.
The code ...
if($value = safe_value($conn, $seardh)) {
is not a legitimate IF statement.
It doesn't matter what the safe_value() function does. It doesn't matter what the operands
are. It is an ASSIGNMENT expression. Not a COMPARISON expression which is the type of statement
the IF statement requires.
The safe_value() function or what it does is irrelevant. By the way, a function shouldn't be
returning different data types (string or boolean). It should only return one data type.
RayPooley
You don't get what I'm saying.
The if
statement requires an expression that evaluates to a boolean (and if it doesn't get a boolean, it coerces what it does get into one). It does not care if that expression is a comparison or not.
https://www.php.net/manual/en/control-structures.if.php
The simplest yet most accurate way to define an expression is "anything that has a value".
https://www.php.net/manual/en/language.expressions.php
RayPooley An ASSIGNMENT returns only ONE value if tested. That would be TRUE.
No, it does not. It returns the value that was evaluated on the right-hand side.
The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3.
https://www.php.net/manual/en/language.operators.assignment.php
RayPooley The safe_value() function or what it does is irrelevant. By the way, a function shouldn't be
returning different data types (string or boolean). It should only return one data type.
Frankly, I agree, but it is a common idiom in PHP with many of its inbuilt functions doing exactly that.
Weedpacket
I'm wasting my time here.
Here's a challenge.
See if you can get this IF statement to return false.
Only two rules.
You can change the initial value of $x.
You can change the assigned value of $x in the IF expression.
$x = 8;
if ($x = 88){
echo "true";
}
else
{
echo "false";
}
then try this one ..
$x = 8;
if ($x == 88){
echo "true";
}
else
{
echo "false";
}