retrieving from database into table in php - php

im trying to retrieve data from database and display it into a table in php
i tried this
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
mysql_query("SET NAMES 'utf8'");
// get all products from products table
$result = mysql_query("SELECT *FROM glossary") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["glossaries"] = array();
echo "<table>";
echo "<tr>";
echo "<th>Symbol</th>";
echo "<th>Name</th>";
echo "<th>Description</th>";
echo "<th>Chapter</th>";
echo "</tr>";
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>". $row['Symbol'] ."</td>";
echo "<td>". $row['Name'] ."</td>";
echo "<td>". $row['Description'] ."</td>";
echo "<td>". $row['ID_Chapter'] ."</td>";
echo "</tr>";
}
echo "</table>";
header("Content-type: application/json; charset=utf-8");
// success
$response["success"] = 1;
// echoing JSON response
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
}
?>
but i will get a really strange result in the browser it will print the table tags td,tr... and the value between them like this:
<table><tr><th>Symbol</th><th>Name</th><th>Description</th><th>Chapter</th></tr><tr><td>θ </td><td></td><td></td><td>8</td></tr><tr><td>A ⊂ B</td><td>Proper subset / strict subset</td><td>Subset has fewer elements than the set</td><td>1</td></tr><tr><td>A'</td><td>Complement </td><td>Event A does not occur</td><td>1</td></tr></table>
why ?

header("Content-type: application/json; charset=utf-8");
That's... not JSON data. That's HTML. For example:
echo "<table>";
The default Content-type is probably HTML, so you can just remove the header line entirely. If you want to be explicit, you can be:
header("Content-type: text/html; charset=utf-8");
Basically what's happening is that you're explicitly telling the browser not to render the HTML, but to just treat it like JSON data. Which is why it's not rendering the HTML.

Related

oci_fetch_assoc it returns only the first row of the table

I am new to OCI and PHP and I am trying to print the data from an oracle table but I am getting an error. The error is that when printing the data of a table there is the oci_fetch_assoc function that only prints the first row of this table and I don't really understand why. This is the code block where I try to print the data:
<?php
include("../controllers/conexion.php");
$db_connection = oci_connect($db_esquema, $db_password, $db_instance);
$stid = oci_parse($db_connection, 'SELECT * FROM PRODUCTOS ');
oci_execute($stid);
while ($fila = oci_fetch_assoc($stid)) {
echo "<tr data-id=" . $fila['IDPRODUCTO'].">";
echo "<td>". $fila['NOMBRE']."</td>";
echo "<td>". $fila['PRECIO']."</td>";
echo "<td>". $fila['DESCRIPCION']."</td>";
echo "<td>"."</i><i class="fas fa-marker"></i></td>';
echo "</tr>";
}
oci_free_statement($stid);
oci_close($db_connection);
?>
This is the output but, there is much more data in the table:

Using php switch statement to display an image url in an html table from a mysql query

I have a MySQL table field which consists of a URL pointing towards an image. I'm using php and want the image to display in a table along with the other fields.
I think I need to use the PHP Switch statement and reference either the Row('Name') or Field Ref Number to create the code. I have this working fine in classic-asp, but need to code this in php.
$result = mysql_query("SELECT sometext,urlvalue,somemoretext FROM Table");
if (!$result) {
die("Query to show fields from table failed");
// Table fields
// sometext
// urlvalue an http image address such as http://www.example.com/image.jpg"
// somemoretext
$fields_num = mysql_num_fields($result);
echo "<table border='1'>
<tr bgcolor='yellow' align='left'>";
for($i=0; $i<$fields_num; $i++) {
$field = mysql_fetch_field($result);
echo "<th>{$field->name}</th>";
}
echo "\n";
// printing table rows
while($row = mysql_fetch_row($result)) {
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
switch $fields_num {
case "2":
// result cell looks like this ---->
// <td><a target='_blank' href='http://www.example.com/image.jpg'><img src='http://http://www.example.com/image.jpg'></a></td>
echo "<td><a target='_blank' href='" . $cell ."'><img src='" . $cell ."'></a></td>";
break;
default:
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
If you know the columns that you are going to be accessing and you know which column is the url, then you can use the following mysqli_-based code block with a condition in the inner loop to check for the matching column name.
If you don't know the columns that you will be dealing with, you can use filter_var($val, FILTER_VALIDATE_URL) assuming you only have one url string in your resultset. If you go for this second option, the one side effect on my code block is that you would have re-engineer the <th> portion.
I refuse to write answers using mysql_ functions, so please take this chance to modernize your code. I've included the connection declaration and basic error checking for your debugging convenience. (Never display error messages on your public site.)
Untested Code:
$columns = ['sometext', 'urlvalue', 'somemoretext'];
if (!$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db")) {
echo "Database Connect Error: " , $mysqli->connect_error;
} elseif (!$result = $mysqli->query("SELECT `" . implode('`, `', $columns) . "` FROM `Table`")) {
echo "Query Syntax Error: " , $mysqli->error;
if (!$result->num_rows) {
echo "No Rows Found";
} else {
echo "<table border='1'>";
echo "<tr bgcolor='yellow' align='left'>";
echo "<th>" , implode("</th><th>", $columns) , "</th>";
echo "</tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr>";
foreach ($row as $col => $val) {
echo "<td>";
if ($col == 'urlvalue') { // or if (filter_var($val, FILTER_VALIDATE_URL)) {
echo "<a target='_blank' href='$val'><img src='$val'></a>";
} else {
echo "$val";
}
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
}
}
I am not completely sure what you mean but rather than referencing the field number just reference the name.
if ($result->num_rows > 0) {
echo "<table border='1'><tr bgcolor='yellow' align='left'>";
while($row = $result->fetch_assoc()) {
echo "<th>".$row['field-name']."</th>";
echo "<tr>";
echo "<td><a target='_blank' href='" . $row['field-name'] ."'><img src='" . $row['field-name'] ."'>
</a>
</td>";
echo "</tr>";
}
echo "</table>";
}

Gather Table Names + Data using mysqli and php

I am trying to get the column names and data from a table using mysqli and php. Any help is appreciated.
I know how to do this in java by more or less this code:
String [] header= new String[numberOfColumns-1];
//Code to get column names in header array
String table = "<table><tr>"
for(int i=0;i<numberOfColumns-1;i++){
table= table + "<td>" + header[i] + </td>;
}
table = table + </tr>;
while(result.next()!=null){
table = table + <tr>
for (int j = 0 ; j < numberOfColumns-1 ; j++){
table = table + <td> + result.getString[j] + </td>
}
table = table + </tr>
}
But i have no idea how to do it in php. Each table is different but what i have to far for the one table:
include("config.php");
session_start();
$sql = ($_POST['q']);
$result = mysqli_query($db,$sql);
echo "<tr>";
echo "<td>First Name</td>";
echo "<td>Last Name</td>";
echo "<td>Date of Birth</td>";
echo "<td>Contact Details</td>";
echo "</tr>";
while($rowitem = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<tr>";
echo "<td>" . $rowitem['fname'] . "</td>";
echo "<td>" . $rowitem['lname'] . "</td>";
echo "<td>" . $rowitem['dob'] . "</td>";
echo "<td>" . $rowitem['contact'] . "</td>";*/
echo "</tr>";
}
echo "</table>"; //end table tag
EDIT: Is the implementation of the fetch_fields correct?
include("config.php");
session_start();
$sql = ($_POST['q']);
$result = mysqli_query($db,$sql);
$finfo = mysqli_fetch_fields($result);
echo "<tr>";
foreach ($finfo as $val) {
echo "<td>" . $val->name . "</td>"
}
echo "</tr>";
while($rowitem = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<tr>";
for($x =0; $x < count($finfo);$x++){
echo "<td>" . $rowitem[$x] . "/td";
}
echo "</tr>";
}
echo "</table>";
EDIT 2: Database Connection.php
<<?php
include("config.php");
session_start();
$sql = ($_GET['q']);
$result = mysqli_query($db,$sql);
echo "<table border='1' class='table_info'>";
$finfo = mysqli_fetch_fields($result);
echo "<tr>";
foreach ($finfo as $val) {
echo "<td>" . $val->name . "</td>";
}
echo "</tr>";
while($rowitem = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<tr>";
foreach ($row as $value) { (line 18)
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>"; //end table tag
?>
Error:
Notice: Undefined variable: row in databaseConnection.php on line 18
Warning: Invalid argument supplied for foreach() in databaseConnection.php on line 18
You can call mysqli_fetch_fields on the $result object, and retrieve the name property for each object in the returned array. See documentation for examples.
There are a couple ways to do this:
Use array_keys() to grab the names of the keys from an associative array:
$rowitem = mysqli_fetch_array($result, MYSQLI_ASSOC);
$header = array_keys($rowitem);
Use mysqli_fetch_fields() to grab the field objects, and parse out the names into an array using array_map():
// Helper function to use in array_map
// (For PHP < 5.3. If >= 5.3.0, use the second version)
function getFieldName($field) { return $field->name; }
// For PHP < 5.3:
$header = array_map("getFieldName", mysqli_fetch_fields($result));
// For PHP >= 5.3.0:
$header = array_map(function($o) { return $o->name; }, mysqli_fetch_fields($result));
As mentioned you can use $result->fetch_fields() to get the field information from the result and this includes the name of each field.
For what you're trying to acheive this code should work for pretty much any table/query:
<?php
/* Connect to mysql */
$mysqli = new mysqli("localhost", "username", "password", "database");
/* Check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Your query */
$query = "SELECT * from table";
if ($result = $mysqli->query($query)) {
/* Output HTML table */
echo "<table border='1'>";
/* Get field information for all returned columns */
$finfo = $result->fetch_fields();
/* Output each column name in first table row */
echo "<tr>";
foreach ($finfo as $val) {
echo "<td>".$val->name."</td>";
}
echo "</tr>";
/* Fetch the result and output each row into a table row */
while($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
$result->free();
echo "</table>";
}
$mysqli->close();
(Obviously you should never query a database from a $_POST variable without some serious sanitisation of the input, but I'll assume that was just for your convenience.)
You can Echo in a table..
$result = mysqli_query($db,$sql)
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysqli_num_fields($result);
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysqli_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysqli_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysqli_free_result($result);`

Query doesn't work via php script

I have a simple php script which performs a simple SQL query twice. Query works perfectly for the first but for the second time error appears;
Notice: Trying to get property of non-object in C:\apache\localhost\www\study.kg\webstore\web_store.php on line 48
Fatal error: Call to a member function free() on a non-object in C:\apache\localhost\www\study.kg\webstore\web_store.php on line 80
First, we make a query to 'categories' table. Everything is good.
Second, we make the same query to 'shoes' table. Everything is bad, because
$query = "SELECT * FROM shoes";
$result = $db->query($query);
returns FALSE value.
But why? The first it worked perfectly. The tables are the same, if you mean encoding and etc. So, as you can guess, my first table displays itself perfectly, second table doesn't show any data at all.
Here is a full snippet.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Лабораторная: интернет-магазин обуви</title>
</head>
<body>
<?php
#$db = new mysqli('localhost', 'dzhakipov', 'asd12345', 'webshop');
if (mysqli_connect_errno()) {
echo 'Error: could not connect to database. Please try again later.';
exit;
}
$query = "SELECT * FROM categories";
$result = $db->query($query);
$num_results = $result->num_rows;
?>
<table>
<tr>
<td>id</td>
<td>Название</td>
<td>Описание</td>
<td>Поставщик</td>
<td>Продавец</td>
<td>Адрес склада</td>
</tr>
<?php
for ($i = 0; $i < $num_results; $i++) {
$row = $result->fetch_assoc();
echo "<tr>";
echo "<td>" .stripslashes($row['id']). "</td>";
echo "<td>" .htmlspecialchars(stripslashes($row['name'])). "</td>";
echo "<td>" .stripslashes($row['description']). "</td>";
echo "<td>" .stripslashes($row['supplier']). "</td>";
echo "<td>" .stripslashes($row['salesman']). "</td>";
echo "<td>" .stripslashes($row['storage_address']). "</td>";
echo "</tr>";
}
echo "</table>";
$query = "SELECT * FROM shoes";
$result = $db->query($query);
$num_results = $result->num_rows; // LINE 48 #############################
?>
<table>
<tr>
<td>id</td>
<td>categoryid</td>
<td>Название</td>
<td>Пол</td>
<td>Размер</td>
<td>Сезон</td>
<td>Внешний материал</td>
<td>Внутренний материал</td>
<td>Цвет</td>
<td>Описание</td>
</tr>
<?php
for ($i = 0; $i < $num_results; $i++) {
$row = $result->fetch_assoc();
echo "<tr>";
echo "<td>" .stripslashes($row['id']). "</td>";
echo "<td>" .stripslashes($row['categoryid']). "</td>";
echo "<td>" .htmlspecialchars(stripslashes($row['name'])). "</td>";
echo "<td>" .stripslashes($row['sex']). "</td>";
echo "<td>" .stripslashes($row['size']). "</td>";
echo "<td>" .stripslashes($row['season']). "</td>";
echo "<td>" .stripslashes($row['inner_material']). "</td>";
echo "<td>" .stripslashes($row['outer_material']). "</td>";
echo "<td>" .stripslashes($row['colour']). "</td>";
echo "<td>" .stripslashes($row['price']). "</td>";
echo "</tr>";
}
echo "</table>";
$result->free(); // LINE 80 #############################
$db->close();
?>
</body>
</html>
Thanks for attention.
See this http://php.net/manual/en/function.mysql-free-result.php before using result for the second time.
You also can change the second $result into $result2 to let It work.
I'd try freeing the first result before querying for the second
$result->free();
$query = "SELECT * FROM shoes";
$result = $db->query($query);
Second, though I'm not familiar with mysqli (big PDO fan here), I believe false might be a possible result of a query, so you should wrap the result traversing in an if block.
if($result) {
$num_results = $result->num_rows;
...
$result->free();
}
As you store your MySQL query as a String in $Query variable now for the php to execute this query you need to use mysqli_query() that will retrieve data from DB

Add link to echo'd HTML from SQL data

Back with another quick question. I have this code below which echo's out product names from a database. What I want to do is make the echoed out product names a link to another page called product.php, each link needs to have a unique ID, for example
Product Name
How would I go about doing this? Many thanks. I will point out that I am very new to PHP.
<?php
//create an ADO connection and open the database
$conn = new COM("ADODB.Connection");
$conn->open("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\WebData\Northwind.mdb");
//execute an SQL statement and return a recordset
$rs = $conn->execute("SELECT product_name FROM Products");
$num_columns = $rs->Fields->Count();
echo "<table border='1'>";
echo "<tr><th>Name</th></tr>";
while (!$rs->EOF) //looping through the recordset (until End Of File)
{
echo "<tr>";
for ($i=0; $i < $num_columns; $i++) {
echo "<td>" . $rs->Fields($i)->value . "</td>";
}
echo "</tr>";
$rs->MoveNext();
}
echo "</table>";
//close the recordset and the database connection
$rs->close();
$rs = null;
$conn->close();
$conn = null;
?>
Assuming your Products table has a unique ID field called "id", change your select to:
$rs = $conn->execute("SELECT id, product_name FROM Products");
And when you want to create a link, use that field and pass it into the URL. So you'd have product.php?id=<?= $thatIdField; ?>.
Example code:
echo "<table border='1'>";
echo "<tr><th>Name</th></tr>";
while (!$rs->EOF) //looping through the recordset (until End Of File)
{
echo "<tr>";
for ($i=0; $i < $num_columns; $i++) {
echo "<td>" . $rs->Fields($i)->value . "</td>";
}
echo "</tr>";
$rs->MoveNext();
}
echo "</table>";

Categories