I want to make a auto complete text box for select employee name from DB. But it makes query error which is
Warning: mysql_fetch_array() expects parameter 1 to be resource, string given in
Following is my code.
<?php
include 'func/db_connect.php';
if(!empty($_POST["keyword"])) {
$query ="SELECT * FROM employee WHERE name like '" . $_POST["keyword"] . "%' ORDER BY name LIMIT 0,6";
$result=mysql_fetch_array($query);
if(!empty($result)) {
?>
<ul id="name-list">
<?php
foreach($result as $name) {
?>
<li onClick="selectName('<?php echo $name["name"]; ?>');"><?php echo $name["name"]; ?></li>
<?php } ?>
</ul>
<?php } } ?>
What is the wrong with this code, can anyone help me !
Try this
$result=mysql_query($query);
while($data = mysql_fetch_assoc($result))
{
$row[] = $data;
}
And change !empty($result) to count($row) > 1
You need to actually perform the query before being able to fetch the results:
$result = mysql_query("SELECT id, name FROM mytable");
$rows = mysql_fetch_array($result);
Check out the PHP docs for more in-depth examples:
http://php.net/manual/de/function.mysql-fetch-array.php
On a sidenote: using mysql_* function has been deprecated for a while, have a look into mysqli!
Try with this , you need to use mysql_query() function and you pass string directly to mysql_fetch_array()
$query = mysql_query("SELECT * FROM employee WHERE name like '" . $_POST["keyword"] . "%' ORDER BY name LIMIT 0,6");
$result = mysql_fetch_array($query);
Note : mysql_* functions deprecated and removed in PHP 7.x. Use MySQLi or PDO_MySQL extension
you have execute the query first
Deprecated features in PHP 5.5.x
The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the MYSQLi or PDO_MySQL extensions.
<?php
// include 'func/db_connect.php';
global $conn;
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
if(!empty($_POST["keyword"])) {
$name_val = '%'.$_POST["keyword"].'%';
$stmt = $conn->prepare("SELECT * FROM employee WHERE name like ? ORDER BY name LIMIT 0,6");
$stmt->bind_param('s',$name_val);
$qry_res=$stmt->execute();
if($row_count>0) {
?>
<ul id="name-list">
<?php
while($row = $qry_res->fetch_assoc())
{
?>
<li onClick="selectName('<?php echo $row["name"]; ?>');"><?php echo $row["name"]; ?></li>
<?php } ?>
</ul>
$stmt->close();
You can try this:
$cn=mysql_connect("localhost","root","");
if(!$cn)
{
echo "Unable to connect";
die();
}
$query = "Select * from table";
$result= mysql_query($query,$cn);
$n = mysql_num_rows($result);
if($n>0)
{
while($rw=mysql_fetch_array($result))
{
$owenername=$rw["owenername"];?>
<p>Owner Name:<?php echo $owenername;?> </p>
<?php}
}
else
{
?>data not found
<?PHP
}
?>
Related
I need to use multiple queries and send them out as well formed xml for as3 purposes.
When I use only one query everything works fine.
Problem starts when multi-query operates.
Right now when //XML header is hidden I get a structure printed on screen and it looks good.
But when header goes enabled, nothing works!
Please take a look at my code:
<?php
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "";
$dbName = "test";
$dbTable = "pizzaroma";
$mysqli = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);
if ($mysqli->connect_errno)
echo "la conection ha fallado: ".$mysqli->connect_errno;
$query = "SELECT * FROM ".$dbTable." WHERE cat='pizza' AND act='1' ORDER BY ID ASC; ";
$query .= "SELECT * FROM ".$dbTable." WHERE cat='pasta' AND act='1' ORDER BY ID ASC; ";
if ($mysqli->multi_query($query)) {
// header("Content-type: text/xml");
echo "<?xml version='1.0' encoding='UTF-8'?>";
echo "<pics>";
do {
echo "<theme name='temporaly'>";
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
echo "<pic name='".$row['NAME']."' desc='".$row['DESCES']."' price='".$row['PRICE']."'/>";
echo "</pic>";
}
$result->free();
}
echo "</theme>";
if ($mysqli->more_results()) {
}
}
while ($mysqli->next_result());
echo "</pics>";
}
$mysqli->close();
?>
earlier i were using "echo",.. now instead ive put "printf" there,.. but only some lines, i am not sure if that was the reason.. but now works. it was throwing me the
"Strict Standards: mysqli_next_result(): There is no next result set. Please, call mysqli_more_results()/mysqli::more_results() to check whether to call this function/method" so looking for help i have found this line there :
do{} while(mysqli_more_results($db) && mysqli_next_result($db));
that solved the problem for xml error.
<?php
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "";
$dbName = "test";
$dbTable = "pizzaroma";
$mysqli = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);
if ($mysqli->connect_errno)
echo "la conection ha fallado: ".$mysqli->connect_errno;
$query = "SELECT * FROM ".$dbTable." WHERE cat='pizza' AND act='1' ORDER BY ID ASC; ";
$query .= "SELECT * FROM ".$dbTable." WHERE cat='pasta' AND act='1' ORDER BY ID ASC; ";
$query .= "SELECT * FROM ".$dbTable." WHERE cat='carne' AND act='1' ORDER BY ID ASC; ";
if ($mysqli->multi_query($query)) {
header("Content-type: text/xml");
printf( "<?xml version='1.0' encoding='UTF-8'?>");
printf( "<pics>");
do {
printf( "<theme name='temporaly'>");
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
echo "<pic name='".$row['NAME']."'/>";
}
$result->free();
}
echo "</theme>";
}
while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli));
echo "</pics>";
}
$mysqli->close();
?>
later on i´ve had to serialize the xml output it was easy :D
>> $i=1; and ... do {printf( "<theme name='".$i++."'>");
but now ,.. how do I associate output serialIDs to elements from array that contains category names. something like...
if name="1" then name="firtsArrayChild"
any idea?
but i think that is another song for another question out there! thanks
I would like to assign field colors like to the field "status". if the mysql filed is "yes" then it should be green, if "no" then it should be red. Who can assist? Many thanks in advance. below you will see my code:
$query = "SELECT * FROM members";
$result = mysql_query($query);
while (list($id,$name,$status) = mysql_fetch_row($result))
{
echo("<tr><td>$name</td><td>$status</td></tr>\n");
}
You can try -
echo("<tr style='color:"
. (($status=='no') ? 'red' : 'green')
. "'><td>$name</td><td>$status</td></tr>\n");
or also can do using an array of colors -
$colors= array('yes' => 'green', 'no' => 'red');
echo("<tr style='color:"
. $colors[$status]
. "'><td>$name</td><td>$status</td></tr>\n");
Stop using mysql_* extension its deprecated and close in PHP 7, use mysqli_* or PDO.
Here is the complete example of your code by using MYSQLi Object Oriented:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM members";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if($row['status'] == 'YES'){
?>
<tr><td style="color:green;"><?=$row['name']?></td><td style="color:green;"><?=$row['status']?></td></tr>
<?php
}
else{
?>
<tr><td style="color:red;"><?=$row['name']?></td><td style="color:red;"><?=$row['status']?></td></tr>
<?php
}
}
}
else
{
echo "0 results";
}
$conn->close();
?>
You just need to add check inside the while loop if status is YES use green color else red color
Considering $status is only yes or no, it should be treated as Boolean
value. I assume this is an Boolean value.
$query = "SELECT * FROM members";
$result = mysql_query($query);
while (list($id,$name,$status) = mysql_fetch_row($result))
{
if($status){
echo("<tr style='color:green'><td>$name</td><td>$status</td></tr>\n");
} else {
echo("<tr style='color:red' ><td>$name</td><td>$status</td></tr>\n");
}
}
Considering it to be Boolean we can modify Sougata's code to be like .
echo("<tr style='color:"
. ($status ? 'red' : 'green')
. "'><td>$name</td><td>$status</td></tr>\n");
You should also use mysqli or PDO as mysql_* are deprecated.
I am using this same code `
php $postId = 41;
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname="my_db";
$host="localhost";
$user="guessthe";
$dbh=mysql_connect ($host,$user,"correctPassword?") or die ('I cannot connect to the database because: ' . mysql_error(). '');
mysql_select_db ("$dbname") or die('I cannot select the database because: ' . mysql_error());
$sql="SELECT * FROM games WHERE postId = $postId";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
There is a value in the gameLength row! I can't get this code to pull any of the rows! Any idea what i'm doing wrong?
You're using MySQL, which is depcirated - and will be phased out. You should use MySQLi or PDO instead. Also, your $postId is defined outside a PHP-tag? Might just be a copy/paste mistake? Anyway, you can try the code below, which is in MySQLi:
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname = "my_db";
$host = "localhost";
$user = "guessthe";
// Connecting to the database
$mysqli = new mysqli($host, $user, "correctPassword?", $dbname);
if ($mysqli->connect_errno) {
// If we are here, the connection failed
echo "Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;
}
$sql ="SELECT * FROM games WHERE postId = $postId";
if ($result = $mysqli->query($sql)) {
// If the query was sucsessfull, we can get the rows
while ($row = $result->fetch_assoc()) {
$gameId = $row['id'];
$game100s = $row['game100s'];
$gamesPlayedAllTime = $row['gamesPlayed'];
$gamesPointsAllTime = $row['gameScore'];
$gameLength = $row['gameLength']; // get number of questions
$gameScore = $row['gameScore'];
$gameType = $row['gameType'];
$gametitle = $row['gameSubTitle'];
}
} else {
// If the query failed, do something here
}
echo $gameLength;
?>
I see some people commenting that you need to put the $postId variable inside quotes in the query, but when using double-quotes (") variables will be posted, so it's not really needed. Also note that things are case-sensitive, so if your results doesn't show, check for spelling-mistakes.
There are many errors in your code
Try this...
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength">
<?php
// MySQL connect configuration
$host = "localhost";
$dbname = "my_db";
$user = "username";
$password = "password";
$dbh = mysql_connect ($host,$user,$password) or die ('I cannot connect to the database because: ' . mysql_error() . '');
mysql_select_db($dbname, $dbh) or die('I cannot select the database because: ' . mysql_error());
$sql = "SELECT * FROM games WHERE postId='$postId'";
$result = mysql_query($sql);
while($rows = mysql_fetch_array($result)){
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
}
?>
You need to fix this is your code and that should fix the error.
$sql="SELECT * FROM games WHERE postId ='".$postId."' ";
If you want all the records you can use a while loop. Here is some pseudo code.
while($row = mysql_fect_assoc($query)){
echo $row["THE THING YOU WANT"];
...
}
what is wrong with this script? it keeps giving my erros but will not tell me what is wrong
I need this to lookup channel number from the item number passed in url. then echo the channel number
<?php
$id = $_GET['item'];
if (!$link = mysql_connect('server', 'user', 'pass')) {
echo 'Could not connect to mysql';
exit;
}
if (!mysql_select_db('xmlrpc', $link)) {
echo 'Could not select database';
exit;
}
$sql = mysql_query("SELECT channel FROM channels WHERE item = '".$_GET['item']."'")or die(mysql_error());
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['channel'];
}
mysql_free_result($result);
?>
$sql = mysql_query("SELECT channel FROM channels WHERE item = '".$_GET['item']."'") or die(mysql_error());
To
$sql = "SELECT channel FROM channels WHERE item = '".$_GET['item']."'";
As a sidenote do not use mysql_ functions, they became obsolete (PHP 5.5). Use PDO instead for example, as it stands your code is vulnerable to SQL injections.
when item is already declared as a variable $id
$id = $_GET['item'];
you could already use it as a variable in your mysql
$sql = mysql_query("SELECT channel FROM channels WHERE item = '".$_GET['item']."'")or die(mysql_error());
change it into
$sql="SELECT * FROM channels WHERE item ='$id'";
So I have the following code in PHP that contains a function which uses mysqli to retrieve data from my database:
function displayuser(){
$db = mysqli_connect("localhost", "root", "", "shop") or die("Error");
$query = "SELECT id, username FROM users";
$result = $db->query($query) or die("Error");
while($row = $result->fetch_array()) {
return $row['id'].' '.$row['username'];
}
}
My question is; how would I go about displaying $row['id'] and $row['username'] in a webpage using HTML presuming I would have to use PHP as well?
Should it be like this? Say in a PHP file user.php for instance
<?php
include_once('function.php');
foreach(displayuser() as $display) {
?>
<p><?php echo $display['id'];?></p>
<?php
}
?>
I used the display method above when I was handling mysql rather than mysqli, so I'm trying to familiarize myself with the improved mysql
EDIT (new code):
functions.php
function getuser() {
$db = mysqli_connect("localhost", "root", "", "shop") or die("Error");
$query = "SELECT id, username FROM users";
$result = $db->query($query) or die();
return $result->fetch_all(); }
display.php
<?php
include_once('functions.php');
foreach(getuser() as $user) {
echo $user['id']. ' '.$user['username'];
}
?>
When executing, display.php displays empty results.
I tried using print_r to print in the data behind the arrays but it seems the arrays were empty. I thought maybe we shouldn't use "foreach" or something.
For starters, the keyword return literally kills your script. Return means 'go back to what called me'. That said, the first row from your query will end the displayUser function. Restructure it like this:
$result = $db->query($query);
return $result->fetch_all();
Then the rest should work but I would reword and structure it.
include_once('function.php');
foreach(displayuser() as $user) {
echo "<p>" . $user['id'] . "</p>";
}
You are nearly there, you could go about doing it like this:
function.php
function get_users(){
$db = mysqli_connect("localhost", "root", "", "shop") or die("Error");
$query = "SELECT id, username FROM users";
$result = $db->query($query) or die("Error");
return $result->fetch_all();
}
Display File
<?php
include_once('function.php');
$users = get_users();
foreach($users as $user) {
echo '<p>' . $user['id'] . ' ' . $user['username'] . '</p>';
}
?>
This has a more clear separation of concerns, no HTML in the function call so it can be reused multiple times reducing duplicate code.