I have a problem in inserting table from my database to div.
html code:
<div class="content">
<?php
$query = "SELECT name, surname FROM players";
$response = #mysqli_query($dbc, $query);
if($response) {
echo' <table align="left"
cellspacing="5" cellpadding="8" >
<tr><td align="left"><b>First Name</b></td>
<td align="left"><b>Last Name</b></td></tr>';
while($row = mysqli_fetch_array($response)) {
echo '<tr><td align="left">' .
$row['imie'] . '</td><td align="left">' .
$row['nazwisko'] . '</td><td align="left">';
echo '</tr>';
}
echo '</table>';
} else {
echo "Couldn't issue database query";
echo mysqli_error($dbc);
}
mysqli_close($dbc);
?>
</div>
css code:
.content {
width: 1000px;
margin-left: auto;
margin-right: auto;
background-color: #ffffff;
color: #000000;
border-bottom: 14px solid #333333;}
Is there a way to insert this table to this div? Because when I'm loading this, the table is under my div'content'. The table should be in blank field 'a'.
Screenshot
Correctly indenting your code would have allowed you o spot the error relatively easily - there is an open td element. Either remove the last td from the echo statement in the loop or add additional td pair to first row in table so that they balance ( unless you use colspan attributes )
<style>
.content table tr td{ align:left;padding:5px;color:black;background:white; }
</style>
<div class='content'>
<?php
$sql = 'select `name`, `surname` from `players`';
$response = mysqli_query( $dbc, $sql );
if( $response ) {
echo "
<table align='left' cellspacing='5' cellpadding='8' >
<tr>
<td><b>First Name</b></td>
<td><b>Last Name</b></td>
</tr>";
while( $row = mysqli_fetch_array( $response ) ) {
echo "
<tr>
<td>{$row['imie']}</td>
<td>{$row['nazwisko']}</td>
</tr>";
}
echo "
</table>";
} else {
printf( 'Couldn\'t issue database query: %s', mysqli_error( $dbc ) );
}
mysqli_close( $dbc );
?>
</div>
There is an open <td> tag in your code you should close it before closing the <tr>
Related
I am just starting with SQL, PHP, and HTML and I plan to take some courses, but I need a basic working model before I can move forward. I have an SQL database that has a few fields. I can display this data without a problem. I would like to filter this data with a drop-down box. Currently, I have the drop-down box populated with a Select Distinct command. I can not seem to figure out the syntax to modify my SQL Select command to only show records that match my pull-down box. Ha, I will be the first to admit that I have no clue what I am doing, but my problem is that I might not know the term I need to look up how to solve my problem. Google and I are tight, but we just can't put our finger on this one. Can you point me in the right direction? Thanks!
<!DOCTYPE html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even){
background-color: #dddddd;
}
</style>
<body>
<form action='new1.php' method="get" name='fPIC'>
<select class="form-dropdown validate[required]" style="width:150px" id="input_PIC" name="sPIC">
<?php
$link = mysqli_connect("localhost", "root", "**********", "pd4poc");
mysqli_select_db($link,'pd4poc');
$query = "SELECT DISTINCT PIC FROM dummydata order by PIC asc";
$result = mysqli_query($link,$query);
$menu=" ";
while($row = mysqli_fetch_array($result))
{
$menu .= "<option value=".$row['PIC'].">" .$row['PIC']. "</option>";
}
echo $menu;
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['PIC'] . "<td><td>" , $row['Reason'] . "<td><td>", $row['Status'] . "</td></tr>";
}
echo "</table>";
mysqli_close($link);
?>
</select>
<input type="submit" name="nPIC" value="Filter">
</form>
<?php
$link = mysqli_connect("localhost", "root", "**********", "pd4poc");
mysqli_select_db($link,'pd4poc');
$query = "SELECT * FROM dummydata"; //need to be picked from the pull down
$result = mysqli_query($link,$query);
echo "<table>";
echo "<tr>
<th>PIC</th>
<th>Reason</th>
<th>PlanApply</th>
<th>HOT</th>
<th>Status</th>
<th>Comments</th>
</tr>\n";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" .
$row['PIC'] . "<td>",
$row['Reason'] . "<td>",
$row['PlanApply'] . "<td>",
$row['HOT'] . "<td>",
$row['Status'] . "<td>",
$row['Comments'] . "</td>\n</tr>";
}
echo "</table>";
mysqli_close($link);
?>
</body>
</head>
I need my table to include submissions into three columns then a new row start with three more columns, etc. So submission 1, first column, submission 2, second column, submission 3, 3 column. Then a new row and the process starts again. (HTML Example Code below)
Every time I try with my php code my page comes up blank so I am missing something somewhere.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, website, url, email, date, description FROM basic";
$result = $conn->query($sql);
if ($result->num_rows>0){
<tr>
while ($row=$result->fetch_assoc()) {
echo "<table><tr><th><b>Company:</b> " . $row["name"]. "</th></tr><tr><td>
<b>URL:</b> <a href='".$row["url"]."'>".$row["url"]."</a></td></tr><tr><td>
<b>Email:</b> " . $row["email"]. "</td></tr><tr><td><b>Launch Date:</b> " .
$row["date"]. "</td></tr><tr><td><b>Announcement:</b> " .
$row["description"]. "</td>
</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Example: This is what I am trying to get it to look like.
<style>
table, td, th {
border: 10px solid #ffffff;
text-align: left;
}
table {
border-collapse: initial;
width: 100%;
}
td {
padding: 15px;
width: 25%;
line-height: 2;
}
th {
background-color: grey;
color: white;
padding: 5px;
width: 25%;
}
</style>
<body>
<table class="ex1">
<tr>
<th>Company</th>
<th>Company</th>
<th>Company</th>
</tr>
<tr>
<td>
<b>URL:</b><br>
<b>Location:</b><br>
<b>Inductry:</b><br>
<b>Start Date:</b><br>
<b>Announcement:</b><br>
<br>
</td>
<td>
<b>URL:</b><br>
<b>Location:</b><br>
<b>Inductry:</b><br>
<b>Start Date:</b><br>
<b>Announcement:</b><br>
<br>
</td>
<td>
<b>URL:</b><br>
<b>Location:</b><br>
<b>Inductry:</b><br>
<b>Start Date:</b><br>
<b>Announcement:</b><br>
<br>
</td>
</table>
Your PHP code is not generating HTML in proper format. Please try below:
// Query executed here and resultset returned
if ($result->num_rows>0){
echo "<table>";
while ($row=$result->fetch_assoc()) {
echo "<tr><th><b>Company:</b> " . $row["name"]. "</th></tr>
<tr><td><b>URL:</b> <a href='".$row["url"]."'>".$row["url"]."</a></td></tr>
<tr><td><b>Email:</b> " . $row["email"]. "</td></tr>
<tr><td><b>Launch Date:</b> " . $row["date"]. "</td></tr>
<tr><td><b>Announcement:</b> " . $row["description"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
Hi I have a table generated from php, it is editable, I want to save edited values to database. I have no Idea how can I do this as there are many rows(dynamic) on a page.
Here is a screen-shot:-
Please suggest
Edit:-
My code is
echo "<table border='1'>
<tr>
<th>Sl Number</th>
<th>Product Id</th>
<th>Product Name</th>
<th>Product Catagory</th>
<th>Retal Price</th>
<th>Max Price</th>
<th>Min Price</th>
<th>Initial Stock</th>
<th>Quantity Sold</th>
<th>Current Stock</th>
<th>Last Order</th>
<th>Edit/Update</th>
</tr>";
while($row = $result->fetch_assoc())
{
echo "<tr contenteditable>";
echo "<td>" . $row["Row Number"]. "</td>";
echo "<td>" . $row["Product Id"]. "</td>";
echo "<td>" . $row["Product Name"]. "</td>";
echo "<td>" . $row["Product Catagory"]. "</td>";
echo "<td>" . $row["Retal Price"]. "</td>";
echo "<td>" . $row["Max Price"]. "</td>";
echo "<td>" . $row["Min Price"]."</td>";
echo "<td>" . $row["Initial Stock"]."</td>";
echo "<td>" . $row["Quantity Sold"]. "</td>";
echo "<td>" . $row["Current Stock"]."</td>";
echo "<td>" . $row["Last Order"]."</td>";
echo "<td contenteditable = 'false'><button href = '#'>Update</a></td>";
echo "</tr>";
}
Let me give you with the best way
First your database tables have spaces: correct that e.g.
from $row["Initial Stock"] to $row["Initial_Stock"]
Then i will propose you use ajax instead of wasting time clicking buttons
The HTML Page
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script>
$(function(){
$("#loading").hide();
//acknowledgement message
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
var field_userid = $(this).attr("id") ;
var value = $(this).text() ;
$.post('update.php' , field_userid + "=" + value, function(data){
if(data != '')
{
message_status.show();
message_status.text(data);
//hide the message
setTimeout(function(){message_status.hide()},1000);
}
});
});
});
</script>
<style>
table.zebra-style {
font-family:"Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
text-align:left;
border:1px solid #ccc;
margin-bottom:25px;
width:100%
}
table.zebra-style th {
color: #444;
font-size: 13px;
font-weight: normal;
padding: 5px 4px;
}
table.zebra-style td {
color: #777;
padding: 4px;
font-size:13px;
}
table.zebra-style tr.odd {
background:#f2f2f2;
}
#status { padding:10px; position:fixed; top:10px; border-radius:5px; z-index:10000000; background:#88C4FF; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
#loading { padding:10px; position:absolute; top:10px; border-radius:5px; z-index:10000000; background:#F99; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
</style>
<div id="status"> </div>
<div id="loading"></div>
<table id="tableID" border="0" class="sortable table zebra-style">
<thead>
<tr>
<th>Sl Number</th>
<th>Product Id</th>
<th>Product Name</th>
<th>Product Catagory</th>
<th>Retal Price</th>
<th>Max Price</th>
<th>Min Price</th>
<th>Initial Stock</th>
<th>Quantity Sold</th>
<th>Current Stock</th>
<th>Last Order</th>
<th>Edit/Update</th>
</tr>
</thead>
<tbody class="list">
<?php do { ?>
<tr>
<td contenteditable="true" id="Row_Number:<?php echo $row["Row_Number"]; ?>"><?php echo $row["Row_Number"]; ?></td>
<td contenteditable="true" id="Product_Id:<?php echo $row["Product_Id"]; ?>"><?php echo $row["Product_Id"]; ?></td>
<td contenteditable="true" id="Product_Name:<?php echo $row["Product_Name"]; ?>"><?php echo $row["Product_Name"]; ?></td>
<td contenteditable="true" id="Product_Catagory:<?php echo $row["Product Id"]; ?>"><?php echo $row["Product_Catagory"]; ?></td>
<td contenteditable="true" id="Retal_Price:<?php echo $row["Retal_Price"]; ?>"><?php echo $row["Retal_Price"]; ?></td>
<td contenteditable="true" id="Max_Price:<?php echo $row["Max_Price"]; ?>"><?php echo $row["Max_Price"]; ?></td>
<td contenteditable="true" id="Min_Price:<?php echo $row["Min_Price"]; ?>"><?php echo $row["Min_Price"]; ?></td>
<td contenteditable="true" id="Initial_Stock:<?php echo $row["Initial_Stock"]; ?>"><?php echo $row["Initial_Stock"]; ?></td>
<td contenteditable="true" id="Quantity_Sold:<?php echo $row["Quantity_Sold"]; ?>"><?php echo $row["Quantity_Sold"]; ?></td>
<td contenteditable="true" id="Last_Order:<?php echo $row["Last_Order"]; ?>"><?php echo $row["Last_Order"]; ?></td>
<td contenteditable="true" id="Last_Order:<?php echo $row["Last_Order"]; ?>"><?php echo $row["Last_Order"]; ?></td>
<td contenteditable = 'false'></td>";
</tr>
<?php } while($row = $result->fetch_assoc()) ?>
</tbody>
</table>
And the update php page
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8',
'username',
'password',
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
?>
<?php
if(!empty($_POST))
{
//database settings
foreach($_POST as $field_name => $val)
{
//clean post values
$field_id = strip_tags(trim($field_name));
//from the fieldname:user_id we need to get user_id
$split_data = explode(':', $field_id);
$product_id = $split_data[1];
$field_name = $split_data[0];
if(!empty($product_id) && !empty($field_name) && !empty($val))
{
$affected_rows = $db->exec("UPDATE yourtable SET $field_name = '$val' WHERE product_ID = $product_id");
echo $affected_rows;
echo "Updated";
} else {
echo "Invalid Requests";
}
}
}
else {
echo "Invalid Requests";
}
?>
To save the whole table, you could leave the row-level update buttons out, and have a single save button:
<button id="save">Save</button>
<div id="msg"></div>
The msg area is to display feed-back from the server when the save-operation is performed.
Then you would add this JavaScript to handle the click of the save button:
$('#save').click(function() {
var data = [];
$('td').each(function() {
var row = this.parentElement.rowIndex - 1; // excluding heading
while (row >= data.length) {
data.push([]);
}
data[row].push($(this).text());
});
$.post('savetable.php', {table: data}, function (msg) {
$('#msg').text(msg);
});
});
This will transform the HTML table contents, without header row, to a JavaScript matrix, which then is sent to savetable.php for processing.
In PHP you would then use $_POST['table'] to access that array. When you implement this, first debug, and do a var_dump($_POST['table']) to make sure the data was transferred correctly, and it has the array structure you expect.
Then loop over that array to insert the rows into your database. You can use mysqli or PDO for this.
The PHP script savetable.php should only echo one message: a confirmation ("the table was saved successfully") or an error message ("a problem occurred. Your data was not saved.").
It should not reproduce the HTML of the table, since that is already displayed in the browser. Whatever PHP prints will be used by the JavaScript code to be displayed below the save button.
Here is how savetable.php could look like. But please debug carefully, I did not test this code. And before it works, you first need to set up your database model of course:
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4',
'username', 'password');
// Configure that all database errors result in an exception:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
// Make a transaction: this allows to rollback any of the changes
// if anything goes wrong before the end of it.
$db->beginTransaction();
// First delete all rows.
$db->exec("DELETE FROM mytable");
// Prepare a statement that will be executed for each row.
// Needs to be extended for all columns:
$stmt = $db->prepare("INSERT INTO mytable (sl_num, product_id, product_name)
VALUES (?, ?, ?)");
foreach ($_POST('table'] as $row) {
$stmt->execute($row); // the columns are passed to the prepared statement.
}
// All went well: commit the changes.
$db->commit();
echo "Table saved successfully";
} catch(PDOException $e) {
// Something went wrong: roll back any changes made
$db->rollback();
echo "An error occurred: " . $e->getMessage();
}
What you can do is ajax call to a php with the id of the row you want to save and the new data. Then use PDO to connect to the database and update the information. After that is done, use javascript to edit the table itself.
So what you need to do is look up how to use ajax calls and use PDO. I suggest when you echo the table itself
<button href = '#' onclick="updateRow('. $row['Row Number'] .')">Update</a></td> where Row Number is the ID in the database and updateRow() is the javascript function you will create to get the new information and send it via ajax. Don't use mysql_*, because it is not supported in php 7 and it will die soon. Look up PDO instead.
I am trying to get information from mysql including a blob image which i shall echo with php and will have an onclick event within the php, redirecting it to another page. The onlick event will contain a mysql result which it will carry with it as seen in the code below.
My main issue is with the syntax of the code or if there is another way to do it all together. please keep in mind the output when the script is run is similiar to that of google images, bing images etc. Thank you.
<?php
$con=mysqli_connect("localhost","root","*******","media");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM movies ORDER BY `movies`.`title` ASC");
echo "<table border='3' style='margin: auto; text-align: left;background: white; padding: 3em;'>
<tr>
<th><b>Movie Title</b></th>
<th><b>Language</b></th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td style='padding-right: 2em;'><img src="data:image/jpeg;base64,' . base64_encode( $row['image'] ) . '" width="160px" height="200px";" onclick="window.location='lookup.php?pattern=" . $row['title'] . "';>";
</td>
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Untested but here is one way you could clean up your code move style and javascript (and use some jquery) into the head:
<?php
$con=mysqli_connect("localhost","root","*******","media") or die("Failed to connect to MySQL: " . mysqli_connect_error());
$result = mysqli_query($con,"SELECT * FROM movies ORDER BY `movies`.`title` ASC");
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('img').each(function() {
var img = $(this);
img.click(function() {
window.location="lookup.php?pattern=" + img.attr('title');
});
});
});
</script>
<style>
table {
margin: auto;
text-align: left;
background: white;
padding: 3em;
border: 2px solid #000000;
}
table tr td {
padding-right: 2em;
}
table tr td img {
width: 160px;
height: 200px;
}
</style>
</head>
<body>
<table>
<tr>
<th>Movie Title</th>
<th>Language</th>
</tr>
<?php
while($row = mysqli_fetch_array($result)) {
echo "
<tr>
<td>
<img src=\"data:image/jpeg;base64," . base64_encode( $row['image'] ) . "\" title=\"" . $row['title'] . "\">
</td>
</tr>
";
}
?>
</table>
</body>
</html>
<?php mysqli_close($con); ?>
Or if you don't want to use javascript, you could always wrap the image around the anchor tag instead:
<td>
<a href='lookup.php?pattern={$row['title']}'>
<img src=\"data:image/jpeg;base64," . base64_encode( $row['image'] ) . "\">
</a>
</td>
You could further separate PHP and HTML code:
<?php
$con=mysqli_connect("localhost","root","*******","media");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$result = mysqli_query($con,"SELECT * FROM movies ORDER BY `movies`.`title` ASC");
?>
<table border='3' style='margin: auto; text-align: left;background: white; padding: 3em;'>
<tr>
<th><b>Movie Title</b></th>
<th><b>Language</b></th>
</tr>
<?php
while($row = mysqli_fetch_array($result)) {
$img = 'data:image/jpeg;base64,'
. base64_encode( $row['image'] );
?>
<tr>
<td style='padding-right: 2em;'>
<img src="<?php echo $img; ?>"
style="width: 160px; height: 200px;"
onclick="window.location='lookup.php?pattern=<?php echo $row['title']?>;'"
/>
</td>
</tr>
<?php } ?>
</table>
<?php
mysqli_close($con);
?>
You could also use some sort of templating engine to do this, but the results would be pretty much the same - I don't see much point in writing, say,
<strong>{{ title }}</strong>
instead of
<strong><?php echo $title; ?></strong>
Overview
I have some data stored in MySql database related to Products. I am trying to retrieve this data and display it on a page using HTML table.
The PHP and MySql has gone well and all the data is retrieved but it is displayed in a very messy manner.
Here is what I have as a layout:
What I am aiming to achieve is to further divide the results table add more columns rows to make the data more readable
Something like this;
The code: PHP, MySQL & HTML:
<?php
session_start();
include('connect_mysql.php');
$product_name = 'product_name';
$product_qua = 'product_qua';
$product_price = 'product_price';
$product_image = 'product_image';
$product_des = 'product_des';
$sql = mysql_query("SELECT * FROM products");
echo "<table id='display'>";
while($rows = mysql_fetch_array($sql))
{
echo"<br>";
echo"<tr><td>";
echo"$rows[$product_name]<br></td>";
echo"<td><img src=$rows[$product_image] height='200px' width='200px'><br></td>";
echo"<td>Avalible: $rows[$product_qua]<br></td>";
echo"<td>Price: $rows[$product_price]<br></td>";
echo"<td>Description: $rows[$product_des]<br></td>";
echo"</tr>";
}
echo "</table>";
?>
CSS responsible for this part:
#display{
float:left;
border: 5px solid black;
margin-left:100px;
}
just add some padding or a border to the table cells:
table#display td{
border: 1px solid black;
padding:0 8px;
}
Edit: What you could do as well:
<table id='display'>
<?php while($rows = mysql_fetch_array($sql)): ?>
<!-- <br> <- why a break? it's not in the correct spot anyway -->
<tr><td>
<?php echo $rows[$product_name]; ?><br>
</td>
<td> - </td>
<td><img src="<?php echo $rows[$product_image]; ?>" height='200px' width='200px'><br></td>
<td> - </td>
<td>Avalible: <?php echo $rows[$product_qua]; ?><br></td>
<td> - </td>
<td>Price: <?php echo $rows[$product_price]; ?><br></td>
<td> - </td>
<td>Description: <?php echo $rows[$product_des]; ?><br></td>
</tr>
<?php endwhile; ?>
</table>
Tip: I prefer to use the while/endwhile; approach rather than using brackets when displaying data to the user.
First of all don't echo so much HTML using PHP, instead do it like this
<?php
session_start();
include('connect_mysql.php');
$product_name = 'product_name';
$product_qua = 'product_qua';
$product_price = 'product_price';
$product_image = 'product_image';
$product_des = 'product_des';
$sql = mysql_query("SELECT * FROM products"); ?>
<table id='display'>
<?php
while($rows = mysql_fetch_array($sql)) {
?>
<tr><td><?php echo $rows[$product_name]; ?></td>
<!-- And so on-->
<?php
}
?>
</table>
Secondly by seeing your inmage, it seems like you need a border for your table so use
table, td {
border: 1px solid #000000;
}
add the following css to apply border on your table cells:
#display td{ border: 2px solid red; }
and optionally add to your #display { :
border-collapse: collapse;