Using MySql to populate a html table using a specific column - php

Essentially, I am creating a movie ordering system that has 7 movie genres, and I want each movie tab to populate according to genre. At this point I cant even get the table to show up. Can anyone help me out?
<div id="content">
<table>
<tr><th>Name</th> <th>Genre</th> <th>Year</th> <th>Rating</th></tr>
<?php
//connect to database
$dbc = mysql_connect('localhost' , 'username' , 'password');
$test = mysql_select_db('movies', $dbc);
if ($test = mysql_select_db('movies', $dbc))//test
{
$query = "SELECT * FROM 'movies' WHERE 'genre' = 'Action'";
//call query
$result = mysql_query($query, $dbc);
while ($row = mysql_fetch_array($result))
{
?>
<tr>
<td><?php print $row['name']; ?></td>
<td><?php print $row['genre']; ?></td>
<td><?php print $row['year']; ?></td>
<td><?php print $row['rating'];?></td>
</tr>
<table>
<?php
}//close the while loop
}//close the if statement
mysql_close($dbc);
?>

First of all, do not use mysql because of secure problems and it will be not suported in PHP later. Read about this http://php.net/manual/en/function.mysql-connect.php .
Try to use PDO or mysqli, for example :
$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 'movies' WHERE 'genre' = 'Action'");
while($row = mysqli_fetch_array($result))
{
echo $row['name'];
echo "<br>";
}
mysqli_close($con);

Related

PHP won't display result of echo

I have a problem, when I try with this code without hosting I'm getting result but when I try it on host php won't display result, I know Select * is not good nowadays but if you can please help.
This is screen how it looks like:
Here is code:
$conn = mysql_connect("localhost", "username", "password");
if (!$conn) {
die("no connection".mysql_error());
}
$db = mysql_select_db("db_name");
mysql_set_charset('utf8', $conn);
I'm using this code on HTML:
<thead>
<tr>
<th>id</th>
<th>სახელი</th>
<th>ტექსტი</th>
<th>პატარა ტექსტი</th>
<th>სურათი</th>
<th>წაშლა</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM news";
$result = mysql_query($sql);
while ($data = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$data['id']."</td>";
echo "<td>".$data['name']."</td>";
echo "<td>".substr($data['article'], 155,300)."</td>";
echo "<td>".substr($data['text'], 155)."</td>";
echo "<td>".$data['img']."</td>";
echo "<td>წაშლა</td>";
echo "</tr>";}
?>
</tbody>

Weird data output about PHP & MySQL

It's wired that only Field name is correct but others. I can't get the the expected result from the code.
How get the correct meta data from the database?
The expected result
Actual result
<?php
// Open a connection to the server and USE the winestore
$link = mysqli_connect("localhost","root","","winestore");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Run a query on the wine table in the winestore database to retrieve
// one row
$query = "SELECT * FROM wine LIMIT 1";
$result = mysqli_query($link, $query);
// Output a header, with headers spaced by padding
print "\n" .
str_pad("Field", 20) .
str_pad("Type", 14) .
str_pad("Null", 6) .
str_pad("Key", 5) .
str_pad("Extra", 12) . "\n";
// How many attributes are there?
$x = mysqli_num_fields($result);
// for each of the attributes in the result set
for($y=0;$y<$x;$y++)
{
// Get the meta-data for the attribute
$info = mysqli_fetch_field ($result);
// Print the attribute name
print str_pad($info->name, 20);
// Print the data type
print str_pad($info->type, 6);
// Print the field length in brackets e.g.(2)
print str_pad("({$info->max_length})", 8);
// Print out YES if attribute can be NULL
if ($info->not_null != 1)
print " YES ";
else
print " ";
// Print out selected index information
if ($info->primary_key == 1)
print " PRI ";
elseif ($info->multiple_key == 1)
print " MUL ";
elseif ($info->unique_key == 1)
print " UNI ";
// If zero-filled, print this
if ($info->zerofill)
print " Zero filled";
// Start a new line
print "\n";
}
mysqli_free_result($result);
mysqli_close($link);
?>
As per the query the expected result is the detail of the table structure and for that one can use mysql Describe table query which will provide the structure of the table.
<?php
$con = mysqli_connect(HOST,USER,PASSWORD,DATABASE NAME);
$data = mysqli_query($con,"DESCRIBE tablename");
?>
<table>
<tr>
<td>Field</td>
<td>Type</td>
<td>Null</td>
<td>Key</td>
<td>Default</td>
<td>Extra</td>
</tr>
<?php while($row=mysqli_fetch_array($data,MYSQLI_ASSOC)){ ?>
<tr>
<td><?php echo $row['Field']; ?></td>
<td><?php echo $row['Type']; ?></td>
<td><?php echo $row['Null']; ?></td>
<td><?php echo $row['Key']; ?></td>
<td><?php echo $row['Default']; ?></td>
<td><?php echo $row['Extra']; ?></td>
</tr>
<?php } ?>
</table>
As per the query the expected result is the detail of the table structure and for that one can use mysql Describe table query which will provide the structure of the table.
you can try following code.I think it will help you.
<?php
error_reporting(0);
$conn = mysqli_connect('localhost', 'root', '');
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('winestore');
$result = mysql_query('SELECT * FROM wine LIMIT 0,1');
if (!$result) {
die('Query failed: ' . mysql_error());
}
?>
<table>
<th>Field</th>
<th>Type</th>
<th>Null</th>
<th>Key</th>
<th>Extra</th>
<?php
/* get column metadata */
$i = 0;
while ($i < mysql_num_fields($result)) {
$meta = mysql_fetch_field($result, $i);
if (!$meta) {
echo "No information available<br />\n";
}
$i++;
?>
<tr>
<td><?php echo $meta->name;?></td>
<td><?php echo $meta->type."(".$meta->max_length.")";?></td>
<td><?php if($meta->not_null==1){echo 'NO';}else{echo 'YES';}?></td>
<td><?php if($meta->multiple_key==1){ echo 'MUL';}if($meta->primary_key==1){echo 'PRI';}?></td>
<td><?php echo $meta->not_null;?></td>
</tr>
<?php
}
mysql_free_result($result);
?>
if you have any more doubt about this issue,please visit this link http://php.net/manual/en/function.mysql-fetch-field.php

Repopulate a table of results with results that match a search

I have the following code which echoes out pupil info from a database automatically. However when the user searches for a specific pupil I need to repopulate the same table with relevant pupils to the search request.
All help is greatly appreciated!
if(!isset ($_POST['search'])){
$pupils = mysql_query("SELECT * FROM pupil") or die("Cant find Pupils");
$count = mysql_num_rows($pupils);
if ($count == 0 ) {
$totalpupil = "There are currently no Pupils in the system.";
} else{
while($row = mysql_fetch_array($pupils)){
?>
<tr>
<td><?php echo ''.$row['pupil_id'].''; ?></td>
<td><?php echo $row['pupil_name']?></td>
<td><?php echo $row['class_id']?></td>
<td>Edit | Delete</td>
</tr>
<?php
}
}
}
Something like this ?
if(!isset ($_POST['search'])){
$pupils = mysql_query("SELECT * FROM pupil") or die("Cant find Pupils");
}
elseif(isset($_POST['search'])){
$search_param = "%".$_POST['search']."%";
$pupils = mysql_query("SELECT * FROM pupil WHERE LOWER(pupil_name) LIKE LOWER($search_param)") or die("Cant find Pupils");
}
$count = mysql_num_rows($pupils);
if($count == 0){
$totalpupil = "There are currently no Pupils in the system.";
}
else{
while($row = mysql_fetch_array($pupils)){
?>
<tr>
<td><?php echo ''.$row['pupil_id'].''; ?></td>
<td><?php echo $row['pupil_name']?></td>
<td><?php echo $row['class_id']?></td>
<td>Edit | Delete</td>
</tr>
<?php
}
I'm assuming that you are searching in the pupil_name column.

PHP MySQL display data by id from database - freedom placement

I would like to have the freedom to place a row entry from my database wherever i' prefer in the page. Right now, the php code that I use is as follows (it is clean working code):
<html><head></head>
<body>
<?php
$db = mysql_connect("xxx","xxx","xxx") or die("Database Error");
mysql_select_db("caisafety",$db);
$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `cert_rr` WHERE `id`='" . $id . "'";
$result = mysql_query($query);
echo $row['id']; while($row = mysql_fetch_array( $result )) {
echo "<br><br>";
echo $row['basic3'];
echo $row['basic2'];
echo $row['basic1'];
}
?>
</body>
</html>
I call id through the browser Eg. http://site.com/getid.php?id=10 . But I do not have the freedom to place my row entry within my html. For eg. like this:
<table><tr>
<td align="center">BASIC INFO 1: <?php echo $row['basic1']; ?></td>
<td align="center">BASIC INFO 2: <?php echo $row['basic2']; ?></td>
</tr></table>
I can place html within echo PHP tags but then I have to clean up my html and thats a lot of work. Retaining HTML formatting would be preferred. Any help or guidelines on this would be much appreciated.
<?php
$db = mysql_connect("xxx","xxx","xxx") or die("Database Error");
mysql_select_db("caisafety",$db);
$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `cert_rr` WHERE `id`='" . $id . "'";
$result = mysql_query($query);
//you need to retrieve every row and save to an array for later access
for($rows = array(); $tmp = mysql_fetch_array($result);)
{
$rows[] = $tmp;
}
//now you can use the $rows array where every you want e.g. with the code from Zhube
?>
....
<table><?php foreach($rows as $r):
<td><?php echo $r['id'] ?></td><?php endforeach ?>
</table>
By
while($row = mysql_fetch_array( $result )) {
echo "<br><br>";
echo $row['basic3'];
echo $row['basic2'];
echo $row['basic1'];
}
you save only the last row
Instead of having your HTML tags as part of the PHP variable, do something like this instead:
<table><?php foreach($row as $r):?>
<td><?php echo $r['id'] ?></td><?php endforeach ?>
</table>

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