live search with Jquery - php

I am trying to implement a live search on my site.
I am using a script somebody has already created. http://www.reynoldsftw.com/2009/03/live-mysql-database-search-with-jquery/
I have got the Jquery, css, html working correctly but am having troubles with the php.
I need to change it to contain my database information but everytime I do I recieve an error:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\search.php on line 33
These are the details of my database:
database name: development
table name: links
Columns: id, sitename, siteurl, description, category
This is the php script
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "password";
$dbname = "links";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
if(isset($_GET['query'])) { $query = $_GET['query']; } else { $query = ""; }
if(isset($_GET['type'])) { $type = $_GET['type']; } else { $query = "count"; }
if($type == "count")
{
$sql = mysql_query("SELECT count(url_id)
FROM urls
WHERE MATCH(url_url, url_title, url_desc)
AGAINST('$query' IN BOOLEAN MODE)");
$total = mysql_fetch_array($sql);
$num = $total[0];
echo $num;
}
if($type == "results")
{
$sql = mysql_query("SELECT url_url, url_title, url_desc
FROM urls
WHERE MATCH(url_url, url_title, url_desc)
AGAINST('$query' IN BOOLEAN MODE)");
while($array = mysql_fetch_array($sql)) {
$url_url = $array['url_url'];
$url_title = $array['url_title'];
$url_desc = $array['url_desc'];
echo "<div class=\"url-holder\">" . $url_title . "
<div class=\"url-desc\">" . $url_desc . "</div></div>";
}
}
mysql_close($conn);
?>
Can anybody help me input this database info correctly? I have tried many times but keep getting an error. Thanks in advance.
EDIT: IT IS CONNECTING TO THE DATABASE WITHOUT AN ERROR. CHECK HERE http://movieo.no-ip.org/

the mysql_query() call is failing an returning false instead of a resource. My bet is that mysql_select_db() is failing. This should show the error:
mysql_select_db($dbname) or die('Couldn\'t select DB: '.mysql_error());

Compare: database name: development to $dbname = "links";
I think you should change it to the right name.

As well as changing the $dbname to development, check your two SQL statements. They are selecting from the table urls instead of links.

Related

fetch_assoc doesn't show first row of results

Not sure what I did wrong. I'm aware that having two fetch_assoc removes the first result but I don't have such a thing.
$sql = "$getdb
WHERE $tablenames.$pricename LIKE 'm9%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo $tableformat;
while($row = $result->fetch_assoc()) {
$name = str_replace('m9', 'M9 Bayonet', $row['Name']);
include 'filename.php';
echo $dbtable;
}
My connect file:
$servername = "";
$username = "";
$dbname = "";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
require_once ('seo.php');
$dollar = '2.';
$euro = '1.9';
$tableformat = "<div class=\"CSSTableGenerator style=\"width:600px;height:150px;\"><table><tr><th>Name</th><th>Price</th><th><a class=\"tooltips\">Community<span>New !</span></a> </th><th>Cash Price</th><th>Trend </th><th>Picture </th></tr></div>";
$getdb = "SELECT utf.id, utf.PriceMin, utf.PriceMax, utf.Name, utf.Trend , community1s.price as com_price, utf.Name, utf.Trend
FROM utf
INNER JOIN (select id, avg(price) price from community1 group by id) as community1s
ON utf.id=community1s.id";
$tablenames = 'utf';
$pricename = 'Name';
$idrange = range(300,380);
What happens is, it fetches the first two column's fine and the rest of the row is not there and pushes the other results down one row, which messes up the data.
Here's an image to demonstrate:
http://imgur.com/CQdnycW
The seo.php file is just a SEO function.
Any ideas on what may be causing this issue?
EDIT:
My Output:
echo $tableformat;
while($row = $result->fetch_assoc()) {
$name = str_replace('m9', 'M9 Bayonet', $row['Name']);
include 'filename.php';
echo $dbtable;
EDIT: Solved it by moving my variables around. Marked as solved.
I found the issue. Some Variables that did the output were in a bad place. Rearranged them and now they are fine.
Your HTML is broken, and strange things happen in broken tables. $tableformat contains HTML that opens a <div> and a <table>, but then closes the <div> with the table still open.
Fix the broken HTML and you'll probably find that all is well

how do I check if mysqli connection is working?

I am really new on php and I am trying to create my own php shop cart. After some research I got myself stuck in the "function products" below because seems to me it is not working properly. I expect to see the names of my products on my mysql database but it is not showing anything. My user name is noivaemd_etalhes, I am using my correct password and my database name is noivaemd_cart and I created on this database the table called Products with my list of products available. Can anybody help me to figure out what am I doing wrong on the php instructions below???? I appreciate any help.
<?php
session_start();
$page = 'index.php';
function products() {
$con = mysqli_connect("localhost", "noivaemd_etalhes", "mypassword", "noivaemd_cart") or die (mysqli_error());
$res = mysqli_query($con, "SELECT id, name, description, price FROM Products WHERE quantity > 0 ORDER BY id DESC");
if (mysqli_num_rows($res)==0) {
echo "<font family=verdana><font size=6px><font color= #90882C><font style=normal><font variant= normal><br>No products available<br></font>";
}
else{
while($get_row = mysqli_fetch_assoc($res)) {
echo '<p>'.$res['name'].'</p>';
}
}
}
?>
This code:
while ($get_row = mysqli_fetch_assoc($res)) {
echo '<p>'.$res['name'].'</p>';
}
Should be:
while ($get_row = mysqli_fetch_assoc($res)) {
echo '<p>'.$get_row ['name'].'</p>';
}
As your title ask also tell how to check if the mysqli database connection is successful you can use the below code:
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Reference link: http://www.php.net/manual/en/function.mysqli-connect.php
It's not good practice to connect to your database directly in your code. Open another file, and save it has 'dbconnect.php' or whatever you choose to name it. Save it in the same root.
Inside DB connect, you connect to the database like this:
<?php
$mysql_host = "localhost";
$mysql_user = "username";
$mysql_pass = "";
$mysql_dbname = "Products";
$conn_error = "Sorry, Could Not Connect";
if(!#mysql_connect($mysql_host,$mysql_user,$mysql_pass)||!#mysql_select_db($mysql_dbname)){
die($conn_error);
}
?>
In your index.php, inside your php tags, write 'require "dbconnect.php";'.
Then you get your values like this:
$InfoQuery = " SELECT id, product, name FROM table_name WHERE quantity>0 ORDER BY id DESC";
$Info = mysql_query($InfoQuery);
while($InfoRow=mysql_fetch_assoc($Info)){echo "<p>".$InfoRow['id']."<br>". $InfoRow['product']"."<br>". $InfoRow['name']."</p>";}
Edit: What you did wrong is in your while loop, you fetched the table data from $res when it should be fetched from $get_row

How to show a database colum data on my php script?

I have a php script made by me that can change a database info by taking db name,user,pass and host. Now I want to show a database column info to my php script.
Now how can i do that here is my main db.php script i didn't put the html from script cause i don't think it's necessary.
I have code this but it's showing a error like that
Parse error: syntax error, unexpected T_STRING in /home/abc/public_html/db.php on line 56
Here is my db.php
<style type="text/css">
body {
background-image: url('data:image/gif;base64,R0lGODlhAwADAPcAAAAAAABCAP///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////ywAAAAAAwADAAAICQADABhIcGBAAAA7');
font-family: Tahoma;text-align: center;color: green;
}
img{opacity:0.75; filter:alpha(opacity=75);}
.field_set{
border-color:#4AB825;
}
</style>
<?php
// escape received values
$dbusr = $_POST['usr'];
$dbpsw = $_POST['psw'];
$dbhost = $_POST['host'];
$dbname = $_POST['dbname'];
$admusr = $_POST['admusr'];
$prfx = $_POST['prfx'];
$admpsw = md5($_POST['admpsw']);
// Create connection
$conn = new mysqli($dbhost, $dbusr, $dbpsw);
// Check connection
if ($conn->connect_error) {
die("<br><br><br><br><br><br><br>Database Connection failed: " . $conn->connect_error);
}
echo "<br><br><br><br><br><br><br>Database Connected successfully";
mysqli_select_db($conn,"$dbname");
// use them in query
$sql = "UPDATE ".$prfx."_users SET user_login='".$admusr."',user_pass='".$admpsw."' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "<br><br>Record updated successfully</br></br>Go to your login page <br><br>ex: www.site.com/wp-admin<br><br>and login with your given id and pass";
} else {
echo "<br>Error updating record:" . $conn->error;
}
$sql = "SELECT guid FROM".$prfx."_posts;
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Site:" . $row["guid"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
$sql = "SELECT guid FROM".$prfx."_posts;
Should be
$sql = "SELECT guid FROM".$prfx."_posts";
You were missing the closing "
As Dagon said in his comment, In most editors code is shown with color coding, and you can usually see if a " or ' is missing it's closing tag because the color will be off.
UPDATE
Missing space between FROM and $prfx, use below:
$sql = "SELECT guid FROM ".$prfx."_posts";
You are missing a " at the end of line try replace this.
$sql = "SELECT guid FROM".$prfx."_posts";
Whenever you get this error it means that you are missing a closing double quote on that line which is mentioned on the error.
Change this,
$sql = "SELECT guid FROM".$prfx."_posts;
to this,
$sql = "SELECT guid FROM".$prfx."_posts";

SQL / PHP if NULL show else

We are trying to complete / fix the below code, We cant seem to do the following.
Check if 'Check_Activation' is set to 'NULL' within the Database
IF value is NULL direct the user to one of the forms (1,2,3)
And finally if the 'Check_Activation' has already been activated and isn't 'NULL' prevent user from accessing one of the 3 forms.
I know its basicly there but we can't seem to figure out the final bug.
Please have a quick look at the code below and if anyone notices anything that isn't right please advice us.
Paste Bucket / Version
Website URL
<?php
$username = $_POST['username'];
$activation_code = $_POST['activation_code'];
$activation_codeurl = $activation_code;
$usernameurl = $username;
$db_host = "localhost";
$db_name = "aardvark";
$db_use = "aardvark";
$db_pass = "aardvark";
$con = mysql_connect("localhost", $db_use, $db_pass);
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_name, $con);
$checkcustomer = mysql_query("SELECT `Check_Activation` FROM `members` WHERE `Username` = '".$username."' & `Activation` = '".$activation_code."'; ");
$array = mysql_fetch_array($checkcustomer);
if (is_null($array['Check_Activation'])) {
$username = substr($username, 0, 1);
if($username == '1') {
$redirect_url='form-one.php?membernumber='.$usernameurl.'&activation_code='.$activation_codeurl;
} elseif($username == '2') {
$redirect_url='form-two.php?membernumber='.$usernameurl.'&activation_code='.$activation_codeurl;
} elseif($username == '3') {
$redirect_url='form-three.php?membernumber='.$usernameurl.'&activation_code='.$activation_codeurl;
}
header("Location:". $redirect_url);
}
else
{
?>
Try this, You need to fetch the row from table and then you can check the values,
$val = mysql_fetch_array($checkcustomer);
if (is_null($val['Check_Activation']))
instead of
$val = mysql_query($checkcustomer);
if ($val == 'NULL')
NOTE: Use mysqli_* functions or PDO instead of using mysql_* functions(deprecated)
before I get into the technicality of what your are trying to accomplish, I have some advice for your code in general. You should avoid using the mysql api as it is deprecated, and use the mysqli api instead. I think you will also find that it is easier to use.
Now for the code:
You have this line in your code which seems to be incorrect, $checkcustomer is a result set from your previous query, so why are you running it as a query again?
$val = mysql_query($checkcustomer);
You already have the result set so do this:
$array = mysql_fetch_array($checkcustomer);
And then take the value of Check_Aviation;
if (is_null($array['Check_Aviation'])) {
//Do Something
}
Should solve your issue

problem with fetching results from mysql via php function

can some one point out the problem with this code? It supposed to fetch data from mysql but it returns blank. Here is the full code.
<ul class="list">
<?php
require("object/db.class.php");
error_reporting(0);
function entry_tickets() {
if($_SESSION['dojopress_global:root'] == false) {
$entry_ticket .= <<<ENTRY_TICKET
<li><p><img src="http://cdn1.iconfinder.com/data/icons/humano2/32x32/apps/gnome-keyring-manager.png" />Access denied</p></li>
ENTRY_TICKET;
} elseif($_SESSION['dojopress_global:root'] == true) {
$q = "SELECT * FROM `notice` ORDER BY nid LIMIT 12 DESC";
$r = mysql_query($q);
if ( mysql_num_rows($r) == 0 ) {
$entry_ticket .= <<<ENTRY_TICKET
<li><p><img src="http://cdn1.iconfinder.com/data/icons/humano2/32x32/status/dialog-information.png" /> Nothing to display</p></li>
ENTRY_TICKET;
} elseif ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_array($r) ) {
$nid = stripslashes($a['nid']);
$note = stripslashes($a['note']);
$type = stripslashes($a['type']);
$private = stripslashes($a['private']);
$date = stripslashes($a['date']);
$author = stripslashes($a['author']);
function note_type($type) {
if($type == 1) { $type = "posted a comment!"; } elseif($type == 2) { $type = "raised a support ticket!"; } else { }
return ($type);
}
$entry_ticket .= <<<ENTRY_TICKET
<li><p> $athor, note_type($type)</p></li>
ENTRY_TICKET;
return $entry_ticket;
}
}
}
}
echo entry_tickets();
?>
</ul>
<div style="clear:both;height:10px;"></div>
sorry forgot db.class.php
<?php
session_start();
//connect.php
$host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "au";
$connectClass = mysql_connect("$host", "$db_user", "$db_pass") or die ("Couldn't establish connection to database server.");
$dbObject = mysql_select_db("$db_name", $connectClass) or die ("Couldn't select database.");
?>
error reporting disabled error code
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in D:\wamp\www\ageis\note.php on line 22
Your mysql syntax looks bad. You have:
SELECT * FROM `notice` ORDER BY nid LIMIT 12 DESC
try
SELECT * FROM `notice` ORDER BY nid DESC LIMIT 12
Erik's comments should have pointed you in the right direction, however:
Figure out where PHP logs errors. Either turn up php's error reporting level so you see more errors, or start tailing your apache error_log
You should always check for errors after running mysql_query and do some sort of logging on failure. This is probably best accomplished by writing a wrapper function for mysql_query that does this, or using a 3rd party db wrapper that has already solved this problem.
You're redefining function note_type every time through your while loop. You have a return call outside the function, below it. Really I can't see how this is even syntactically correct. It looks like you have a large problem with mismatched brackets.
As for an actual database issue, you should check mysql_error() if no rows return from the call because it's likely something went wrong.
Also I recommend using PDO which is a true database class instead of the native function based ones.

Categories