PHP parameterized on mysql query with LIKE and CONCAT on partial string - php

I'm struggling with this query. I'm trying to match one of two fields against a partial string for an ajax call. Start typing a name, it should match against first or last name.
My parameterized query is returning 0 rows on LIKE statement.
I've tried answers from here and here and here.
I'm afraid I'm missing something simple, but I can only think that the parameters aren't passing in right for the partial string.
<?
$access = 3;
$dbConnect = true;
require "../scripts/php/scriptSecurity.php";
// Partial name given by user.
$name = $_GET["name"];
if (!empty($name)){
if (strpos($name, " ")){
$nameParts = explode(" ", $name);
if (strpos($nameParts[0], ",")) {
$last = str_replace(",", "",$nameParts[0]);
$first = $nameParts[1];
}
else {
$first = $nameParts[0];
$last = $nameParts[1];
}
}
else {
$last = str_replace(",", "", $name);
$first = str_replace(",", "", $name);
}
// Freak out that maybe some hidden character is in the name.
$last = preg_replace( "/[^a-zA-Z0-9']/", "", $last );
$first = preg_replace( "/[^a-zA-Z0-9']/", "", $first );
if ($last != $first){
$query = "SELECT * FROM students WHERE LastName LIKE CONCAT('%', ? , '%') AND FirstName LIKE CONCAT('%', ? , '%') ORDER BY LastName, FirstName LIMIT 30" ;
}
else {
$query = "SELECT * FROM students WHERE LastName LIKE CONCAT('%', ? , '%') OR FirstName LIKE CONCAT('%', ? , '%') ORDER BY LastName, FirstName LIMIT 30";
}
if ($nameStmt = $connect->prepare($query)){
$nameStmt->bind_param('ss', $last, $first);
if (!$nameStmt->execute()) {
echo $nameStmt->error;
}
$result = $nameStmt->get_result();
$count = 0;
if (empty($result)){
while ($row = $result->fetch_assoc()){
$count++ ;
if ($count % 2 != 0)
$class="odd";
else
$class="even";
?>
<div class="studentRow <?php echo $class ?>"><?php echo $row["LastName"] . ", " . $row["FirstName"] . " " . $row["MiddleName"] ?> <div><a class="stuPass" id="stuPass_<?php echo $row["id"] ?>" href="scripts/getPass.php?id=<?php echo $row["id"] ?>">Pass</a></div><div><a class="stuDetails" id="stuDetails_ <?php $row["id"] ?>" href="scripts/students/getDetails.php?id=<?php echo $row["id"] ?>">Details</a></div></div>
<div class="stuDetails hidden" id="stuDetailsHolder_<?php echo $row["id"]?>"></div>
<?php
}
}
else {
echo "Results are empty.";
}
}
else {
echo "<br />". $connect->error;
}
}
Here is the code from uploading the data in the db. I was worried that I might have hidden characters lurking, but I think I have them all stripped out.
$fStu = new SplFileObject('../resources/students.txt');
$fStu->seek($count);
list($year,$building,$id,$last,$middle,$first,$gender,$grade,$gradYear) = explode(",",$fStu->current());
if (!empty($year)){
$stuQuery = "INSERT INTO students (LastName, MiddleName, FirstName, StudentId, Gender, Grade, GradYear) VALUES (?,?,?,?,?,?,?)";
$stuStmt = $connect->prepare($stuQuery);
$last = preg_replace( "/[^a-zA-Z0-9']/", "", $last );
$first = preg_replace( "/[^a-zA-Z0-9']/", "", $first );
$middle = preg_replace( "/[^a-zA-Z0-9']/", "", $middle );
$gender = preg_replace( "/\r|\n|\s+/", "", $gender );
$id = intval(preg_replace('/\D/', '', $id));
$gradYear = intval(preg_replace('/\D/','', $gradYear));
$grade = intval(preg_replace('/\D/','', $grade));
$stuStmt->bind_param("sssisss", $last, $middle, $first,$id,$gender,$grade,$gradYear);
$stuStmt->execute();
echo $count . "||" . $last . ", " . $first . " (" . $id . ")";
}
else {
$count = -1;
echo $count . "||Complete.";
}
Here's the main page passing the partial name with the querystring.
$(document).ready(function(){
$("#name").on("change paste keyup", function(e){
e.preventDefault();
$.ajax({url: "process/students.php?name=" + $("#name").val(),
success: function(result){
$("#results").removeClass("hidden");
$("#results").html(result);
}
});
});
Here's a set of data getting uploaded.
> > Current School Year,Current Building,Student Id,Student Last Name,Student Middle Name,Student First Name,Student Gender,Student
> > Grade,Grad Year 2018,111,11111111111,Doe,Jane,,F,09,2021
> > 2018,111,22222222222,Doe,John,,M,09,2021

This is tagged as PDO. If you really are using PDO and not mysqli then you cannot bind multiple parameters in a single statement as you are trying to. They should be declared individually and if you are using ? as placeholders they need to be numbered.
If you are using LIKE you must add the % signs to either side of the variable which you are going to bind, you cannot include them in your query as you are trying to.
As far as your query method, instead of trying to split your user input into first and last names why not concat the name fields from the database and search against the result of that instead?
SELECT * FROM students WHERE CONCAT_WS(' ', FirstName, LastName) LIKE '%whatever%';

Related

Autocomplete search by First Name and Last Name

I have created an autosuggestion search box using PHP and jQuery. The user is prompted to insert First name and Last name to find someone that exists in my database, in a table called customers. Table customers holds 2 columns, first_name and last_name.
My search works fine when you type the First name but after pressing space to move and type Last Name does not give any results. The whole problem seems to appear when pressing space button. Any idea how to fix it?
$(document).ready(function($){
$("#customers").autocomplete({
source: "fetch_customers.php?cc=<?php echo $agencyid; ?>",
minLength: 2,
select: function(event, ui) {
var code = ui.item.id;
if (code != '#') {
location.href = '/view-customer/' + code;
}
},
open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000);
}
});
});
<?php
$countrycode1 = $_GET['cc'];
$term = trim(strip_tags($_GET['term']));
$term = preg_replace('/\s+/', ' ', $term);
$a_json = array();
$a_json_row = array();
$a_json_invalid = array(array("id" => "#", "value" => $term, "label" => "Only letters and digits are permitted..."));
$json_invalid = json_encode($a_json_invalid);
if ($data = $conn->query("SELECT id, first_name, last_name FROM customers WHERE agency_id='$countrycode1' AND (first_name LIKE '%$term%' OR last_name LIKE '%$term%') ORDER BY first_name , last_name"))
{
while($row = mysqli_fetch_array($data))
{
$firstname = htmlentities(stripslashes($row['first_name']));
$lastname = htmlentities(stripslashes($row['last_name']));
$code = htmlentities(stripslashes($row['id']));
$a_json_row["id"] = $code;
$a_json_row["value"] = $firstname.' '.$lastname;
$a_json_row["label"] = $firstname.' '.$lastname;
array_push($a_json, $a_json_row);
}
}
/* jQuery wants JSON data */
$json = json_encode($a_json);
print $json;
flush();
$conn->close();
Split Your $term like this.
$splited_term = explode(" ",$term);
$first_term = $splited_term[0];
$last_term = (isset($splited_term[1]) && !empty($splited_term)) ? $splited_term[1] : null;
Generate your query according
$query = "SELECT id, first_name, last_name FROM customers WHERE agency_id='$countrycode1' AND ";
if(!empty($first_term)){
$query.= "(first_name LIKE '%$first_term%' OR last_name LIKE '%$first_term%'" ;
}
if(!empty($last_term)){
$query .= ((!empty($first_term)) ? " OR " : " ( " )." first_name LIKE '%$last_term%' OR last_name LIKE '%$last_term%')" ;
}
$query .= ((empty($last_term)) ? ")" : "")." ORDER BY first_name , last_name";
This will support
"Milind Patel"
"Patel Milind"
" Milind"
" Patel"
"Milind"
"Patel"
So Your code should be like this.
<?php
$countrycode1 = $_GET['cc'];
$term = trim(strip_tags($_GET['term']));
$term = preg_replace('/\s+/', ' ', $term);
$splited_term = explode(" ",$term);
$first_term = $splited_term[0];
$last_term = (isset($splited_term[1]) && !empty($splited_term)) ? $splited_term[1] : null;
$a_json = array();
$a_json_row = array();
$a_json_invalid = array(array("id" => "#", "value" => $term, "label" => "Only letters and digits are permitted..."));
$json_invalid = json_encode($a_json_invalid);
$query = "SELECT id, first_name, last_name FROM customers WHERE agency_id='$countrycode1' AND ";
if(!empty($first_term)){
$query.= "(first_name LIKE '%$first_term%' OR last_name LIKE '%$first_term%'" ;
}
if(!empty($last_term)){
$query .= ((!empty($first_term)) ? " OR " : " ( " )." first_name LIKE '%$last_term%' OR last_name LIKE '%$last_term%')" ;
}
$query .= ((empty($last_term)) ? ")" : "")." ORDER BY first_name , last_name";
if ($data = $conn->query($query))
{
while($row = mysqli_fetch_array($data))
{
$firstname = htmlentities(stripslashes($row['first_name']));
$lastname = htmlentities(stripslashes($row['last_name']));
$code = htmlentities(stripslashes($row['id']));
$a_json_row["id"] = $code;
$a_json_row["value"] = $firstname.' '.$lastname;
$a_json_row["label"] = $firstname.' '.$lastname;
array_push($a_json, $a_json_row);
}
}
/* jQuery wants JSON data */
$json = json_encode($a_json);
print $json;
flush();
$conn->close();

PHP Parameterized mysql statement with LIKE clause returns command out of sync

I am trying to use a LIKE clause with a parameterized query with php and mysql. Every time I try though, I'm getting different errors.
I've tried to implement solutions from here, here, and here. Each of these is throwing different errors, so I'm afraid the problem is in something that I'm missing. If I try with an array in the execute function, I get Command out of sync error. When I try binding values or parameters, I'm getting a can't bind on string error.
I'm at a loss for what I'm missing.
Thanks for any help!
<?
$access = 3;
$dbConnect = true;
require "../scripts/php/scriptSecurity.php";
// Partial name given by user.
$namePart = $_GET["namePart"];
// Deal with name parts. last, first middle or first middle last, or first last
if (strpos($namePart, ',') !== false){
$arr_name = explode(",", $namePart);
$lName = $arr_name[0];
if (strpos($arr_name[1], " ") !== false){
$firstName = substr($arr_name[1], 0, strpos($arr_name[1], " ", 1));
$middleName = substr($arr_name[1], strpos($arr_name[1], " ", 1));
}
}
elseif (strpos($namePart, " ") !== false){
$arr_name = explode(" ", $namePart);
if (sizeOf($arr_name) == 3) {
$fName = $arr_name[0];
$lName = $arr_name[3];
$mName = $arr_name[2];
}
elseif (sizeOf(arr_name) == 2) {
$fName = $arr_name[0];
$lName = $arr_name[1];
$mName = $arr_name[1];
}
else {
$fName = $namePart;
$mName = $namePart;
$lName = $namePart;
}
}
else {
$fName = $namePart;
$lName = $namePart;
$mName = $namePart;
}
// Get rid of extra spaces.
$fName = str_replace(" ", "", $fName);
$lName = str_replace(" ", "", $lName);
$mName = str_replace(" ", "", $mName);
// build query
$query = "SELECT LastName, FirstName, MiddleName, StudentId, Gender, Grade, GradYear FROM students WHERE LastName LIKE ? OR FirstName LIKE ? OR MiddleName LIKE ? ORDER BY LastName, FirstName LIMIT 20";
$stmt = $connect->prepare($query);
// execute
$stmt->execute(array('%'.$lName.'%', '%'.$fName.'%', '%'.$mName.'%'));
$result = $stmt->get_result();
// post results
if (!$result) {
echo $connect->error;
echo "No Results";
}
else {
echo "Results";
while ($row = $result->fetch_assoc()){
?>
<div><? echo $row["LastName"] . ", " . $row["FirstName"] . "(" . $row["StudentId"] . ")"?> </div>
<?php
}
}
?>
You pass the string in param with wildchar in wrong way you can use a simplest way managing the wildchar with concat and assign the pure var as param
$query = "SELECT LastName, FirstName, MiddleName, StudentId, Gender, Grade, GradYear
FROM students
WHERE LastName LIKE concat('%',?, '%')
OR FirstName LIKE concat('%',?, '%')
OR MiddleName LIKE concat('%',?, '%')
ORDER BY LastName, FirstName
LIMIT 20";
$stmt = $connect->prepare($query);
// execute
$stmt->execute(array($lName, $fName, $mName));

Php search query with range filter

I am trying to do a search query, but not sure how to put everything together. I am having problem with the range filter part.
What i am trying to achieve:
A search form that
1.) If field A,B(not empty) then put in the search query
2.) search through price column with (price lower range, price higher range)
include the results if it matches Field A,B(if it is not empty) and price(if it is in range).
(if search Fields A, B are empty then display all results that exist between range).
Thanks for your time.
The codes that i have now.
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
session_start();
include 'connect.php';
if($_POST)
{
$A = ($_POST['A']);
$B = ($_POST['B']);
$C = ($_POST['C']);
$pricelow = ($_POST['pricelow']);
$pricehigh = ($_POST['pricehigh']);
$sql = array();
if (!empty($A)) {
$sql[] = "A='$A'";
}
if (!empty($B)) {
$sql[] = "B='$B'";
}
if (!empty($C)) {
$sql[] = "C='$C'";
}
if (!empty($price)) {
for($i = pricelow; $i<pricehigh; $i++){
$price = $i;
}
$sql[] = "price='$price'";
$sql = implode(' AND ', $sql);
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . $sql: '');
$result = mysqli_query($con,$sql);
$output = array();
// fetch your results
while( $row = mysqli_fetch_assoc($result) )
{
// add result row to your output's next index
$output[] = $row;
}
// echo the json encoded object
echo json_encode( $output );
}
?>
Edit:
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . $sql: '') . ("AND" 'price' BETWEEN "$pricelow" AND "$pricehigh");
Edit:
if (!empty($pricelow) || !empty($pricehigh)) {
$sql[] = $pricehigh>= 'price' and 'price'>=$pricelow ;
}
$sql = array();
$sql = implode(' AND ', $sql);
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . implode(" AND ", $sql): '');
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
session_start();
include 'connect.php';
if($_POST)
{
$A = ($_POST['A']);
$B = ($_POST['B']);
$C = ($_POST['C']);
$pricelow = ($_POST['pricelow']);
$pricehigh = ($_POST['pricehigh']);
$query = "SELECT * FROM Listing WHERE ";
$flag = 0;
if (!empty($A)) {
$query .= $flag==0?" A='$A' ":" AND A = '$A'";
$flag = 1;
}
if (!empty($B)) {
$query .= $flag==0?" B = '$B' ":" AND B = '$B'";
$flag = 1;
}
if (!empty($C)) {
$query .= $flag==0?" C='$C' ":" AND C= '$C'";
$flag = 1;
}
if ($flag == 0) {
$query .= " price > $pricelow AND price > $pricehigh"
}
$result = mysqli_query($con,$query);
$output = array();
// fetch your results
while( $row = mysqli_fetch_assoc($result) )
{
// add result row to your output's next index
$output[] = $row;
}
//your rest of the code
>?
I can't test it so, try and report the result!
You are creating an array of conditions and later you try to use that array as a string. This will not work, as the generated query is invalid. Take a look here, implode is a function which implodes an array using a separator. If you use " AND " as separator, then you will get the string you have desired. So, instead of:
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . $sql: '');
do the following:
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . implode(" AND ", $sql): '');
and your problem should be solved.
EDIT:
I have read your edit and I mean this code in particular:
if (!empty($pricelow) || !empty($pricehigh)) {
$sql[] = $pricehigh>= 'price' and 'price'>=$pricelow ;
}
$sql = array();
$sql = implode(' AND ', $sql);
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . implode(" AND ", $sql): '');
After you build your array you are initializing it again, thus you lose all information you have processed earlier. Then you implode it twice, which is not needed. Try this way:
if (!empty($pricelow) || !empty($pricehigh)) {
$sql[] = $pricehigh>= 'price' and 'price'>=$pricelow ;
}
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . implode(" AND ", $sql): '');

Multi word search in PHP/MySQL

I'm struggling to create a search that searches for multiple words. My first attempt yielded no results whatsoever and is as follows:
require_once('database_conn.php');
if($_POST){
$explodedSearch = explode (" ", $_POST['quickSearch']);
foreach($explodedSearch as $search){
$query = "SELECT *
FROM jobseeker
WHERE forename like '%$search%' or surname like '%$search%'
ORDER BY userID
LIMIT 5";
$result = mysql_query($query);
}
while($userData=mysql_fetch_array($result)){
$forename=$userData['forename'];
$surname=$userData['surname'];
$profPic=$userData['profilePicture'];
$location=$userData['location'];
echo "<div class=\"result\">
<img class=\"quickImage\" src=\"" . $profPic. "\" width=\"45\" height=\"45\"/>
<p class=\"quickName\">" . $forename . " " . $surname . "</p>
<p class=\"quickLocation\"> " . $location . "</p>
</div>";
}
}
I also tried the following, which yielded results, but as you can imagine, I was getting duplicate results for every word I entered:
if($_POST){
$explodedSearch = explode (" ", $_POST['quickSearch']);
foreach($explodedSearch as $search){
$query = "SELECT *
FROM jobseeker
WHERE forename like '%$search%' or surname like '%$search%'
ORDER BY userID
LIMIT 5";
$result .= mysql_query($query);
while($userData=mysql_fetch_array($result)){
$forename=$userData['forename'];
$surname=$userData['surname'];
$profPic=$userData['profilePicture'];
$location=$userData['location'];
echo "<div class=\"result\">
<img class=\"quickImage\" src=\"" . $profPic. "\" width=\"45\" height=\"45\"/>
<p class=\"quickName\">" . $forename . " " . $surname . "</p>
<p class=\"quickLocation\"> " . $location . "</p>
</div>";
}
}
}
I'm pretty much at a loss as to how to proceed with this, any help would be greatly appreciated.
EDIT:
if($_POST){
$quickSearch = $_POST['quickSearch'];
$explodedSearch = explode (" ", trim($quickSearch));
$queryArray = array();
foreach($explodedSearch as $search){
$term = mysql_real_escape_string($search);
$queryArray[] = "forename like '%" . $term . "%' surname like '%" . $term . "%'";
}
$implodedSearch = implode(' or ', $queryArray);
$query="SELECT *
FROM jobseeker
WHERE ($implodedSearch)
ORDER BY userID
LIMIT 5";
$result = mysql_query($query);
while($userData=mysql_fetch_array($result, MYSQL_ASSOC)){
$forename=$userData['forename'];
$surname=$userData['surname'];
$profPic=$userData['profilePicture'];
$location=$userData['location'];
echo "<div class=\"result\">
<img class=\"quickImage\" src=\"" . $profPic. "\" width=\"45\" height=\"45\"/>
<p class=\"quickName\">" . $forename . " " . $surname . "</p>
<p class=\"quickLocation\"> " . $location . "</p>
</div>";
}
}
I've been working on the same subject (search with keywords) for a while and this how i did it :
$words = $_POST['keywords'];
if(empty($words)){
//redirect somewhere else!
}
$parts = explode(" ",trim($words));
$clauses=array();
foreach ($parts as $part){
//function_description in my case , replace it with whatever u want in ur table
$clauses[]="function_description LIKE '%" . mysql_real_escape_string($part) . "%'";
}
$clause=implode(' OR ' ,$clauses);
//select your condition and add "AND ($clauses)" .
$sql="SELECT *
FROM functions
WHERE
user_name='{$user_name}'
AND ($clause) ";
$results=mysql_query($sql,$connection);
if(!$results){
redirect("errors/error_db.html");
}
else if($results){
$rows = array();
<?php
while($rows = mysql_fetch_array($results, MYSQL_ASSOC))
{
// echo whatever u want !
}
?>
-- Now this is how it look when i tried to run it with FULLTEXT search :
But you should set the table type as "MyISAM"
<?php
$words = mysql_real_escape_string($_POST['function_keywords']);
if(empty($words)){
redirect("welcome.php?error=search_empty");
}
//if the columns(results)>1/2(columns) => it will return nothing!(use "NATURAL LANGUAGE"="BOOLEAN")
$sql="SELECT * FROM functions
WHERE MATCH (function_description)
AGAINST ('{$words}' IN NATURAL LANGUAGE MODE)";
$results=mysql_query($sql,$connection);
if(!$results){
redirect("errors/error_db.html");
}
else if($results){
$rows = array();
while($rows = mysql_fetch_array($results, MYSQL_ASSOC))
{
// echo
}
}
?>
Perhaps what you are looking for is a MySQL full-text search.
For your example, you could do something like:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$search = $_POST['quickSearch'];
// Todo: escape $search
$sql = "
SELECT
*,
MATCH (`forename`)
AGAINST ('{$search}' IN NATURAL LANGUAGE MODE) AS `score`
FROM `jobseeker`
WHERE
MATCH (`forename`)
AGAINST ('{$search}' IN NATURAL LANGUAGE MODE)";
// Todo: execute query and gather results
}
Note that you will need to add a FULLTEXT index to the column forename.
Take a look at MySQL fulltext searches, if you must use MySQL. Otherwise take a look at SOLR, which is a fulltext search engine. You can use MySQL and SOLR in combination to provide enterprise level search capabilities for your apps.
here's what i did
if (isset($_POST['search'])){
$words = mysql_real_escape_string($_POST['searchfield']);
$arraySearch = explode(" ", trim($words));
$countSearch = count($arraySearch);
$a = 0;
$query = "SELECT * FROM parts WHERE ";
$quote = "'";
while ($a < $countSearch)
{
$query = $query."description LIKE $quote%$arraySearch[$a]%$quote ";
$a++;
if ($a < $countSearch)
{
$query = $query." AND ";
}
}
$result=mysql_query($query) or die(error);
//you could just leave it here, short and sweet but i added some extra code for if it doesnt turn up any results then it searches for either word rather than boths words//
$num = mysql_num_rows($result);
if ($num == 0){
$a = 0;
$query = "SELECT * FROM parts WHERE ";
while ($a < $countSearch)
{
$query = $query."description LIKE $quote%$arraySearch[$a]%$quote ";
$a++;
if ($a < $countSearch)
{
$query = $query." OR ";
$msg = "No exact match for: $words. Maybe this is what you're looking for though? If not please try again.";
}
}
}
$result=mysql_query($query) or die($query);
if (mysql_num_rows($result) == 0){
$msg = "No results, please try another search";
}
}

mysql search using for loop from php

i am a beginner. but I'm practicing a lot for few days with php mysql, and I am trying to use for loop to search an exploded string, one by one from mysql server.
Till now I have no results.
I'm giving my codes,
<?php
// Example 1
$var = #$_GET['s'] ;
$limit=500;
echo " ";
echo "$var";
echo " ";
$trimmed_array = explode(" ", $var);
echo "$trimmed_array[0]"; // piece1
echo " ";
$count= count($trimmed_array);
echo $count;
for($j=0;$j<$count;$j++)
{
e cho "$trimmed_array[$j]";;
echo " ";
}
echo " ";
for($i=0; $i<$count ; $i++){
$query = "select * from book where name like \"%$trimmed_array[$i]%\" order by name";
$numresults=mysql_query($query);
$numrows =mysql_num_rows($numresults);
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed_array[i] . "" returned zero results</p>";
}
if (empty($s)) {
$s=0;
}
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
echo "<p>You searched for: "" . $var . ""</p>";
echo "Results<br /><br />";
$count=1;
while ($row= mysql_fetch_array($result)) {
$name = $row["name"];
$publisher=$row["publisher"];
$total=$row["total"];
$issued=$row["issued"];
$available=$row["available"];
$category=$row["category"];
echo "<table border='1'><tr><td>$count)</td><td>$name </td><td>$publisher </td><td>$total </td><td>$issued </td><td>$available </td><td>$category </td></tr></table>" ;
$count++ ;
}
}
?>
In your case, you do for every record in your array ($trimmed_array) a new select. Thats not really good.
It would be better when you create just one select...
For example this:
// you need 1=1 for example when $i<count is false...
$baseQuery = "select * from book where 1=1";
$query = $baseQuery;
for($i=0; $i<$count ; $i++){
$query .= " OR name like ?";
}
// do your ordering:
$query.= " order by name";
But what does this "?" mean?
--> Do you know what sql-injection means? somebody could really easy put some information in this array wich could give any information about your database.. therefore you have to escape every userinput...
i like the mysqli package in php5. watch this example:
$query = "SELECT `id` FROM employees WHERE `name`=?";
// Setup parameter to be bound into query
$name = "Joey";
// Get instance of statement
$stmt = $mysqli->stmt_init();
// Prepare Query
if($stmt->prepare($query)){
// Bind Parameters [s for string]
$stmt->bind_param("s",$name);
// Execute statement
$stmt->execute();
// Bind result variables
$stmt->bind_result($employee_id);
// Fetch Value
$stmt->fetch();
// Echo results
echo "$name has an ID of $employee_id";
// Close Statement
$stmt->close();
}
Damn, your code really extremely crazy. Here you example about how to work with this:
<?php
$var = $_GET['s'];
$exp = explode(" ",$var);
$total = count($exp) - 1;
for($i = 0; $i <= $total; $i++) {
echo "Search for: " . $exp[$i] ."\n";
$sql = mysql_query("SELECT * FROM `book` WHERE `name` LIKE '%" . mysql_real_escape_string($exp[$i]) ."%'") or die(mysql_error());
if (mysql_fetch_num($sql) != 0) {
// Somthing found
}
}
?>
You have an error on line 25,
e cho "$trimmed_array[$j]";;
should be
echo "$trimmed_array[$j]";
Also, it seems that you are using $GET_[] variables, which are passed via the url string, which does not allow spaces. On line 15, you are splitting the array with explode(" ", $var);
I would also urge you, if you have not, look into sanitizing your database queries.

Categories