How can I convert mysql query (group_concat) in postgresql query - php

I want to convert this bellow two MySQL query(specially second query) in PostgreSQL query.because I want to use this bellow query for PostgreSQL database.So how can i write this bellow query in PostgreSQL.So that this bellow query support PostgreSQL Database.
<?php
$data = [];
$branchs = [];
$query=mysqli_query($con,"SELECT DISTINCT branchcode FROM brackinfo2 WHERE event_id BETWEEN 71 AND 75");
while($values=mysqli_fetch_array($query)){
$branchs[] = $values['branchcode'];
}
$query=mysqli_query($con,"SELECT CONCAT(section,'.', sub_sec_id) AS si, GROUP_CONCAT (CONCAT(branchcode,':',question_point)) as brands, section, sub_sec_id, point as fullmark FROM brackinfo2 WHERE event_id BETWEEN 71 AND 75 GROUP BY branchcode,si");
while($values=mysqli_fetch_array($query)){
$data[$values['si']]['fullmark'] = $values['fullmark'];
$data[$values['si']]['section'] = $values['section'];
$tmp = explode(",", $values['brands']);
foreach ($tmp as $key => $value) {
$tmp2 = explode(":", $value);
$data[$values['si']]['branchs'][$tmp2[0]] = $tmp2[1];
}
}
?>
<table>
<thead>
<tr>
<th>SI</th>
<th>Full Marks</th>
<th>Section & Indicator Name</th>
<?php
foreach ($branchs as $branch) {
echo "<th> Branch Name<br>($branch)</th>";
}?>
</tr>
</thead>
<tbody>
<?php
foreach ($data as $si => $info)
{
echo "<tr>";
echo "<td>$si</td>";
echo "<td>{$info['fullmark']} </td>";
echo "<td>{$info['section']} </td>";
foreach( $branchs as $branch)
{
if (isset($info['branchs'][$branch])) {
echo "<td>{$info['branchs'][$branch]}</td>";
} else {
echo "<td></td>";
}
}
echo "</tr>";
}
?>
</tbody>
</table>

You need to use PHP PDO to support both MYSQL and POSTGRESQL with same query(most of the case) OR use pg_connect(), pg_query() and pg_fetch_array() specifically for postgresql only. See here for more about PHP PDO query examples
Connection example in MYSQL:
<?php
try {
$dbuser = 'mysql';
$dbpass = 'abc123';
$dbhost = 'localhost';
$dbname='mysql';
$dbh = new PDO('mysql:host=$dbhost;dbname=$dbname', $dbuser, $dbpass);
}catch (PDOException $e){
echo "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Connection example in POSTGRESQL:
<?php
try{
$dbuser = 'postgres';
$dbpass = 'abc123';
$dbhost = 'localhost';
$dbname='postgres';
$dbh = new PDO("pgsql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}catch (PDOException $e){
echo "Error : " . $e->getMessage() . "<br/>";
die();
}
?>

Related

get all values of columns in sql php [duplicate]

I want to retrieve the values from a database table and show them in a html table in a page.
I already searched for this but I couldn't find the answer, although this surely is something easy (this should be the basics of databases lol). I guess the terms I've searched are misleading.
The database table name is tickets, it has 6 fields right now (submission_id, formID, IP, name, email and message) but should have another field called ticket_number.
How can I get it to show all the values from the db in a html table like this:
<table border="1">
<tr>
<th>Submission ID</th>
<th>Form ID</th>
<th>IP</th>
<th>Name</th>
<th>E-mail</th>
<th>Message</th>
</tr>
<tr>
<td>123456789</td>
<td>12345</td>
<td>123.555.789</td>
<td>John Johnny</td>
<td>johnny#example.com</td>
<td>This is the message John sent you</td>
</tr>
</table>
And then all the other values below 'john'.
Example taken from W3Schools: PHP Select Data from MySQL
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
It's a good place to learn from!
Try this: (Completely Dynamic...)
<?php
$host = "localhost";
$user = "username_here";
$pass = "password_here";
$db_name = "database_name_here";
//create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = mysqli_connect($host, $user, $pass, $db_name);
//get results from database
$result = mysqli_query($connection, "SELECT * FROM products");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
$all_property[] = $property->name; //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
Here is an easy way to fetch data from a MySQL database using PDO.
define("DB_HOST", "localhost"); // Using Constants
define("DB_USER", "YourUsername");
define("DB_PASS", "YourPassword");
define("DB_NAME", "Yourdbname");
$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset-utf8mb4", DB_USER, DB_PASS);
$print = ""; // assign an empty string
$stmt = $dbc->query("SELECT * FROM tableName"); // fetch data
$stmt->setFetchMode(PDO::FETCH_OBJ);
$print .= '<table border="1px">';
$print .= '<tr><th>First name</th>';
$print .= '<th>Last name</th></tr>';
while ($names = $stmt->fetch()) { // loop and display data
$print .= '<tr>';
$print .= "<td>{$names->firstname}</td>";
$print .= "<td>{$names->lastname}</td>";
$print .= '</tr>';
}
$print .= "</table>";
echo $print;
Learn more about PHP and the MySQLi Library at PHP.net.
First, start a connection to the database. Do this by making all the string variables needed in order to connect, adjusting them to fit your environment, then creating a new connection object with new mysqli() and initializing it with the previously made variables as its parameters. Now, check the connection for errors and display a message whether any were found or not. Like this:
<?php
$servername = "localhost";
$username = "root";
$password = "yourPassword";
$database = "world";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $database);
echo "Connected successfully<br>";
?>
Next, make a variable that will hold the query as a string, in this case its a select statement with a limit of 100 records to keep the list small. Then, we can execute it by calling the mysqli::query() function from our connection object. Now, it's time to display some data. Start by opening up a <table> tag through echo, then fetch one row at a time in the form of a numerical array with mysqli::fetch_row() which can then be displayed with a simple for loop. mysqli::field_count should be self explanatory. Don't forget to use <td></td> for each value, and also to open and close each row with echo"<tr>" and echo"</tr>. Finally we close the table, and the connection as well with mysqli::close().
<?php
$query = "select * from city limit 100;";
$queryResult = $conn->query($query);
echo "<table>";
while ($queryRow = $queryResult->fetch_row()) {
echo "<tr>";
for($i = 0; $i < $queryResult->field_count; $i++){
echo "<td>$queryRow[$i]</td>";
}
echo "</tr>";
}
echo "</table>";
$conn->close();
?>
First, connect to the database:
$conn=mysql_connect("hostname","username","password");
mysql_select_db("databasename",$conn);
You can use this to display a single record:
For example, if the URL was /index.php?sequence=123, the code below would select from the table, where the sequence = 123.
<?php
$sql="SELECT * from table where sequence = '".$_GET["sequence"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$result=mysql_fetch_array($rs);
echo '<table>
<tr>
<td>Forename</td>
<td>Surname</td>
</tr>
<tr>
<td>'.$result["forename"].'</td>
<td>'.$result["surname"].'</td>
</tr>
</table>';
?>
Or, if you want to list all values that match the criteria in a table:
<?php
echo '<table>
<tr>
<td>Forename</td>
<td>Surname</td>
</tr>';
$sql="SELECT * from table where sequence = '".$_GET["sequence"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
echo '<tr>
<td>'.$result["forename"].'</td>
<td>'.$result["surname"].'</td>
</tr>';
}
echo '</table>';
?>
Surely a better solution would by dynamic so that it would work for any query without having to know the column names?
If so, try this (obviously the query should match your database):
// You'll need to put your db connection details in here.
$conn = new mysqli($server_hostname, $server_username, $server_password, $server_database);
// Run the query.
$result = $conn->query("SELECT * FROM table LIMIT 10");
// Get the result in to a more usable format.
$query = array();
while($query[] = mysqli_fetch_assoc($result));
array_pop($query);
// Output a dynamic table of the results with column headings.
echo '<table border="1">';
echo '<tr>';
foreach($query[0] as $key => $value) {
echo '<td>';
echo $key;
echo '</td>';
}
echo '</tr>';
foreach($query as $row) {
echo '<tr>';
foreach($row as $column) {
echo '<td>';
echo $column;
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
Taken from here: https://www.antropy.co.uk/blog/handy-php-snippets/
mysql_connect("localhost","root","");
mysql_select_db("database");
$query=mysql_query("select * from studenti");
$x=#mysql_num_rows($query);
echo "<a href='file.html'>back</a>";
echo "<table>";
$y=mysql_num_fields($query);
echo "<tr>";
for($i=0 ,$i<$y,$i++)
{
$values=mysql_field_name($query,$i);
echo "<th>$values</th>";
}
echo "</tr>";
while(list($p ,$n $your_table_list)=mysql_fetch_row($query))
{
print("<tr>\n".
"<td>$p</td>".
"</tr>/n");
}
?>
<?php
$mysql_hostname = "localhost";
$mysql_user = "ram";
$mysql_password = "ram";
$mysql_database = "mydb";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Oops some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Oops some thing went wrong");// we are now connected to database
$result = mysql_query("SELECT * FROM users"); // selecting data through mysql_query()
echo '<table border=1px>'; // opening table tag
echo'<th>No</th><th>Username</th><th>Password</th><th>Email</th>'; //table headers
while($data = mysql_fetch_array($result))
{
// we are running a while loop to print all the rows in a table
echo'<tr>'; // printing table row
echo '<td>'.$data['id'].'</td><td>'.$data['username'].'</td><td>'.$data['password'].'</td><td>'.$data['email'].'</td>'; // we are looping all data to be printed till last row in the table
echo'</tr>'; // closing table row
}
echo '</table>'; //closing table tag
?>
it would print the table like this
just read line by line so that you can understand it easily..
OOP Style :
At first connection with database.
<?php
class database
{
public $host = "localhost";
public $user = "root";
public $pass = "";
public $db = "db";
public $link;
public function __construct()
{
$this->connect();
}
private function connect()
{
$this->link = new mysqli($this->host, $this->user, $this->pass, $this->db);
return $this->link;
}
public function select($query)
{
$result = $this->link->query($query) or die($this->link->error.__LINE__);
if($result->num_rows>0)
{
return $result;
}
else
{
return false;
}
}
?>
Then :
<?php
$db = new database();
$query = "select * from data";
$result = $db->select($query);
echo "<table>";
echo "<tr>";
echo "<th>Name </th>";
echo "<th>Roll </th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td> $row[name]</td>";
echo "<td> $row[roll]</td>";
echo "</tr>";
}
echo "</table>";
?>

Show list of users in my database [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 2 years ago.
Hey guys i am trying to display a list off all users in my database. not sure how to get along with it. Getting confused with mysqli and sql..
my dadtabase connection file is :
class Dbconnect extends PDO
{
private $dbengine = 'mysql';
private $dbhost = 'localhost';
private $dbuser = 'root';
private $dbpassword = '';
private $dbname = 'test';
public $dbh = null;
function __construct()
{
try{
$this->dbh = new PDO("".$this->dbengine.":host=$this->dbhost; dbname=$this->dbname", $this->dbuser, $this->dbpassword);
$this->dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
}
catch (PDOException $e){
$e->getMessage();
}
}
}
?>
I tired this on it but getting an error.
$sqlget = "SELECT * FROM user";
$sqldata = mysqli_query($dbh, $sqlget) or die('error users');
echo "<table>";
echo " <th>User Name </th> <th>Email</th> <th> Some Name</th>";
while($row = mysql_fetch_array($sqldata, MYSQL_ASSOC)) {
echo "<tr><td>";
echo $row['name'];
echo "</td><td>";
echo $row['email'];
echo "</td><td>";
echo $row['some'];
echo "</td>";
}
echo "</table>"
?>
I have also created a table to insert the data on them..
User Name . Email . lastName
not sure how to proceed. especially as i just got into php.. help will be much appreciaited to come up with a php handling file for me.
and any further tips to delete or edit users...Thanks in Advance people..!!!!!!
You must use PDO functions:
$db = new PDO("".$dbengine.":host=$dbhost; dbname=$dbname", $dbuser, $dbpassword);
$q = "SELECT * FROM users";
$result = $db->query($q)->fetchall();
foreach ($result as $user) {
echo $user['name'];
}
Try this:
$dbh = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'root', '');
$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$sqlget = "SELECT * FROM user";
$sqldata = $dbh->query($sqlget) or die('error users');
echo "<table>";
echo " <th>User Name </th> <th>Email</th> <th> Some Name</th>";
while($row = $sqldata->fetch(PDO::FETCH_ASSOC)) {
echo "<tr><td>";
echo $row['name'];
echo "</td><td>";
echo $row['email'];
echo "</td><td>";
echo $row['some'];
echo "</td>";
}
echo "</table>"

PHP MYSQLI fetch Errors

At school my teacher told me a lot of thing about coding in PHP using a POSTGRES DATABASE.
But when I started to use MYSQLI Server i couldn't do a lot of thing.
First of all the functions.
My teacher told me to do this type of function
$rows = getBuildings();
if (count($elenco) == 0) {
print "<hr> No buildings here </hr>";
} else {
?>
<thead>
<tr>
<th>address</th>
<th>town</th>
<th>Manager</th>
</tr>
</thead>
<tbody>
<?php
foreach ($elenco as $riga) {
?>
<tr>
<td> <?= $row->address ?></td>
<td> <?= $row->town ?></td>
<td> <?= $row->name ?> <?= $riga->surname ?> </td>
</tr>
<?php
}
?>
</tbody>
</table>
</tbody>
</table>
<?php
}
?>
</body>
</html>
<?php
function getBuldings() {
global $db;
$sql = "select * from buildings, boss
where boss.codBo=buildings.codBu";
$rows = array();
if (!DB::isError($tab = $db->query($sql))) {
while ($row = $tab->fetchRow(DB_FETCHMODE_OBJECT)) {
$rows[] = $row;
}
} else {
die("ErrorSQL:" . $tab->getMessage());
}
return $rows;
}
?>
But to get it working in MYSQL i had to do a lot of changes. In fact there was an error in !BD::isError. I had to change the connection.php in from this one
<?php
Session_Start();
require_once("DB.php");
$db = DB::connect("pgsql:etc....");
if (DB::isError($db)) {
die("Error: " . $db->getMessage());
}
?>
to this one
<?php
$servername = "localhost";
$username = "test";
$password = "";
$dbname = "test";
// Create connection
$db = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$a = mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
echo "Connected successfully " . $a . " ";
?>
In order to show the result of the query my code had become this:
<body>
<?php
$rows = getBoss();
if (count($rows) == 0) {
print "<h2>No Boss here</h2>";
} else {
foreach ($rows as $row) {
print "<p>" . $row['name'] . "</p>";
print "<p>" . $row['surname'] . "</p>";
}
}
?>
<?php
function getBoss() {
global $db;
$sql = "select *
from test_boss
order by name, surname";
$rows = array();
if ($tab = $db->query($sql)) {
while ($row = $tab->fetch_array()) {
$rows[] = $row;
}
return $elenco;
} else {
die("Errore sql: " . $tab->getMessage() . ":" . $sql);
}
}
?>
</body>
</html>
That in facts works pretty well, but I had to change FETCH_ROW to FETCH_ARRAY.
I could not use anymore the method of posting the data from the $rows value.
<?= $row->name ?>
Because there was an error
Notice: Trying to get property of non-object
but I had to use
print "<p>".$row['name']."</p>";
What can I do in order to use the method FETCH_ROW corretly?
You can type cast the array to an object by tweaking the code slight.
if you want to retrieve an object in form of $row->name then your code will be.
while ($row= $tab->fetch_array()) {
$rows[] = (object)$row;
}
OR
while ($row= $tab->fetch_object()) {
$rows[] = $row;
}

PHP Loop based on PHP values

I am in the process of learning PHP and I am trying to start a loop based on the values taken from a MySQL table.
In the MySQL table I have a course name with a start_year and duration. What I would like to achieve is something along the following code example:
$results = $conn->query($sql);
for (int $i = $results as $row['start_year']; $i <= $results as $row['duration']; i++) {
echo "<tr>" . $i . "</tr>";
}
Any help will be greatly appreciated!
Thanks
Code Update:
<thead>
<tr>
<th scope="col" class="wide" >Year</th>
</tr>
</thead>
<!-- Table body -->
<tbody>
<?php
try {
$dsn = "mysql:host=localhost;dbname=".$mysqldatabase;
// try connecting to the database
$conn = new PDO($dsn, $mysqlusername, $mysqlpassword);
// turn on PDO exception handling
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
// enter catch block in event of error in preceding try block
echo "Connection failed: ".$e->getMessage();
}
try {
$sql="SELECT *
FROM courses
WHERE courses.cid = \"". $_GET['courses'] . "\"
ORDER BY courses.title";
$results=$conn->query($sql);
if ($results->rowcount()==0){
} else {
//generate table of results
foreach ($results as $row){
$years=range($row['startYear'],$row['startYear']+$row['duration']-1);
echo "<tr><td>";
echo implode(",",$years."</td></tr>");
}
} catch ( PDOException $e ) {
echo "Query failed: " . $e->getMessage();
}
$conn = null;
?>
You can find this answer on the php manual
$results = $conn->query($sql);
foreach ($results as $row){
$years=range($row['start_year'],$row['start_year']+$row['duration']-1);
echo implode(",",$years)."<br/>";
}

Show values from a MySQL database table inside a HTML table on a webpage

I want to retrieve the values from a database table and show them in a html table in a page.
I already searched for this but I couldn't find the answer, although this surely is something easy (this should be the basics of databases lol). I guess the terms I've searched are misleading.
The database table name is tickets, it has 6 fields right now (submission_id, formID, IP, name, email and message) but should have another field called ticket_number.
How can I get it to show all the values from the db in a html table like this:
<table border="1">
<tr>
<th>Submission ID</th>
<th>Form ID</th>
<th>IP</th>
<th>Name</th>
<th>E-mail</th>
<th>Message</th>
</tr>
<tr>
<td>123456789</td>
<td>12345</td>
<td>123.555.789</td>
<td>John Johnny</td>
<td>johnny#example.com</td>
<td>This is the message John sent you</td>
</tr>
</table>
And then all the other values below 'john'.
Example taken from W3Schools: PHP Select Data from MySQL
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
It's a good place to learn from!
Try this: (Completely Dynamic...)
<?php
$host = "localhost";
$user = "username_here";
$pass = "password_here";
$db_name = "database_name_here";
//create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = mysqli_connect($host, $user, $pass, $db_name);
//get results from database
$result = mysqli_query($connection, "SELECT * FROM products");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
$all_property[] = $property->name; //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
Here is an easy way to fetch data from a MySQL database using PDO.
define("DB_HOST", "localhost"); // Using Constants
define("DB_USER", "YourUsername");
define("DB_PASS", "YourPassword");
define("DB_NAME", "Yourdbname");
$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset-utf8mb4", DB_USER, DB_PASS);
$print = ""; // assign an empty string
$stmt = $dbc->query("SELECT * FROM tableName"); // fetch data
$stmt->setFetchMode(PDO::FETCH_OBJ);
$print .= '<table border="1px">';
$print .= '<tr><th>First name</th>';
$print .= '<th>Last name</th></tr>';
while ($names = $stmt->fetch()) { // loop and display data
$print .= '<tr>';
$print .= "<td>{$names->firstname}</td>";
$print .= "<td>{$names->lastname}</td>";
$print .= '</tr>';
}
$print .= "</table>";
echo $print;
Learn more about PHP and the MySQLi Library at PHP.net.
First, start a connection to the database. Do this by making all the string variables needed in order to connect, adjusting them to fit your environment, then creating a new connection object with new mysqli() and initializing it with the previously made variables as its parameters. Now, check the connection for errors and display a message whether any were found or not. Like this:
<?php
$servername = "localhost";
$username = "root";
$password = "yourPassword";
$database = "world";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $database);
echo "Connected successfully<br>";
?>
Next, make a variable that will hold the query as a string, in this case its a select statement with a limit of 100 records to keep the list small. Then, we can execute it by calling the mysqli::query() function from our connection object. Now, it's time to display some data. Start by opening up a <table> tag through echo, then fetch one row at a time in the form of a numerical array with mysqli::fetch_row() which can then be displayed with a simple for loop. mysqli::field_count should be self explanatory. Don't forget to use <td></td> for each value, and also to open and close each row with echo"<tr>" and echo"</tr>. Finally we close the table, and the connection as well with mysqli::close().
<?php
$query = "select * from city limit 100;";
$queryResult = $conn->query($query);
echo "<table>";
while ($queryRow = $queryResult->fetch_row()) {
echo "<tr>";
for($i = 0; $i < $queryResult->field_count; $i++){
echo "<td>$queryRow[$i]</td>";
}
echo "</tr>";
}
echo "</table>";
$conn->close();
?>
First, connect to the database:
$conn=mysql_connect("hostname","username","password");
mysql_select_db("databasename",$conn);
You can use this to display a single record:
For example, if the URL was /index.php?sequence=123, the code below would select from the table, where the sequence = 123.
<?php
$sql="SELECT * from table where sequence = '".$_GET["sequence"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$result=mysql_fetch_array($rs);
echo '<table>
<tr>
<td>Forename</td>
<td>Surname</td>
</tr>
<tr>
<td>'.$result["forename"].'</td>
<td>'.$result["surname"].'</td>
</tr>
</table>';
?>
Or, if you want to list all values that match the criteria in a table:
<?php
echo '<table>
<tr>
<td>Forename</td>
<td>Surname</td>
</tr>';
$sql="SELECT * from table where sequence = '".$_GET["sequence"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
echo '<tr>
<td>'.$result["forename"].'</td>
<td>'.$result["surname"].'</td>
</tr>';
}
echo '</table>';
?>
Surely a better solution would by dynamic so that it would work for any query without having to know the column names?
If so, try this (obviously the query should match your database):
// You'll need to put your db connection details in here.
$conn = new mysqli($server_hostname, $server_username, $server_password, $server_database);
// Run the query.
$result = $conn->query("SELECT * FROM table LIMIT 10");
// Get the result in to a more usable format.
$query = array();
while($query[] = mysqli_fetch_assoc($result));
array_pop($query);
// Output a dynamic table of the results with column headings.
echo '<table border="1">';
echo '<tr>';
foreach($query[0] as $key => $value) {
echo '<td>';
echo $key;
echo '</td>';
}
echo '</tr>';
foreach($query as $row) {
echo '<tr>';
foreach($row as $column) {
echo '<td>';
echo $column;
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
Taken from here: https://www.antropy.co.uk/blog/handy-php-snippets/
mysql_connect("localhost","root","");
mysql_select_db("database");
$query=mysql_query("select * from studenti");
$x=#mysql_num_rows($query);
echo "<a href='file.html'>back</a>";
echo "<table>";
$y=mysql_num_fields($query);
echo "<tr>";
for($i=0 ,$i<$y,$i++)
{
$values=mysql_field_name($query,$i);
echo "<th>$values</th>";
}
echo "</tr>";
while(list($p ,$n $your_table_list)=mysql_fetch_row($query))
{
print("<tr>\n".
"<td>$p</td>".
"</tr>/n");
}
?>
<?php
$mysql_hostname = "localhost";
$mysql_user = "ram";
$mysql_password = "ram";
$mysql_database = "mydb";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Oops some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Oops some thing went wrong");// we are now connected to database
$result = mysql_query("SELECT * FROM users"); // selecting data through mysql_query()
echo '<table border=1px>'; // opening table tag
echo'<th>No</th><th>Username</th><th>Password</th><th>Email</th>'; //table headers
while($data = mysql_fetch_array($result))
{
// we are running a while loop to print all the rows in a table
echo'<tr>'; // printing table row
echo '<td>'.$data['id'].'</td><td>'.$data['username'].'</td><td>'.$data['password'].'</td><td>'.$data['email'].'</td>'; // we are looping all data to be printed till last row in the table
echo'</tr>'; // closing table row
}
echo '</table>'; //closing table tag
?>
it would print the table like this
just read line by line so that you can understand it easily..
OOP Style :
At first connection with database.
<?php
class database
{
public $host = "localhost";
public $user = "root";
public $pass = "";
public $db = "db";
public $link;
public function __construct()
{
$this->connect();
}
private function connect()
{
$this->link = new mysqli($this->host, $this->user, $this->pass, $this->db);
return $this->link;
}
public function select($query)
{
$result = $this->link->query($query) or die($this->link->error.__LINE__);
if($result->num_rows>0)
{
return $result;
}
else
{
return false;
}
}
?>
Then :
<?php
$db = new database();
$query = "select * from data";
$result = $db->select($query);
echo "<table>";
echo "<tr>";
echo "<th>Name </th>";
echo "<th>Roll </th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td> $row[name]</td>";
echo "<td> $row[roll]</td>";
echo "</tr>";
}
echo "</table>";
?>

Categories