Search a MySQL table in PHP - php

I am building a script where a user can query (search) a MySQL database.
The user firstly selects the table from a drop down list, and then they can choose upto 4 'filters' for example userID=001.
Here is my code:
$con=mysqli_connect("localhost","Username","Password","DBname");
// Check connection
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT * FROM ".$table." WHERE 1=1 ";
if($filter1 != "" or $filter1v != "" )
{
$query .= " and $filter1 LIKE'%$filter1v%'";
}
if($filter2 != "" or $filter2v != "" )
{
$query .= " and $filter2 LIKE'%$filter2v%'";
}
if($filter3 != "" or $filter3v != "" )
{
$query .= " and $filter3 LIKE'%$filter3v%'";
}
if($filter4 != "" or $filter4v != "")
{
$query .= " and $filter4 LIKE'%$filter4v%'";
}
$query .= ";";
$resultRAW = mysqli_query($con, $query);
echo mysqli_error($con);
$result = array();
while($data = mysqli_fetch_array($resultRAW, MYSQLI_ASSOC))
{
$result[] = $data;
}
echo "<table class='table table-striped' id='tableWithExportOptions'>";
$amountRows = count($result);
for($i = 0; $i < $amountRows; $i++)
{
$keys = array_keys($result[$i]);
$amountColumns = count($keys);
if ($i == 0)
{
echo "<thead><tr>";
//I replaced the foreach clause because of performance reasons but they would work as well
for($j = 0; $j < $amountColumns; $j++)
{
echo "<th>".$keys[$j]."</th>";
}
echo "</tr></thead>";
}
echo "<tr>";
for($j = 0; $j < $amountColumns; $j++)
{
echo "<th>".$result[$i][$keys[$j]]."</th>";
}
echo "</tr>";
}
echo "</table>";
?>
If the user doesn't choose any filters the script works fine, however when using a filter it doesn't show any results?

Depending on your database this may vary. But you can not append a string to the result. $result is a MySQL Result object. You need to fetch the result for example with this code:
$array = array();
while($data = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$array[] = $data;
}
Then you can work with your result array $array and do whatever you want to do
If you want to create a query this way you need to call the mysqli_query later and build the query which could look like this:
$con = mysqli_connect("localhost","Username","Password","DBname");
// Check connection
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$query = "SELECT * FROM ".$table." WHERE 1=1 ";
if($field != "" or $fieldvalue != "" )
{
$query .= " and ".$field." LIKE'%".$fieldvalue."%'";
}
if($filter1 != "" or $filter1value != "" )
{
$query .= " and ".$filter1." LIKE'%".$filter1value."%'";
}
if($filter2 != "" or $filter2value != "" )
{
$query .= " and ".$filter2." LIKE'%".$filter2value."%'";
}
if($filter3 != "" or $filter3value != "" )
{
$query .= " and ".$filter3." LIKE'%".$filter3value."%'";
}
if($filter4 != "" or $filter4value != "")
{
$query .= " and ".$filter4." LIKE'%".$filter4value."%'";
}
$query .= ";";
$resultRAW = mysqli_query($con, $query);
$result = array();
while($data = mysqli_fetch_array($resultRAW, MYSQLI_ASSOC))
{
$result[] = $data;
}
And I would be extremely careful with $table. in the query. This looks like a very good point to start an SQL Inejction attack. To prevent those I recomment the use of prepared statements. More can be found here: Prevent SQL Injection.
Unfortunalty this does not work with tablenames so you need to manually test it for any malicios input. If you "trust" this variable then it might be ok but if it is a use rinput I would AT LEAST call:
$table = mysqli_real_escape_string($table);
EDIT:
echo "<table class='table table-striped' id='tableWithExportOptions'>";
$amountRows = count($result);
for($i = 0; $i < $amountRows; $i++)
{
$keys = array_keys($result[$i]);
$amountColumns = count($keys);
if ($i == 0)
{
echo "<thead><tr>";
//I replaced the foreach clause because of performance reasons but they would work as well
for($j = 0; $j < $amountColumns; $j++)
{
echo "<th>".$keys[$j]."</th>";
}
echo "</tr></thead>";
}
echo "<tr>";
for($j = 0; $j < $amountColumns; $j++)
{
echo "<th>".$result[$i][$keys[$j]]."</th>";
}
echo "</tr>";
}
echo "</table>";
If this does not work please tell me, I have not tested this.

Because you concatenate string to $result = mysqli_query
$result = "SELECT * FROM $table WHERE 1=1";
if ($field != "" or $fieldvalue != "") {
$result .= " and $field LIKE'%$fieldvalue%'";
}
if ($filter1 != "" or $filter1value != "") {
$result .= " and $filter1 LIKE'%$filter1value%'";
}
if ($filter2 != "" or $filter2value != "") {
$result .= " and $filter2 LIKE'%$filter2value%'";
}
if ($filter3 != "" or $filter3value != "") {
$result .= " and $filter3 LIKE'%$filter3value%'";
}
if ($filter4 != "" or $filter4value != "") {
$result .= " and $filter4 LIKE'%$filter4value%'";
}
mysqli_query($con, $result);

Few things I can see that give me pause here.
But firstly, to Answer your question:
The mysqli_query(); method executes the query you pass to it. In your code you're executing the basic query with mysqli_query(); before you check for and add the filters and their values. So no matter what the user selects on your drop downs, that query without filters will always be executed first. You need to build your whole query string first, then execute the query with mysqli_query(); after all the checking and possible additions to your query.
Additionally, things that might break things later on:
Also, you might want to use and/&& in your if statements. or like you have it will allow your SELECT statement to break if you have the $filter1value populated with a value and $filter1 not, it will test true in your if and the WHERE clause will be concatenated to your query with a value but no field.
TIPS: echo your SQL command out to see what your php code has generated to see if it's valid SQL before running it while you develop.
Myself and many other PHP developers prefer to use PDO to interact with Databases personally, but that's just my preference.
I wanted to give you a code example of how I would have done it, but I honestly would change too much of your code, so I left it.
Side-note: I'm not sure what levels of security you have on the inputs but what you're doing by including your input variables directly into you SQL command string like that leaves you open to SQL injection attacks. Very dangerous depending on who will be able to access your script. Perhaps try using a prepared statement with parameters to keep security up a bit. Please look at mysqli_prepare(); it's friend, the mysqli_stmt_bind_param(); method in this case where you're using mysqli. Always use prepared statements on the database libraries you use if you're accepting external inputs to your system. It'll save your job one day.
Just my two cents use it, don't use it. :)

I guess you should add the filters on the query string before you execute the query, instead of adding the filter to the results? E.g.
$query = "SELECT * FROM $table WHERE 1=1";
if (...) {
$query .= ...
}
// some more ifs...
$result = mysqli_query($con, $query);

Related

possible ?: mysql row to an if condition

hi guys im trying to insert a mysql data to a variable that will set an if condition depending on the result. is this possible, am i doing it right? what is the right way to do it ? what i want to achieve is to validate if there's a equal value given by the user inside my mysql rows.
$db = mysql_connect('localhost','test','');
if (!$db)
{
print "<h1>Unable to Connect to MySQL</h1>";
}
$dbname = 'test';
$btest = mysql_select_db($dbname);
if (!$btest)
{
print "<h1>Unable to Select the Database</h1>";
}
$sql_statement = "SELECT * ";
$sql_statement .= "FROM registered_email ";
$result = mysql_query($sql_statement);
$outputDisplay = "";
$myrowcount = 0;
if (!$result) {
$outputDisplay .= "<br /><font color=red>MySQL No: ".mysql_errno();
$outputDisplay .= "<br />MySQL Error: ".mysql_error();
$outputDisplay .= "<br />SQL Statement: ".$sql_statement;
$outputDisplay .= "<br />MySQL Affected Rows: ".mysql_affected_rows()."</font><br />";
}
else{
$numresults = mysql_num_rows($result);
for ($i = 0; $i < $numresults; $i++)
{
$row = mysql_fetch_array($result);
$id = $row['id'];
$sentEmailClients = $row['email'];
$outputDisplay.= "".$sentEmailClients."<br />";
}
}
and here what im trying to achieve, btw is $clientEmail has a default values so dont worry about that.
if($clientEmail === $outputDisplay){
...... some codes..........
}
else{
....... some codes.......
}
you can use mysql row to compare with your user input. you can add condition, while you'r getting row value for the email inside the loop.
$email_exist = 0;//define the default value.
for ($i = 0; $i < $numresults; $i++)
{
$row = mysql_fetch_array($result);
$id = $row['id'];
$sentEmailClients = $row['email'];
$outputDisplay.= "".$sentEmailClients."<br />";
//my code start here
if($sentEmailClients == $clientEmail)
$email_exist = 1;
}
//outside the loop
if($email_exist == 1) {
//..........write some code.......
}else{
//........write some code.......
}
why don't you use a while loop?
make sure to update to mysqli_* because mysql_* is deprecated and is going to get removed on php 7.0
$email_exist = 0;//define the default value.
while ( $row = mysql_fetch_assoc($result) ) // you are using associative array and not the indexed once tho you should go for mysql_fetch_assoc
{
$id = $row['id'];
$sentEmailClients = $row['email'];
$outputDisplay.= "".$sentEmailClients."<br />";
//my code start here
if($sentEmailClients == $clientEmail)
$email_exist += 1; //maybe it exist more than once?
}
//outside the loop
if($email_exist == 1) {
//..........write some code.......
}else{
//........write some code.......
}
or you can do something more simple like this
$query = "select email from tablename where email='$clientemail'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count > 0) {
// email exists
} else {
// doesn't exist
}

Browser hangs and crashes when using a while loop

I am executing two queries and evaluating the following conditions for each record:
if $production_query->row->0 is equal to $jobcard_query->row->0
if $production_query->row->1 is equal to $jobcard_query->row->1
When true, it should display the results of $production_query.
However, when using a while statement, the browser takes a long time to respond and crashes.
Can anyone suggest a solution?
My code:
$query = " SELECT job_card_num , die_qty,id FROM sample_jobcard ORDER BY id DESC”
$production_query = mysql_query($query,$connection1);
$query1 = "SELECT job_card_num , die_qty,id FROM com_jobcard ORDER BY id DESC ";
$jobcard_query = mysql_query($query1,$connection1);
while ($row = mysql_fetch_array($production_query))
{
while( $row1 = mysql_fetch_array($jobcard_query))
{
while (($row1[0] == $row[0]) && ($row1[1] == $row[1]))
{
echo $row[0] . $row[1]. $row[2]'<br>';
}
}
}
Try changing the query to something like this:
$query = "SELECT sample_jobcard.job_card_num AS JOBCARDNUM, sample_jobcard.die_qty AS DIEQTY, sample_jobcard.id AS JID, com_jobcard.job_card_num, com_jobcard.die_qty, com_jobcard.id FROM sample_jobcard
join com_jobcard on sample_jobcard.job_card_num = com_jobcard.job_card_num AND sample_jobcard.die_qty = com_jobcard.die_qty ORDER BY sample_jobcard.id DESC";
$jobcard_query = mysql_query($query);
if($jobcard_query && mysql_num_rows($jobcard_query) > 0)
{
while ($row = mysql_fetch_array($jobcard_query))
{
echo $row['JOBCARDNUM']." ".$row['DIEQTY']." ".$row['JID']."<br>";
}
}
Replace while:
while (($row1[0] == $row[0]) && ($row1[1] == $row[1]))
{
echo $row[0] . $row[1]. $row[2]'<br>';
}
With if:
if ($row1[0] == $row[0] && $row1[1] == $row[1])
{
echo $row[0] . $row[1]. $row[2] . '<br>';
}
If your conditions ever evaluate as true, you have essentially written:
while(true) {
// run forever
}
This will run forever (well, until maximum execution time).
You end up printing the same line over and over, producing a large document that your browser has difficulty handling, inducing a crash.

how to use php to select value from a table use some keys

I want to write a function which takes 2 parameters: one is a table name and another one is a associative array of keys. Now I have a function:
// returns an assoc array with all info in $table for given $keyValues
function getAllFrom($table,$keyValues){
$qry="SELECT * FROM ". $table;
$i=sizeof($keyValues);
foreach($keyValues as $key=>$val) {
if($i==1) $qry.=" WHERE ".$key."=".$keyValues[$key]." ";
else $qry.=" AND ".$key."=".$keyValues[$key]." ";
$i++;
}
//echo " query is : ".$qry;
$result=mysql_query($qry) or die("Query $qry failed.");
if($results= mysql_fetch_assoc($result))
return $results;
else return false;
} // end getAllFrom
But it is not work. Could anyone help me modify this and tell me what's foreach($keyValues as $key=>$val) mean? I am confused.
Thanks!
You code can be solved, but I would rather tell you to not try to solve that specific code, since it is an old deprecated solution that you want to remove asap later on.
What you want to do is to use the PDO adapter http://php.net/manual/en/class.pdo.php
Benefits from doing this is that you get protection from all the evils lurking in user input, and also you get a lot of nice abstractions solving exactly the problem you described.
This is a function I use to do this in my code, it might look a bit advanced but if you consult the manual you shouldn't have a problem solving it.
public function select( $table, array $conditions )
{
$where = array();
foreach ( $conditions as $col => $value )
{
$input[":" . $col] = $value;
$where[] = $col." = :" . $col;
}
$sql = "SELECT FROM " . $table
. " WHERE ".implode("AND", $where);
return (int) $this->prepare( $sql )
->execute( $conditions )
->getLastInsertId();
}
To understand Foreach loops I would read the manual http://php.net/manual/en/control-structures.foreach.php
Another built in function I would recommend you looking into is the http://php.net/manual/en/function.implode.php
You may give this a try:
function getAllFrom($table,$keyValues=null){
$qry="SELECT * FROM ". $table . " WHERE 1 " ;
if($keyValues){
foreach($keyValues as $key=>$val) {
$qry.=" AND ".$key."=".$keyValues[$key]." ";
}
}
$result=mysql_query($qry) or die("Query $qry failed.");
if($results= mysql_fetch_assoc($result)){
return $results;
}else{
return false;
}
}
You have understood the concept of foreach($keyValues as $key=>$val) correctly meaning if there is an associative array say
$testArr = array("key1"=>"val1","key2"=>"val2","key3"=>"val3")
then in each iteration of "foreach($keyValues as $key=>$val)"
$key would take values key1,key2,key3 and $val would take val2,val2 and val3 respectively.
Your query wont work because $i initially will not have value as 1 but it will have length of the associative array i.e. if $testArr is taken then it will have $i = 3. Your current query looks like this
$qry = AND key1 = val1 AND key2 = val2 AND key3 =val3
, since if($i == 1) is never satisfied.
Also remember if values is a string then we need to have quotes around them so Try the below for the query you expect
$i=1;
foreach($keyValues as $key=>$val)
{
if($i==1)
{
$qry.=" WHERE ".$key."='".$keyValues[$key]."' "; //the ' have to be included if value is a string and not number
$i = 0;
}
else
{
$qry.=" AND ".$key."='".$keyValues[$key]."' ";
}
}
Try this :
getAllFrom($table,$keyValues){
$qry="SELECT * FROM ". $table;
$i=0;
if(count($keyValues > 0)){
foreach($keyValues as $key=>$val) {
if($i==0) $qry.=" WHERE ".$key."=".$val." ";
else $qry.=" AND ".$key."=".$val." ";
$i++;
}
}
//echo " query is : ".$qry;
$result=mysql_query($qry) or die("Query $qry failed.");
if($results= mysql_fetch_assoc($result))
return $results;
else return false;
} // end getAllFrom
if this helps dont froget to accept answer.
if i am not wrong, you actually need dynamic SQL Query based on your keyValue array parameters.
$sqlQuery ='SELECT * FROM '.$table;
$whereCondition='';
foreach($keyValues as $key=>$val) {
if($whereCondition =='')
$whereCondition .= " WHERE ".$key."=".$val." ";
else
$whereCondition .=" AND ".$key."=".$val." ";
}
if($whereCondition !='')
$sqlQuery .= $whereCondition;
Note:please be sure about your where condition values.
Function
The function now returns multi dimensional array of all result rows. (your function returns only one result row even if have multiple results.)
function getAllFrom ($table,$keyValues)
{
$returnArray = array();
$qry = "SELECT * FROM ". $table;
if (count($keyValues) > 0)
{
$qry .= " WHERE ";
foreach ($keyValues as $key=>$val)
{
$qry.= $key."=".$keyValues[$key]." AND ";
}
$qry = rtrim($qry, " AND ");
} //echo "query is : ".$qry."<br />";
$result = mysql_query($qry);
if (mysql_num_rows($result) > 0)
{
while ($results = mysql_fetch_assoc($result))
{
$returnArray[] = $results;
}
}
return $returnArray;
} // end getAllFrom
Function Call
$keyValues = array();
$keyValues['status'] = "'active'";
$keyValues['id'] = "'12'";
$resultArray = getAllFrom('products', $keyValues);
echo '<pre>';
print_r($resultArray);
echo '</pre>';
Notes
$keyValues stores the query conditions. If this parameter is null ($keyValues = array()), function return all the rows

Trouble pulling data out of an sql table

I have a html form tat my user can use to search through a table in my MYSQL database.
By default if you just hit go it will display the entire table, however I would like them to be able select certain fields and my php form to search via the fields that are filled in.
I seem to be unable to find a way of doing this without writing a seperate query for all 11 inputs in the different combinations they could be entered in, which comes out at a total of 76 queries..
If anyone has a way to simplify this I would love any advice.
I have tried just running a query with the AND operator but that doesnt work as some variables can be left empty and that will return no result, not sure if that is what is upposed to happen, but that is what is happening.
my html and php:
http://jsbin.com/oquwid/1/edit
PHP
$sql = "SELECT * FROM ".$tbl_name."
WHERE fname='".$fname."'
and lname='".$lname."'
and city='".$city."'
and phone='".$pohne."'
and interest_inet='".$internet."'
and interest_tv='".$television."'
and interest_voice='".$voice."'
and submission_ip='".$ip."'
and inquiry_handled='".$handled."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
echo $row;
}
echo "</table>";
You could append parts to the query depending on which are filled in:
if(!empty($fname) || !empty($lname) || !empty($city) || etc.etc.) {
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryParts = array();
if($fname != "") {
$queryParts[] = " fname='$fname'";
}
if($lname != "") {
$queryParts[] = " lname='$lname'";
}
etc.etc.
$sql .= implode(" AND ", $queryParts);
// do query, etc.
}
else {
// Don't do query if no parameters are specified
}
You also need to make sure that you escape all of your query parameters before you use them or risk having someone ravage your data.
The following uses loops to avoid duplicate code:
$fieldIsSpecified = false;
$queryFields = array('fname' => $fname, 'lname' => $lname, 'city' => $city, etc...);
foreach($queryFields as $column => $value) {
if(!empty($value){
$fieldIsSpecified = true;
break;
}
}
if($fieldIsSpecified) {
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryParts = array();
foreach($queryFields as $column => $value) {
if(!empty($value)) {
$queryParts[] = " $column = '$value'";
}
}
$sql .= implode(" AND ", $queryParts);
// do query, etc.
}
else {
// Don't do query if no parameters are specified
}
The reason you're query isn't working if a value is not filled in, is probably because the query results in this (given first name is empty)
SELECT * FROM $tbl_name WHERE fname=''
And there probably isn't a user having no first name.
Further, you considered adding a flag per requested info, and on base of that either add or remove the needed part to the select part of the query ?
For example,
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryChanged = false;
if (isset($fname)){
if (!empty($fname)){
$sql .= "fname='$fname' ";
$queryChanged=true;
}
}
if (isset($lname)){
if (!empty($lname)){
$sql .= ($queryChanged) ? " AND lname='$lname'" : "lname='$lname'";
$queryChanged = true;
}
}
... //Continue the logic
I'd recommend you to read this post about select * as well as this about user input and how to handle it
this is how i am going to have to do it
php:`
//if just lname is set
if(empty($start_date) && empty($end_date) && empty($fname) && isset($lname) && empty($city) &&
empty($internet) && empty($television) && empty($voice) && empty($phone) && empty($ip) &&
empty($handled) && empty($not_handled)){
$sql = "SELECT * FROM ".$tbl_name."
WHERE lname='".$lname."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
}
echo "</table>";
exit();
}
//if just city is selected
if(empty($start_date) && empty($end_date) && empty($fname) && empty($lname) && isset($city) &&
empty($internet) && empty($television) && empty($voice) && empty($phone) && empty($ip) &&
empty($handled) && empty($not_handled)){
$sql = "SELECT * FROM ".$tbl_name."
WHERE city='".$city."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
}
echo "</table>";
exit();
}
And etc... i am going to have to repeat this process until i cover all, 76 i believe, possibilites. thnkfully its just a lot of copy paste. thanks for the help everyone
First don't use MYSQL_*. Use PDO
Second, with your code, your are requiring all fields to be filled.
If you don't wanna do that then go this way:
You can use WHERE 1=1 , but it's not recommended !!!!!
$sql = "SELECT * FROM ".$tbl_name." WHERE confirm = '0' ";
$sql .= "AND fname = ".$fname."";
$sql .= "AND lname = ".$lname."";
$sql .= "AND city = ".$city."";
$sql .= "AND phone = ".$pohne."";
$sql .= "ORDER BY date DESC";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
echo $row;
}
echo "</table>";

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