jquery autocomplete with php file that queries a mysql database - php

i'm trying to use a jquery autocomplete text-input with a mysql database for autocomplete suggestions. From a tutorial i got the following php function that is used to query a database.
<?php
include "db_connect.php";
$search = protect($_GET['term']);
$result = mysql_query("SELECT planeID FROM `planes` WHERE `planeID` LIKE '%$search%' ")
or die('Something went wrong');
$json = '[';
$first = true;
while ($row = mysql_fetch_assoc($result))
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['planeID'].'"}';
}
$json .= ']';
echo $json;
within the chrome networkpanel, i can see, that after each input into my textfield a request to "suggest_planeID.php?term=d-" i sent but i don't reveive any suggestion.
the database looks like this:
i have ha DatatBase called "test" with a table caled "planes" inside. This table has two columns 'planeID' and 'planeType".
is there any chance to debug the php file to find the error or does anyone here already see the error?

Related

How to highlight user input in mysql search results using php?

I have added my code below, i am new to php and mysql and trying to search mysql using php based on user inputs and working really fine. But not sure how to highlight the user input value while displaying from mysql.
$output = NULL;
if(isset($_POST['submit'])){
$mysqli = new mysqli("localhost","root","","test");
$search = $mysqli->real_escape_string($_POST['search']);
$resultSet = $mysqli->query("SELECT * FROM books WHERE BookContent LIKE '%$search%'");
if($resultSet->num_rows>0){
while($rows = $resultSet->fetch_assoc()){
$BookContent = $rows['BookContent'];
//$output = preg_replace("/($search)/i",'<span class="highlight">$1</span>', $output);
echo $output = "" ."Your search results--> $BookContent"."<br>";
}
}else{
echo $output = "No result" ;
}
}
?>
just add this in your page.
CSS:
.highlight{background-color:yellow}
jQuery:
$("body").highlight("<?php echo $search; ?>");

How to display SQL result separately

I'm currently making a webpage which is meant to show all it's content from the database. So I made an SQL command which selects the data needed for only 1 particular field on the webpage.
Is it possible to make the SQL command so that it get's all the content for the page at once and that ill still be able to display it separately?
If so, how? Thanks
function dbGet() {
global $conn;
global $return;
$sql = SELECT * FROM testTable;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$return = $row["text"];
return $return;
}
}
else {
echo "0 results";
}
// $conn->close();
}
You can use in this way through which you can identify records has been there or not.
function dbGet() {
global $conn;
// I am not sure what is the datatype of $return here.
// if it's having a predefined format,
// please push the records into $return instead of creating as an array,
// which will be taken care by framework if any you are using.
// global $return;
$return = array('status' => false, records => []);
$sql = "SELECT text FROM testTable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$return['status'] = true;
while($row = $result->fetch_assoc()) {
$return['records'][] = $row["text"];
}
}
// $conn->close();
return json_encode($return);
}
Just echo the results inside while loop instead of returning in whatever format you wish
If you are using php, you can try something like
echo $row["text"];
Hope it helps
Let me know if you require any further help
First you should fix your return code as #AbraCadaver mentioned :
$return[] = $row["text"];
Then you can use foreach in your html :
<?php
foreach($return as $r){
echo $r['text'];
}
?>
I think a Json encoding : json_encode will work well.
Try this: http://php.net/manual/pt_BR/function.json-encode.php

My PHP Search Function isn't Outputting Data

So I am trying to create a way of searching my website. I've created a search bar on my index page. You can find this page here: http://seersvillage.com/v1.2/
My search form looks like this:
<form method="post" action="search.php">
<input type="text" name="search" class="search" value="Skeleton" onFocus="this.value=''">
</form>
and I have a functions.php file attatched and this page is also connected to my mysql database. I have content available to be read / searched for all ready.
Here is my search function on functions.php:
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM entries WHERE name LIKE '%$searchq%' or description LIKE '%$searchq%' or content LIKE '%$searchq%'") or die("Could not search");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'there was no search results!';
} else {
while($row = mysql_fetch_array($query)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$output .= '<div>'.$eName.' '.$eDesc.'</div>';
}
}
}
}
And the only thing on my search.php (excluding your usual html layout) is as follows:
<?php
include('includes/functions.php');
if(!isset($_POST['search'])) {
header("Location:index.php");
}
?>
and further down in the tags.
<?php print("$output");?>
Now I am pretty new to PHP and MySQL. However I am getting no error on my error.log file, making troubleshooting a little hard for a first timer. Any suggestions? I'm sure it's a very simple mistake, probably just misspelt something, but I just can't see it.
it seems that your php.ini file is set to not display errors. Add these lines of code at the beginning of your code and retry:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
Your doSearch function does not return anything.
return $output;
But $output is only declared within the function. So you'll need to use
print(doSearch());
Either that or declare $output as a global variable, but we don't want to do that :)
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM entries WHERE name LIKE '%$searchq%' or description LIKE '%$searchq%' or content LIKE '%$searchq%'") or die("Could not search");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'there was no search results!';
} else {
while($row = mysql_fetch_array($query)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$output .= '<div>'.$eName.' '.$eDesc.'</div>';
}
}
//make sure your function returns $output
return $output;
}
Make sure your function returns the output and then echo out the function:
<?php echo doSearch(); ?>
This is because of how PHP variables are scoped.
...then of course we need to add in all the standard provisos ... don't use the mysql_ library it's almost as dead as a Norwegian Blue. If you use mysqli or PDO you can bind the parameters/values to a prepared statement and not only will that improve efficiency but it'll ensure your input is properly sanitised (far better than that odd ad-hoc preg_replace you're using).
You don't want to kill your script (die) when the query fails - that's just a bit weird, handle the error properly.
There are far better ways to do searches in SQL such as FULLTEXT searches.. or if you can, perhaps implement Apache Solr rather than trying to roll your own.

Retrieving records within a PHP function

The following code is taken from a perfect working drop down list, and then when I put it into a function it breaks it! Am I doing something wrong here?
<?php
require "connect.php";
//create country lists
function records() {
$countryOptions = '';
$query = "SELECT DISTINCT country FROM regions";
$result = mysql_query($query);
if (!$result) {
$countryOptions = "<option>Error Retrieving Records</option>\n";;
}
else {
while ($row=mysql_fetch_assoc($result)) {
$countryOptions .= "<option value=\"{$row['country']}\">";
$countryOptions .= "{$row['country']}";
$countryOptions .= "</option>\n";
}
}
}
echo records();
?>
You're not outputting $countryOptions anywhere.
Either add
echo $countryOptions;
at the end of the function or better yet use
return $countryOptions;
and call the function like this:
echo records();
(or implement it to fit your exact needs - it's hard to tell how you use it in your own code)

PHP: Strange behaviour while calling custom php functions

I am facing a strange behavior while coding in PHP with Flex. Let me explain the situation:
I have two funcions lets say:
populateTable() //puts some data in a table made with flex
createXML() //creates an xml file which is used by Fusion Charts to create a chart
Now, if i call populateTable() alone, the table gets populated with data but if i call it with createXML(), the table doesn't get populated but createXML() does it's work i.e. creates an xml file.
Even if i run following code, only xml file gets generated but table remains empty whereas i called populateTable() before createXML(). Any idea what may be going wrong?
MXML Part
<mx:HTTPService id="userRequest" url="request.php" method="POST" resultFormat="e4x">
<mx:request xmlns="">
<getResult>send</getResult>
</mx:request>
and
<mx:DataGrid id="dgUserRequest" dataProvider="{userRequest.lastResult.user}" x="28.5" y="36" width="525" height="250" >
<mx:columns>
<mx:DataGridColumn headerText="No." dataField="no" />
<mx:DataGridColumn headerText="Name" dataField="name"/>
<mx:DataGridColumn headerText="Age" dataField="age"/>
</mx:columns>
PHP Part
<?php
//--------------------------------------------------------------------------
function initialize($username,$password,$database)
//--------------------------------------------------------------------------
{
# Connect to the database
$link = mysql_connect("localhost", $username,$password);
if (!$link)
{
die('Could not connected to the database : ' . mysql_error());
}
# Select the database
$db_selected = mysql_select_db($database, $link);
if (!$db_selected)
{
die ('Could not select the DB : ' . mysql_error());
}
//
populateTable();
createXML();
# Close database connection
}
//--------------------------------------------------------------------------
populateTable()
//--------------------------------------------------------------------------
{
if($_POST['getResult'] == 'send')
{
$Result = mysql_query("SELECT * FROM session" );
$Return = "<Users>";
$no = 1;
while ( $row = mysql_fetch_object( $Result ) )
{
$Return .= "<user><no>".$no."</no><name>".$row->name."</name><age>".$row->age."</age><salary>". $row->salary."</salary></session>";
$no=$no+1;
$Return .= "</Users>";
mysql_free_result( $Result );
print ($Return);
}
//--------------------------------------------------------------------------
createXML()
//--------------------------------------------------------------------------
{
$users=array
(
"0"=>array("",0),
"1"=>array("Obama",0),
"2"=>array("Zardari",0),
"3"=>array("Imran Khan",0),
"4"=>array("Ahmadenijad",0)
);
$selectedUsers=array(1,4); //this means only obama and ahmadenijad are selected and the xml file will contain info related to them only
//Extracting salaries of selected users
$size=count($users);
for($i = 0; $i<$size; $i++)
{
//initialize temp which will calculate total throughput for each protocol separately
$salary = 0;
$result = mysql_query("SELECT salary FROM userInfo where name='$users[$selectedUsers[$i]][0]'");
$row = mysql_fetch_array($result))
$salary = $row['salary'];
}
$users[$selectedUsers[$i]][1]=$salary;
}
//creating XML string
$chartContent = "<chart caption=\"Users Vs Salaries\" formatNumberScale=\"0\" pieSliceDepth=\"30\" startingAngle=\"125\">";
for($i=0;$i<$size;$i++)
{
$chartContent .= "<set label=\"".$users[$selectedUsers[$i]][0]."\" value=\"".$users[$selectedUsers[$i]][1]."\"/>";
}
$chartContent .= "<styles>" .
"<definition>" .
"<style type=\"font\" name=\"CaptionFont\" size=\"16\" color=\"666666\"/>" .
"<style type=\"font\" name=\"SubCaptionFont\" bold=\"0\"/>" .
"</definition>" .
"<application>" .
"<apply toObject=\"caption\" styles=\"CaptionFont\"/>" .
"<apply toObject=\"SubCaption\" styles=\"SubCaptionFont\"/>" .
"</application>" .
"</styles>" .
"</chart>";
$file_handle = fopen('ChartData.xml','w');
fwrite($file_handle,$chartContent);
fclose($file_handle);
}
initialize("root","","hiddenpeak");
?>
If your createXML function generates xml on the same exact page generation, and it sends a Content-Type of application/xml then it might be possible the table stuff doesn't parse. Again, this would only be guessing until you provided code.
Well, the only answer is that createXML somewhere overwrites/deletes your (probably global) table. Please have a look into your code again.
like comments given above, will be difficult without more info/codes/backend db:
however my wild guest:
populateTable() insert data to db
createXML() query data inserted by populateTable().
looks like 2 diff db conn. certain db required u to do commit inside your code, if so, make sure you do it inside populateTable() before closing the db conn.

Categories