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.
Related
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
}
?>
How to check MySQL results are empty or not. If MySQL query results are empty then else condition should not be executed.
In case MySQL results in data there & in else condition my error my message is there but it is not showing any error message.
I have tried the following code but not showing any alert or echo message on the screen.
<?php
$sql = "select * from hall_search_data_1 where rent BETWEEN '".$_SESSION['amount1']."' AND '".$_SESSION['amount2']."'";
$res = mysql_query($sql);
if (!empty($res)) {
while ($row = mysql_fetch_row($res)) {
// here my data
}
} else {
echo "no results found";
}
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "id: " . $row["id"] . " - Name: " . $row["firstname"] . " " . $row["lastname"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Check number of rows
$result = mysqli_query($conn, $sql);
$rowcount=mysqli_num_rows($result);
if($rowcount > 0){
echo "Number of rows = " . $rowcount;
}
else
{
echo "no record found";
}
You can use mysql_num_rows to get count of number of rows returned from query.
if(mysqli_num_rows($res) > 0)
{
// rest of your stuff
}
else
{
echo "No records found.";
}
Note: mysql is deprecated instead use mysqli or PDO as seen above
Security Tip First of all stop using the mysql_* functions because they are not secure for production and later versions has stopped support for this API. So if accidentally you used those function in production then you can be in trouble.
It is not recommended to use the old mysql extension for new development, as it was deprecated in PHP 5.5.0 and was removed in PHP 7. A detailed feature comparison matrix is provided below. More Read
For your answer you have to only check no of rows is zero or not
Read this Post at php documentation with Example.
mysqli_num_rows
mysql_* API has been removed from PHP long time ago. To access the database you should use PDO. Checking if PDO has returned any results is actually pretty simple. Just fetch the results and if the array is empty then there was nothing returned from MySQL.
$stmt = $pdo->prepare('SELECT * FROM hall_search_data_1 WHERE rent BETWEEN ? AND ?');
$stmt->execute([$_SESSION['amount1'], $_SESSION['amount2']]);
$records = $stmt->fetchAll();
if ($records) {
foreach ($records as $row) {
// your logic
}
} else {
echo 'No records found!';
}
There is also mysqli library and if you are stuck using it you have to do a little more work, but the idea is the same. Fetch all results and if nothing was fetched then it means MySQL returned no rows.
$stmt = $mysqli->prepare('SELECT * FROM hall_search_data_1 WHERE rent BETWEEN ? AND ?');
$stmt->bind_param('ss', $_SESSION['amount1'], $_SESSION['amount2']);
$stmt->execute();
$records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
if ($records) {
foreach ($records as $row) {
// your logic
}
} else {
echo 'No records found!';
}
You can use mysql_num_rows(); to check your query return rows or not
$sql = "select * from hall_search_data_1 where rent BETWEEN '".$_SESSION['amount1']."' AND '".$_SESSION['amount2']."'";
$res = mysql_query($sql);
$rows=mysql_num_rows($res);
if($rows>0)
{
echo "data return from query";
}else{
echo "data not return";
}
Note:- mysql is deprecated instead use mysqli or PDO
I know this question has been asked many times , I tried lot of other answers but it didn't work for me
Here is my class
<?php
class saveexceltodb
{
var $inputFileName;
var $tableName;
var $conn;
var $allDataInSheet;
var $arrayCount;
/**
* Create a new PHPExcel with one Worksheet
*/
public function __construct($table=0)
{
$this->initiatedb();
}
private function initiatedb(){
//var_dump($allDataInSheet);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xyx";
// Create connection
$this->conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$this->conn) {
die("Connection failed: " . mysqli_connect_error());
}
}
public function updateIntermidiate(){
$allocationeventwise=array();
mysqli_query($this->conn,"DELETE FROM `allocationeventwise` WHERE 1");
$sql = "INSERT INTO `allocationeventwise` (`empid`, `event1`, `event2`, `event3`, `event4`, `event5` `event6`, `event7`) VALUES ";
$result = mysqli_query($this->conn, "SELECT usdeal.empid , usdeal.event1 , usdeal.event2, usdeal.event3, usdeal.event4, usdeal.event5, usdeal.event6, usdeal.event7 , salary.salary from usdeal INNER JOIN salary ON usdeal.empid = salary.empid where usdeal.allocated=0");
$i=0;
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$i++;
$totaleventDays = $row["event1"]+$row["event2"]+$row["event3"]+$row["event4"]+$row["event5"]+$row["event6"]+$row["event7"];
$allocationeventwise[$row["empid"]]['event1']=($row['salary']/$totaleventDays)*$row["event1"];
$allocationeventwise[$row["empid"]]['event2']=($row['salary']/$totaleventDays)*$row["event2"];
$allocationeventwise[$row["empid"]]['event3']=($row['salary']/$totaleventDays)*$row["event3"];
$allocationeventwise[$row["empid"]]['event4']=($row['salary']/$totaleventDays)*$row["event4"];
$allocationeventwise[$row["empid"]]['event5']=($row['salary']/$totaleventDays)*$row["event5"];
$allocationeventwise[$row["empid"]]['event6']=($row['salary']/$totaleventDays)*$row["event6"];
$allocationeventwise[$row["empid"]]['event7']=($row['salary']/$totaleventDays)*$row["event7"];
$sql .='("'.$row["empid"].'",
'.$allocationeventwise[$row["empid"]]["event1"].',
'.$allocationeventwise[$row["empid"]]["event2"].',
'.$allocationeventwise[$row["empid"]]["event3"].',
'.$allocationeventwise[$row["empid"]]["event4"].',
'.$allocationeventwise[$row["empid"]]["event5"].',
'.$allocationeventwise[$row["empid"]]["event6"].',
'.$allocationeventwise[$row["empid"]]["event7"].',)';
if($i<mysqli_num_rows($result))
$sql .=",";
else
$sql .=";";
}
echo $sql;
if (mysqli_query($this->conn, $sql)) {
echo "New record created successfully<br/>";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($this->conn);
}
} else {
echo "0 results";
}
}
}
When I use it like this
include('saveexceltodb.php');
$obj = new saveexceltodb(0);
$obj->updateIntermidiate();
I get following error .
Warning: mysqli_query(): Couldn't fetch mysqli in C:\xampp\htdocs\import-excel\saveexceltodb.php
You should follow below steps
Check database connection
Check query syntax
You have to pass connection object in mysqli_query function in you case it is ' $this->conn '
Hope, It may help you.
When i run the following code it will return 100 users record from a table but when i increase the value of LIMIT from 100 to a greater number like 5000 then it will not return anything.i have total 6000 records in table. So how can i access different number of records like 2000, 3000 or even all 6000 records? kindly Guide what's wrong!
<?php
$db = mysql_connect("localhost","root","");
if (!$db) {
die('Could not connect to db: ' . mysql_error());}
mysql_select_db("distributedsms",$db);
$result = mysql_query("select * from users LIMIT 100", $db);
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['user no'] = $row['sno'];
$row_array['mnc'] = $row['mnc'];
$row_array['mcc'] = $row['mcc'];
$row_array['lac'] = $row['lac'];
$row_array['cell id'] = $row['cell id'];
$row_array['lat'] = $row['lat'];
$row_array['lng'] = $row['lng'];
$row_array['address'] = $row['address'];//push the values in the array
array_push($json_response,$row_array);
$users = $json_response;}
$fp = fopen('users_data.json', 'w+');
fwrite($fp, json_encode($json_response));
fclose($fp);
echo json_encode($json_response);
?>
First, enable error reporting in your INI or Script:
<?php error_reporting(E_ALL);
ini_set('display_errors', 1);
This will help you if there is any error/warning in case of low memory allocation or similar.
To fetch all records, you shouldn't use LIMIT, remove LIMIT from your SQL.
i.e. select * from users
You should not use mysql_connect as it is deprecated. Use mysqli_connect instead. Also, I don't think you need to iterate so much, just choose what you want in your select statement.
UPDATE: another factor on why this might be happening can also be the returned information from the database, if you have apostrophes ' in your strings and you try to use json_encode, it will break, you would need to addslashes first.
Try the following, change your LIMIT as you wish, and let me know if you still have those errors:
<?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 sno,mnc,mcc,lac,cell_id,lat,lng,address FROM users LIMIT 100";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$response = array();
while ($row = $result->fetch_assoc()) {
foreach($row as $k => $str){
$row[$k] = addslashes($str);
}
array_push($response, $row);
}
echo json_encode($response);
} else {
echo "0 results";
}
$conn->close();
?>
HTML FILE:
<form method="post" action="generate.php">
Product Reference(s): (if multiple, separate by ",")<br />
<input type="text" name="project_ref" value="REF123, REF124" />
<input type="submit" value="Generate" />
</form>
PHP FILE:
<?php
$ref_array = explode(',', $_POST['project_ref']);
foreach ($ref_array as &$ref) {
// Create connection
$conn = mysqli_connect($host, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM `inventory` WHERE reference = '$ref' LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Brand: " . $row["brand"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
}
?>
RESULTS:
Brand: Bose
0 results
But I actually wanted:
Brand: Bose
Brand: Beats
So the problem is that the MySQL query is not running for every array item. Its only executing the first item of the array.
Your input value has a space between the different refs: REF123, REF124
You can either explode on a comma & space:
$ref_array = explode(', ', $_POST['project_ref']);
Or trim the values:
$sql = "SELECT * FROM `inventory` WHERE reference = '" . trim($ref) . "' LIMIT 1";
It's also strongly recommended that you pass in $ref as a parameter, rather than a string literal:
http://php.net/manual/en/mysqli-stmt.bind-param.php
It looks like your issue is in your explode. The first value of the explode is correct the second (third, forth, etc.) will have a leading space. explode on ', ' instead of ',' or trim the results before using it.
But there are a few other things in this code. Don't create a new connection for each query, the single connection will work just reuse it. Second, use parameters or sanitize the value before you use it in the sql, this will help prevent sql injection attacks, a better way is to use PDO and use parameters. Last, change your query so that a single query returns all the results you need by using an IN clause.
<?php
$ref_array = explode(', ', $_POST['project_ref']);
$ref_IN = "";
foreach ($ref_array as $ref_val)
$ref_IN .= "'{$ref_val}', ";
$ref_IN = rtrim($ref_IN , ",");
// Create connection
$conn = mysqli_connect($host, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM `inventory` WHERE reference IN ({$ref_IN}) GROUP BY reference";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Brand: " . $row["brand"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>