Separator in my results - php

This query works fine for me, it gets my results and echos them back. But what I am missing and can not get to work is to get a separator in between the results. I have tried to use the implode function but was unable to. What I would like is a "|" in between the results in the echo. Below is my code I am using, any help or direction would be greatly appreciated.
$dbh = mysqli_connect("xxxxxxxxxxx", $user_name, $password, $database_name);
if (!$dbh)
{
die("Not connected : " . mysqli_error($dbh));
}
else
{
$query = "SELECT value FROM `$table_name` WHERE field IN('$field1', '$field2')";
$result = mysqli_query($dbh,$query);
if (mysqli_num_rows($result) == 0) {
echo "NO_DATA_FOUND";
}
else
{
while ($result_list = mysqli_fetch_array($result, MYSQL_ASSOC))
echo '' .$result_list["value"] . '';
}
mysqli_close($dbh);
}
?>

Related

How to output php search result to html table?

Want to output search result from database into an html table, but all I'm getting is a printed array. Fairly certain that's due to "print_r", but how do I output to html table instead and getting shown more than just the first result?
My html table using data from my database works fine - but there I'm just using a "SELECT *" with no user input.
I've tried playing around with my php-code that works with just the "SELECT *", but no luck.
<?php
$servername = "test";
$username = "test";
$password = "test";
$dbname = "test";
$journal = (isset($_SESSION["journal"])) ? $_SESSION["journal"]
: null;
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("connection failed: " . mysqli_connect_error());
mysqli_select_db($conn, $dbname) or die("something went wrong");
if(isset($_POST["form_submit"]))
{
$journal =$_POST["journal"];
$stmt = $conn->prepare("SELECT * FROM straffesager WHERE journalnummer=?");
$stmt->bind_param("s",$journal);
$stmt->execute();
$val = $stmt->get_result();
$row_count= $val->num_rows;
if($row_count >0)
{
$result =$val->fetch_assoc();
print_r($result);
}
else{
echo "<br><br>Den indtastede information matcher ikke sager i databasen.";
}
$stmt->close();
$conn->close();
}
?>
This is my result: "Array ( [idnumber] => 4 [journalnummer] => 17-1717171 [status] => lukket".
The result above is just text. I'd like it to be in the html table I'm using somewhere else as well.
How do I output the result from my code to an HTML table and have more than one search result being shown?
Thanks for helping out a rookie.
instead of
$result =$val->fetch_assoc();
print_r($result);
you should print your table with help of your $result variable
like this
echo "<table><tr><th>HEAD1</th><th>HEAD2</th><th>HEAD3</th></tr>";
while ($row = $val->fetch_assoc()) {
printf("<tr><td>%s</td><td>%s</td><td>%s</td></tr>",
$row['idnumber'],$row['journalnummer'],$row['status']);
//it will put $row instead of %s
}
echo "</table>";

Why do i get more results from my mysql query in php then what i ask for?

I am getting return values that do not exist in my current database. Even if i change my query the return array stays the same but missing values. How can this be what did i do wrong?
My MYSQL server version is 10.0.22 and this server gives me the correct result.
So the issue must be in PHP.
My code:
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Result:
array(1) {
[1]=> array(9) {
["UID"]=> string(1) "1"
["CreationTimestamp"]=> NULL
["UpdateTimestamp"]=> NULL
["ProcessState"]=> NULL
}
}
Solution:
I have found this code somewhere in my program. The program used the same name ass mine. This function turns the MYSQL result into a array. This happens between the result view and my script. This was done to make the result readable.
parent::processUpdatedAfter($date);
Function:
public function processUpdatedAfter($date)
{
$result = parent::processUpdatedAfter($date);
$array = Array();
if($result != false)
{
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$array[$row["UID"]]["UID"] = $row["UID"];
$array[$row["UID"]]["CreationTimestamp"] = $row["CreationTimestamp"];
$array[$row["UID"]]["UpdateTimestamp"] = $row["UpdateTimestamp"];
$array[$row["UID"]]["ProcessState"] = $row["ProcessState"];
}
return $array;
}
return false;
}
I edited this and my script works fine now thanks for all the help.
Note that, var_dump($result); will only return the resource not data.
You need to mysql_fetch_* for getting records.
Example with 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 process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row['UID'];
}
}
else
{
echo "No record found";
}
$conn->close();
?>
Side Note: i suggest you to use mysqli_* or PDO because mysql_* is deprecated and closed in PHP 7.
You are var_dumping a database resource handle and not the data you queried
You must use some sort of fetching process to actually retrieve that data generated by your query.
$ts = '2016-09-20 08:56:43';
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > '$ts'";
$result = mysql_query($select_query, $link_identifier);
// did the query work or is there an error in it
if ( !$result ) {
// query failed, better look at the error message
echo mysql_error($link_identifier);
exit;
}
// test we have some results
echo 'Query Produced ' . mysql_num_rows($result) . '<br>';
// in a while loop if more than one row might be returned
while( $row = mysql_fetch_assoc($result) ) {
echo $row['UID'] . '<br>';
}
However I have to mention Every time you use the mysql_
database extension in new code
a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions.
Start here
$select_query = "SELECT `UID` FROM `process_state ` WHERE `UpdateTimestamp` > \"[given time]\" ORDER BY UID DESC ";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Try this hope it will works

How to check if MySQL results returned empty in 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

Fetch specific column value from result set in php

MY code is:
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("select userid,fname,type from native_users where email=:email and pass=:pass");
$stmt->bindParam(':email', $username);
$stmt->bindParam(':pass', $password);
$stmt->execute();
if($stmt->rowCount() > 0)
{
$_SESSION['uid']=$stmt->fetchColumn(0); //working
$_SESSION['fname']=$stmt->fetchColumn(1); //not working
$utype=$stmt->fetchColumn(3); // not working
if($utype == "admin")
{
// send to admin page
}
else
{
//send to user page
}
}
else
{
echo"Incorrect data.";
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
I am new to PHP, I basically do Java.
I read here that:
There is no way to return another column from the same row if you use
PDOStatement::fetchColumn() to retrieve data.
In java, there is ResultSet#getString() funtion to do this.
What is the PHP equivalent of this?
You can use:
$result = $sth->fetch();
$result[0] will give userid
$result[1] will give fname
$result[2] will give type
Please read this
fetchColumn(), Returns a single column from the next row of a result
set.
Please read this for detail.
Use PDO::fetchAll() :
$rows = $stmt->fetchAll();
foreach ($rows as $v) {
echo $v['userid'] . " " . $v['fname'] . " " . $v['type'] ;
}
}
or just print_r($rows) you will notice that it's an associative array.

Checking if data is in a table row

This is my first post so please bear with me with inputting the code into here. Im trying to output some images to a PDF and need to create a if statement that looks for data with in a row.
$connection = mysql_connect("localhost", "testdb", "********")
or die ("Unable to connect!");
// select database
mysql_select_db("testdb") or die ("Unable to select database!");
// Select all the rows in the test table
$query = "SELECT * FROM test2 WHERE testid=89";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while ($row= mysql_fetch_array($result)) {
$image = $row[1];
$text = $row[2];
}
That's what I have so far and basically I need something along the line of this:
If (data in row 1) {
print $image;
} else {
print $text;
}
It's hard to say exactly what you're looking for since it isn't very clear, but I think what you're wanting to do is check to see if $image has a value, and if so, display it. If not, display $text instead.
If this is the case use empty(). It will tell you if a variable is empty or not.
if (!empty($image))
{
print $image;
}
else
{
print $text;
}
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
looks like you just need to test for data in $image
if(!empty($image))
{
echo $image;
}
else
{
echo $text;
}
if( !empty($row[1]) ) {
...
Use isset to check variable.
Like
if(isset($images) !='')
{
echo $images;
}
Although you are using old mysql_* functions which are depreciated, you are almost there
$connection = mysql_connect("localhost", "testdb", "********") or die ("Unable to connect!");
// select database
mysql_select_db("testdb") or die ("Unable to select database!");
// Select all the rows in the test table
$query = "SELECT * FROM test2 WHERE testid=89";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while ($row= mysql_fetch_array($result))
// This will only be called if there is a matching result.
{
echo $row[1];
echo $row[2];
}
Edit: Here is a cut and paste of a section of a query that happen to be open in eclipse:
$arrKPIData = Array();
try{
$dbh = new PDO($this->mySQLAccessData->hostname, $this->mySQLAccessData->username, $this->mySQLAccessData->password);
$stmt = $dbh->query($sql);
$obj = $stmt->setFetchMode(PDO::FETCH_INTO, new kpiData);
$dataCount=0;
foreach($stmt as $kpiData)
{
$arrKPIData[$dataCount]['year']=$kpiData->year;
$arrKPIData[$dataCount]['month']=$kpiData->month;
$arrKPIData[$dataCount]['measure']=$kpiData->kpiMeasure;
$arrKPIData[$dataCount]['var1']=$kpiData->var1;
$arrKPIData[$dataCount]['var2']=$kpiData->var2;
$dataCount++;
unset($stmt);
}
unset($dbh);
}
catch(PDOException $e){
echo 'Error : '.$e->getMessage();
exit();
}
unset($arrKPIData);
I am populating a simple array with data before I cleanse it and convert it into a class further in the code.

Categories