Displaying columns in PHP [duplicate] - php

This question already has answers here:
Show values from a MySQL database table inside a HTML table on a webpage
(9 answers)
Closed 1 year ago.
Would anyone know how to get this result ? Basically I just need to display the columns as well.
Wanted Result image
Current result image
<h1>
Harry Potter Movies
</h1>
<?php
$hostname = "localhost";
$dbUser = "root";
$dbPassword = "root";
$dbName = "harry potter movies";
$port = 3306;
$conn = mysqli_connect($hostname, $dbUser, $dbPassword, $dbName, $port);
$sql = "SELECT * FROM Movies";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["movie"]. " " . $row["rating"]. " " . $row["year"]. "<br>" ;
}
} else {
echo "0 results";
}
?>

You can use a table for that.
<?php
$hostname = "localhost";
$dbUser = "root";
$dbPassword = "root";
$dbName = "harry potter movies";
$port = 3306;
$conn = mysqli_connect($hostname, $dbUser, $dbPassword, $dbName, $port);
if (mysqli_connect_errno()) exit("Failed to connect to MySQL: " . mysqli_connect_error());
?>
<h1>Harry Potter Movies</h1>
<table>
<thead>
<tr>
<th>Movie</th>
<th>Rading</th>
<th>Year</th>
</tr>
</thead>
<tbody>
<?php
$result = $conn->query("SELECT movie, rating, year FROM Movies");
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<tr>
<td><?= htmlentities($row["movie"], ENT_QUOTES) ?></td>
<td><?= htmlentities($row["rating"], ENT_QUOTES) ?></td>
<td><?= htmlentities($row["year"], ENT_QUOTES) ?></td>
</tr>
<?php
}
} else { ?>
<tr>
<td colspan="3">0 results</td>
</tr>
<?php
}
?>
</tbody>
</table>

What you want is something like this:
<table>
<tr>
<th>
Movie
</th>
<th>
Rating
</th>
<th>
Year
</th>
</tr>
<tr>
<td>
Harry Potter and the Philosopher's Stone
</td>
<td>
7.6
</td>
<td>
2001
</td>
</tr>
So your echo should ouptup some HTML tags with the content.

Related

TWO MySQL commands (SELECT to View), but only one is showing output

I have a table and each , I want to select a data from the same table in my database.
For example, first <td> is first name, then the second <td> is phone number.
I got the command, but only the first command is showing output.
This is my php codes to open and connect to the database :
<?php
include("./inc/db_connect.php");
$conn = OpenCon();
?>
This is the php codes for the table including <th> and <td> :
<div class="layer55">
<h3>
<table class="flat-table">
<tbody>
<tr>
<th>
<?php
$sql = "SELECT * FROM sharp_emp WHERE employee_id = 'AA170336'";
if ($result = $conn->query($sql)) {
if ($result->num_rows > 0) {
echo "Name";
}
}
?>
</th>
<th>
<?php
$sql = "SELECT * FROM sharp_emp WHERE employee_id = 'AA170336'";
if ($result = $conn->query($sql)) {
if ($result->num_rows > 0) {
echo "Phone Number";
}
}
?>
</th>
</tr>
<tr>
<td>
<?php
$sql = "SELECT first_name FROM sharp_emp WHERE employee_id = 'AA170336'";
while ($row = $result->fetch_array()) {
echo "" . $row['first_name'] . "";
}
?>
</td>
<td>
<?php
$sql = "SELECT phone FROM sharp_emp WHERE employee_id = 'AA170336'";
while ($row = $result->fetch_array()) {
echo "" . $row['phone'] . "";
}
?>
</td>
</tr>
</tbody>
</table>
</h3>
</div>
This is the php codes for db_connect.php :
<?php
function OpenCon()
{
$dbhost = "localhost";
$dbuser = // Hidden;
$dbpass = // Hidden;
$db = "sharp_db";
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n". $conn -> error);
return $conn;
}
function CloseCon($conn)
{
$conn -> close();
}
?>
The expected output :
|----------|----------|
|Name |Phone Number|
|----------|----------|
|John |179898765 |
The current output :
|----------|----------|
|Name |Phone Number|
|----------|----------|
|John |Null (empty) |
You are running the same query multiple times, overwriting the $result variable for no reason, having useless $sql for the later 2 fetch without using them, and fetching a single $result twice by mistake.
So there are multiple concept problem with your code. I think your current code is something equivalant to this:
<div class="layer55">
<h3>
<table class="flat-table">
<tbody>
<tr>
<?php
$sql = "SELECT * FROM sharp_emp WHERE employee_id = 'AA170336'";
if ($result = $conn->query($sql)) {
if ($result->num_rows > 0) {
?>
<th>Name</th>
<th>Phone Number</th>
<?php } else { ?>
<th></th>
<th></th>
<?php } ?>
<?php } ?>
</tr>
<tr>
<?php if ($row = $result->fetch_array()) { ?>
<td><?php echo "" . $row['first_name'] . ""; ?></td>
<td><?php echo "" . $row['phone'] . ""; ?></td>
<?php } else { ?>
<td></td>
<td></td>
<?php } ?>
</tr>
</tbody>
</table>
</h3>
</div>
But frankly, it makes no sense to me to print an empty table when there is no result. So what you need is probably something like this.
<?php
$sql = "SELECT * FROM sharp_emp WHERE employee_id = 'AA170336'";
if (
($result = $conn->query($sql))
&& ($result->num_rows > 0)
&& ($row = $result->fetch_array())
):
?>
<div class="layer55">
<h3>
<table class="flat-table">
<tbody>
<tr>
<th>Name</th>
<th>Phone Number</th>
</tr>
<tr>
<td><?php echo $row['first_name']; ?></td>
<td><?php echo $row['phone']; ?></td>
</tr>
</tbody>
</table>
</h3>
</div>
<?php endif; ?>

how to add values for each colum for each day?

I have a Table which Input all the necessary data to do statistics. i now face the issue that i dont know how to add up the values for each colum but that it only adds the values up for each day. and then Displays it in a row or another Table.
this Code is what i use to call out all of the values and insert them into a table
<html>
<head>
<title>Your Home Page</title>
</head><body>
<table border="1">
<tr>
<th>Date</th>
<th>Participant ID</th>
<th>Gender</th>
<th>Hand</th>
<th>Udnder 18</th>
<th>Adult</th>
<th>R</th>
<th>C</th>
<th>L</th>
<th>Cash</th>
<th>Card</th>
<th>Ammount</th>
</tr>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "***";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * FROM table ORDER BY Date ASC";
$result = mysqli_query($mysqli, $sql) or die(mysqli_error());
$datum = '';
while($set = mysqli_fetch_assoc($result)) {
?>
<tr>
<td>
<?php
if ($datum == $set["Date"]) {
echo ' ';
} else {
echo $set["Date"];
}
?>
</td>
<td><?php echo $set["ParticipantID"]; ?></td>
<td><?php echo $set["Gender"]; ?></td>
<td><?php echo $set["Hand"]; ?></td>
<td><?php echo $set["Under18"]; ?></td>
<td><?php echo $set["Adult"]; ?></td>
<td><?php echo $set["r"]; ?></td>
<td><?php echo $set["c"]; ?></td>
<td><?php echo $set["l"]; ?></td>
<td><?php echo $set["Cash"]; ?></td>
<td><?php echo $set["Card"]; ?></td>
<td><?php echo $set["Ammount"]; ?></td>
</tr>
<?php $datum = $set["Date"]; ?>
<?php
}
?>
</table> </body></html>
So for 04-01-2018 for the colum R the total summed up value should be 2. etc.
Thanks for the help.
Kind Regards
Mark
The first way of solving this problem is to use the second MySQL query to get total values for each date. After that create a function printDateTableRow to print each row of the table. Using the mysqli_fetch_assoc($totalMysqliResult) parameter of this function, you can pass values of a row with total values for each new date.
Another way is to use the the WITH ROLLUP group modifier (you can try to write such query by yourself).
Here is the working code for the first way:
<html>
<head>
<title>Your Home Page</title>
</head>
<body>
<table border="1">
<tr>
<th>Date</th>
<th>Participant ID</th>
<th>Gender</th>
<th>Hand</th>
<th>Udnder 18</th>
<th>Adult</th>
<th>R</th>
<th>C</th>
<th>L</th>
<th>Cash</th>
<th>Card</th>
<th>Ammount</th>
</tr>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "***";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * FROM `table` ORDER BY Date ASC";
$result = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
$totalMysqliResult = mysqli_query($mysqli, '
SELECT
Date, "" AS ParticipantID, "" AS Gender, "" AS Hand,
SUM(Under18) AS date_total_Under18,
SUM(Adult) AS date_total_Adult, SUM(r) AS date_total_r,
SUM(c) AS date_total_с, SUM(l) AS date_total_l,
SUM(Cash) AS date_total_Cash, SUM(Card) AS date_total_Card,
SUM(Amount) AS date_total_Amount
FROM `table`
GROUP BY Date
ORDER BY Date ASC') or die(mysqli_error($mysqli));
/**
* #param $row
* #param null $dateFieldHeader
*/
function printDateTableRow($row, $dateFieldHeader = null) {
?><tr><?
foreach ($row as $key => $curVal) {
?><td><?
if ($key == 'Date') {
echo $dateFieldHeader == null ? $curVal : $dateFieldHeader;
} else {
echo $curVal;
}
?></td><?
}
?></tr><?
}
$previousDate = null;
$oneDateRowsCount = 0;
while($row = mysqli_fetch_assoc($result)) {
if ($row['Date'] == $previousDate) {
$oneDateRowsCount++;
printDateTableRow($row, ' ');
} else {
if ($previousDate !== null) {
printDateTableRow(mysqli_fetch_assoc($totalMysqliResult), 'Date total');
}
printDateTableRow($row);
$oneDateRowsCount = 1;
}
$previousDate = $row['Date'];
}
// add total for the last rows with the same date
if ($oneDateRowsCount > 1) {
printDateTableRow(mysqli_fetch_assoc($totalMysqliResult), 'Date total');
}
?>
</body>
</html>
You should refactor this code in OOP style and use PDO instead of mysqli.

Script for deleting table rows not working in MySQL & PHP

I want to delete a table row from my database with MySQL and PHP. I have searched through my code and I can't figure out what I'm doing wrong. I think I am close to getting it, probably something simple that I'm not realizing.
If I hover over the delete link there is a link showing with the correct ID number of the row to delete. But if I click it, it isn't working. It just refreshes the screen.
This is my code for index.php:
<!-- Table -->
<form action="index.php" method="get" id="dispatch">
<div class="col-md-8 column">
<fieldset>
<legend>Incident Board (Incidents in red are active)</legend>
<div class="scroll-bar">
<table>
<thead>
<tr>
<th>Incident #</th>
<th>Town</th>
<th>Location</th>
<th>Incident Type</th>
<th>Time/Date</th>
<th>Admin</th>
<th>Delete Entry</th>
</tr>
</thead>
<tbody>
<?php
if( isset($_POST['town']) )
{
$town = $_POST['town'];
}
if( isset($_POST['location']) )
{
$location = $_POST['location'];
}
if( isset($_POST['incident_type']) )
{
$incident_type= $_POST['incident_type'];
}
if( isset($_POST['time_date']) )
{
$time_date= $_POST['time_date'];
}
if( isset($_POST['admin']) )
{
$admin = $_POST['admin'];
}
if( isset($_POST['id']) )
{
$id = $_POST['id'];
}
$db = mysqli_connect('localhost','root','') or die("Database error");
mysqli_select_db($db, 'cad');
$result= mysqli_query($db, "SELECT * FROM `cad` ORDER BY `time_date` DESC LIMIT 20");
while($row = mysqli_fetch_array($result))
{
$town = $row['town'];
$location = $row['location'];
$incident_type = $row['incident_type'];
$time_date = $row['time_date'];
$admin = $row['admin'];
$id = $row['id'];
echo "
<tr>
<td class=\"id-center\">
".$id."
</td>
<td >
".$town."
</td>
<td>
".$location."
</td>
<td >
".$incident_type."
</td>
<td >
".$time_date."
</td>
<td >
".$admin."
</td>
<td>
<span class=\"glyphicon glyphicon-trash\"></span>
</td>
</tr>";
}
mysqli_close($db);
?>
</tbody>
</table>
</div>
</fieldset>
</div>
</form>
<!-- End -->
This is my delete.php code:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("cad", $dbhandle);
mysql_query("DELETE FROM cad WHERE id = ".$_GET['id']."");
header('location: index.php');
?>
mysql is deprecated, instead of this use mysqli
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$con=mysqli_connect($hostname, $username, $password,"cad");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
mysqli_query($con,"DELETE FROM cad WHERE id = ".$_GET['id']."");
mysqli_close($con);
?>

Getting error "No database selected" [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
Trying to query database table. I'm getting a connection successful result when I run the connection script but can't figure out whats wrong with the query. Sorry I'm new to php
<?php
$servername = "localhost";
$database = "laravel";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = mysql_query("SELECT * FROM users WHERE id=1") or die(mysql_error());
if(mysql_num_rows($result) > 0): ?>
<table>
<tr>
<th>name</th>
<th>lastname</th>
<tr>
<?php while($row = mysql_fetch_assoc($result)): ?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['lastname']; ?></td>
</tr>
<?php endwhile; ?>
</table>
<?php endif; ?>
?>
No, don't MIX them, just use PDO all the way through. Use methods ->query() and ->fetch() accordingly.
<?php
$servername = "localhost";
$database = "laravel";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the PDO error mode to exception
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$query = $conn->query('SELECT * FROM users');
?>
<table>
<tr>
<th>name</th>
<th>lastname</th>
<tr>
<?php while($row = $query->fetch(PDO::FETCH_ASSOC)): ?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['lastname']; ?></td>
</tr>
<?php endwhile; ?>
</table>

how to store the printed value in mysql table using php

I am printing values in the address bar using the get variable,it works perfectly, then my problem is i want store the printed values into a mysql table, but it only stores null values, please help me where i am going wrong in below attached code.
<?php
session_start();
include('header.php');
?>
<form name="cart.php">
<table>
<tr>
<th> ID </th>
<th> Vehicle Description </th>
<th> Price </th>
</tr>
<tr>
<td><?php echo $_GET['id']; ?> </td>
<td><?php echo $_GET['name']; ?> </td>
<td><?php echo $_GET['price']; ?> </td>
</tr>
</table>
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$x=$_GET['id'];
$y=$_GET['name'];
$z=$_GET['price'];
$sql = "INSERT INTO products (id,description,price)
VALUES ('$x', '$y', '$y')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<form><input type="button" value="Go back" onClick="window.location.href='automobile_list.php'"></form>
</form>
<?php
include('footer.php');
?>
<?php
session_start();
include('header.php');
$x=$_GET['id'];
$y=$_GET['name'];
$z=$_GET['price'];
?>
<form name="cart.php">
<table>
<tr>
<th> ID </th>
<th> Vehicle Description </th>
<th> Price </th>
</tr>
<tr>
<td><?php echo $x; ?> </td>
<td><?php echo $y; ?> </td>
<td><?php echo $z; ?> </td>
</tr>
</table>
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO products (id,description,price)
VALUES ('$x', '$y', '$y')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<form><input type="button" value="Go back" onClick="window.location.href='automobile_list.php'"></form>
</form>
<?php
include('footer.php');
?>
use the above code you will get your code working.
the problem is in query
so update that line as:
$sql = "INSERT INTO products (id,description,price)
VALUES ('".$x."', '".$y."', '".$y."')";

Categories