How to output php search result to html table? - php

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>";

Related

Some table values returning null?

I have a database that stores a website's news articles. Each row contains a time, title, author, and a content field. Javascript handles the information passed from php and displays it via togglable buttons. For some reason even though I see the data in Mysql Workbench some content fields are returning null. Why would this be?
Here is my code..
var json = <?php
$servername = "sfxworks.net"; //Currently pulls from my webserver. Pass sql credentials or write a php file that I can include that wont show on github.
$username = "foo";
$password = "bar";
$dbname = "foodbarmmmmmmmmm";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$rows = array();
$sql = "SELECT title, author, date, content FROM News";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
echo "0 results";
}
$conn->close();
print json_encode($rows);
?>;
For some reason, after php processes this with error reporting on, I just get null values at random. In the same places, but random.
There are some values in the table with interesting apostrophes..
After removing [ ’ ] from the string and replacing it with [ ' ] the value is no longer null.

PhP MySQL get ceratin items from database and echo them

I need some help and I can't figure it out,i tried searching the internet but I found nothing
So I'm using this code from w3schools
<?php
$servername = "localhost"; //Obviously this are set to my parameters
$username = "username"; //Obviously this are set to my parameters
$password = "password"; //Obviously this are set to my parameters
$dbname = "myDB"; //Obviously this are set to my parameters
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Some code goes here
}
} else {
echo "0 results";
}
$conn->close();
?>
How can I modify this code to echo certain items only?
EXAMPLE
I have 10 items in talbe People (Table people contains id,age,name,gender)
I want to echo out 3 out of 10 People by using their ID which are 1 trough 10
I know i can use this AND id IN(1, 5, 9)"; This just echoes them out 1 after another
Is there a way to echo out id 1 goes here , id 5 goes here and than id 9 goes there like in 3 different places with 3 different codes or something? is this even possible?
You could use:
class people
{
public function people()
{
$sql = $this->conn->prepare("SELECT * FROM `people`");
$sql->execute();
$result = $sql->fetch(PDO::FETCH_OBJ);
return $result;
}
}
then when you want certain information you could simply use in say index.php:
$fetch = new people();
$info = $fetch->people();
you can then run simple echo's such as $info->name or $info->id etc etc..
Depending on how you're searching for the user you could just add
WHERE `userid` = :id
$sql->bindParam(':id', $userid);
and add $userid into the people($userid)
But this will vary depending on how you're pulling out specific users.
use this code
<?php
//using PDO
try
{
$conn = new PDO('mysql:dbhost=myhost;dbname=mydbname;', 'user','pass');
}
catch (PDOException $e)
{
echo $e->getMessage();
}
$getId = $conn->query("
SELECT * FROM users
WHERE id = 1
AND id = 5
AND id = 9
");
while ($ids = $getId->fetch(PDO::FETCH_OBJ)
{
echo $getId->id . '<br>';
}

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 make custom function that returns all applicable rows in PHP

Below is my custom function that will take care the queries I call:
<?php
function cusQuery($sql){
$servername = "localhost";
$username = "root";
$password = "366y~V3g4n";
$dbname = "learnTurkishDesktop";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sql);
$output = array();
if($result->num_rows>0){
while ($row = $result->fetch_assoc()){
//as you see I tried to output all rows using print_r and it worked but I want it to just return an array containing all applicable rows and the call should handle the rest(formatting and which columns to include).
print_r($output[] = $row);
}
}else{
return array("0 results");
}
mysqli_close($conn);
}
?>
Now I am calling the my cusQuery function at my index.php
<?php
include('myFunctions.php');
$myQuery = cusQuery("SELECT Title, Content FROM user_created_notebooks");
echo "<h4>". $myQuery['Title']." ".$myQuery['Content']."</h4>";
?>
I tried using for loop in my function call but it didn't work. Below is the reference of what I'm trying to do:
http://www.dreamincode.net/forums/topic/126144-shortest-way-to-write-a-mysql-fetch-query/
I also tried not using while loop in the function itself just like the example given in the link but it only outputs the first applicable row.
I would love to hear new ideas too.
Thanks in advance.
The reference given works perfectly because only one row was returned from the database. "SELECT name FROM table WHERE ID = '$var'";
For your case the "$output[] = $row" statement creates a multidimentional array
of associative arrays contained with in a numeric array so the method does not work. below is how you should loop over the results
if(!empty($output)){
foreach($output as $row){
echo "h4 {$row['Title']} {$row['content']}";
}
}

Value returned from mysqli db call in php doesn't return values with newline chara

Ok so for some reason when I try and get values from a cell in my table with type TEXT it returns nothing, even thought there is text in the cell. It might be because there are new line characters in the text. In fact I'm certain that's the reason cause the only time things aren't return from the table is when there are newlines in it.
Here is the code where I get the data from my db:
function getRecord($cmo_name,$username,$password){
$i = 0;
$servername = "localhost";
$db = "my_db";
$return_array[] = "";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `my_table` WHERE `Name` = '".$name."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
foreach($row as $value)
array_push($return_array, $value);}
}
$conn->close();
return $return_array;
}
The above code returns nothing for the TEXT column that includes the newlines.
Help please!!!
Wrap your query result in PHP's TRIM function to strip the newline and returns out:
http://php.net/manual/en/function.trim.php

Categories