PHP echoing MySQL data into HTML table - php

So I'm trying to make a HTML table that gets data from a MySQL database and outputs it to the user. I'm doing so with PHP, which I'm extremely new to, so please excuse my messy code!
The code that I'm using is: braces for storm of "your code is awful!"
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = mysql_connect("localhost", "notarealuser", 'notmypassword');
for ($i = 1; $i <= 20; $i++) {
$items = ($mysqli->query("SELECT id FROM `items` WHERE id = $i"));
echo ("<tr>");
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['id'];
}</td>");
$items = ($mysqli->query("SELECT name FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['name'];
}</td>");
$items = ($mysqli->query("SELECT descrip FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['descrip'];
}</td>");
$items = ($mysqli->query("SELECT reward FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['reward'];
}</td>");
$items = ($mysqli->query("SELECT img FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['img'];
}</td>");
echo ("</tr>");
}
?>
</tbody>
</table>
However, this code is not working - it simply causes the page to output an immediate 500 Internal Server Error. IIS logs show it as a 500:0 - generic ISE. Any ideas?

You are mixing mysql and mysqli, not closing php code block and you are not selecting a database. Plus you don't have to run a query for each field
Try this:
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = new mysqli("host","user", "password", "database");
$execItems = $con->query("SELECT id, name, descrip, reward, img FROM `items` WHERE id BETWEEN 1 AND 20 ");
while($infoItems = $execItems->fetch_array()){
echo "
<tr>
<td>".$infoItems['id']."</td>
<td>".$infoItems['name']."</td>
<td>".$infoItems['descrip']."</td>
<td>".$infoItems['reward']."</td>
<td>".$infoItems['img']."</td>
</tr>
";
}
?>
</tbody>
</table>

<table class="table table-striped table-hover">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = mysqli_connect("hostname","username",'password');
$sql= "SELECT * FROM `items` WHERE id <20 ";
$items = (mysqli_query($sql));
while ( $db_field = mysqli_fetch_assoc($items) ) {?>
<tr><td><?php echo $db_field['id'];?></td></tr>
<tr><td><?php echo $db_field['name'];?></td></tr>
<tr><td><?php echo $db_field['descrip'];?></td></tr>
<tr><td><?php echo $db_field['reward'];?></td></tr>
<tr><td><?php echo $db_field['img'];?></td></tr>
<?php}
</tbody>
</table>
Try these, not tested

Where is the question?
There's many problems with this code.
First, you are confused between PHP and HTML.
Code between is PHP. It's executed on the server, you can have loops and variables and assignments there. And if you want some HTML there you use "echo".
Code outside is HTML - it's sent to the browser as is.
Second - what you seem to be doing is querying each field separately. This is not how you work with SQL.
Here's more or less what you need to do:
//Query all rows from 1 to 20:
$items = $mysqli->query("SELECT id,name,descrip,reward,img FROM `items` WHERE id between 1 and 20");
//Go through rows
while ( $row = mysqli_fetch_assoc($items) )
{
echo "<tr><td>{$db_field['id']}</td>";
//echo the rest of the fields the same way
});

I'm going to go ahead and assume that the code isn't working and that's because there's several basic errors. I'd strongly suggest doing some hard reading around the topic of PHP, especially since you're using databases, which, if accessed with insecure code can pose major security risks.
Firstly, you've set-up your connection using the procedural mysql_connect function but then just a few lines down you've switched to object-orientation by trying to call the method mysqli::query on a non object as it was never instantiated during your connection.
http://php.net/manual/en/mysqli.construct.php
Secondly, PHP echo() doesn't require the parentheses. PHP sometimes describes it as a function but it's a language construct and the parentheses will cause problems if you try to parse multiple parameters.
http://php.net/manual/en/function.echo.php
Thirdly, you can't simply switch from HTML and PHP and vice-versa with informing the server/browser. If you wish to do this, you need to either concatenate...
echo "<td>".while($db_filed = mysqli_fetch_assoc($item)) {
print $db_field['id'];
}."</td>;
Or preferably (in my opinion it looks cleaner)
<td>
<?php
while($db_filed = mysqli_fetch_assoc($item)) {
print $db_field['id'];
}
?>
</td>
However, those examples are based on your code which is outputting each ID into the same cell which I don't think is your goal so you should be inserting the cells into the loop as well so that each ID belongs to its own cell. Furthermore, I'd recommend using echo over print (it's faster).
Something else that may not be a problem now but could evolve into one is that you've used a constant for you FOR loop. If you need to ever pull more than 20 rows from your table then you will have to manually increase this figure and if you're table has less than 20 rows you will receive an error because the loop will be trying to access table rows that don't exist.
I'm no PHP expert so some of my terminology might be incorrect but hopefully what knowledge I do have will be of use. Again, I'd strongly recommend getting a good knowledge of the language before using it.

Related

Create sub-headers for dynamically created table headers in html

I am trying to create a table with few of its column created dynamically, based on database values. Till here things are going good. Now only for the dynamic table headers, I want to create two sub-headers for each header being generated under the columns for showing two different fields. How can this be achieved. Till now what I am trying is not sufficient and needs some insights. So please take a look to my code where 'Module' is the column that is being generated dynamically based on number of modules in database and under each of 'Module' column I want to put 'Attempt' and 'Result' sub-headers. Any help/insight will be very helpful.
<table id="example" class="table table-striped table-hover table-bordered dataTableReport" cellspacing="0" width="100%">
<thead>
<tr>
<th rowspan="2">S.No.</th>
<th rowspan="2">E-mail ID</th>
<th rowspan="2">Name</th>
<?php
$query_select = "SELECT id from tbl;";
$result_select = mysql_query($query_select) or die(mysql_error());
$rows = array();
while($row = mysql_fetch_array($result_select))
$rows[] = $row;
foreach($rows as $row){
$mid = $row['id'];
echo "<th style='width:5%' colspan='2'>Module ".$mid."</th><tr><th>Attempt</th><th>Result</th>";
} ?>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT id FROM tbl;";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($result)){
?>
<th style='width:5%' colspan='2'>Module <?php echo $row['id']; ?></th>
<br><tr><th>Attempt</th><br><th>Result</th></tr>
<?php
}
?>
I have updated your code to mysqli from mysql mainly because it dated and doesn't have all the updated features. I would start learning mysqli to keep up with the competition, and to stop bugs later down the line.
$conn = you should rename this to your database variable.

Need someone to correct my mysql query for table creation

I want to create a table as that I can have in the one variable (going to send it to js later on) and then display it. But result of my echo is only table head ('Produkty', 'Ilość', 'Cena'). Can you show me where I made mistakes or correct me?
<?php
header('Access-Control-Allow-Origin: *');
include "database.php";
$dane = array();
$tabela='<table class="table table-striped">
<thead>
<tr>
<th>Produkt</th>
<th>Ilość</th>
<th>Cena</th>
</tr>
</thead>
<tbody>';
$dane=array();
$sql_main="SELECT Products.`Name`,Orders_NEW.`Amount`,((Products.`Price`)*(Orders_NEW.`Amount`)) as 'PRICE' FROM `Orders_NEW` inner join `Products` on Orders_NEW.`Product`=Products.`ID` AND `Order_ID`=669";
$dane = $db->query($sql_main);
foreach($dane as $row)
{
$tabela.="<tr><td>".$row['Name']."</td><td>".$row['Amount']."</td><td>".$row['Price']."</td></tr>";
}
$sql_second="SELECT SUM((Products.`Price`)*(Orders_NEW.`Amount`)) as 'SUMA' FROM `Orders_NEW` inner join `Products` on Orders_NEW.`Product`=Products.`ID` AND `Order_ID`=669";
$dane_second= array();
$dane_second= $db -> query($sql_second);
foreach($dane_second as $row)
{
$tabela.='<thead>
<tr>
<th>Łącznie</th>
<th></th>
<th>'.$row["SUMA"].'</th>
</tr>
</thead>
</table>';
}
echo($tabela);
?>
Edited: Changed foreach into while($row = $dane->fetch_assoc())
Now my result is:
Produkt Ilość Cena
Łącznie
seems like variables like $row['Name'] etc is the problem here
I'm not sure if you have some sort of custom class with database.php, but if $db just contains mysqli object then you need to do the following:
$dane = $db->query($sql_main);
while($row = $dane->fetch_assoc()) {
$tabela.="<tr><td>".$row['Name']."</td><td>".$row['Amount']."</td><td>".$row['Price']."</td></tr>";
}
Same goes for the second query (this assumes your SQL is correct and returning results by the way).
You have a mistake in the code:
foreach($dane_second as $row){
$tabela.='<thead>
<tr>
<th>Łącznie</th>
<th></th>
<th>'.$row["SUMA"].'</th>
</tr>
</thead>
</table>'; //Here's the problem
}
echo($tabela);
Move closing table out of foreach.

PHP/MYSQL - Fetch DB values from dropdown menu, then into table in same page

I'm building an exam management website and one of the pages I'm working on is for adding students to a course. I have a dropdown menu for the student number (which fetches values from a table), however I'd like to make it so that when the teacher selects the student number from the dropdown menu, that student's name and major appear on a table below. I have pretty much all the code for it however I can't seem to make it work. The way it is right now it shows the head of the table but it doesn't show any lines.
The errors are always in the lines where I declare $sql1 and $sql2 and vary according to how I define the condition in the statement.
Code for my dropdown menu : (works fine)
<label class="control-label" for="number">Student Number</label>
<?php
$sql = "SELECT number FROM students";
$result = $conn->query($sql);
echo "<select class=".'"form-control"'.' id="number" name="number" for="number">';
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row['number'] . '">' . $row['number'] . "</option>";
}
echo "</select>";
?>
Code for my table : (shows only head of table, which is the best I got after moving around the code and getting conversion errors and such)
The errors are always in the lines where I declare $sql1 and $sql2 and vary according to how I define the condition in the statement.
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Major</th>
</tr>
</thead>
<tbody>
<?php
$sql1 = "SELECT name FROM students WHERE number='$row'";
$result1 = $conn->query($sql1);
$value = $result1->fetch_object();
$sql2 = "SELECT major FROM students where number='$row'";
$result2 = $conn->query($sql2);
$value1 = $result2->fetch_object();
echo "<tr>
<td>".$value."</td>
<td>".$value1."</td>
</tr>";
?>
</tbody>
</table>
Thank you for all your help!!
Before I can formulate a complete answer, I must advise you that there are a few logical errors in your code.
How does your page "know" that a user selected an option from the select? You should perhaps intercept the event and respond to that using an asynchronoys mechanism, e.g. via AJAX.
Anyhow, there's no need to run two queries when you can make it with just one:
SELECT name, major FROM students WHERE number = ...
Once you have described how you mean to address issue #1 we can continue discussing the complete solution.
Well, I think there will be no $row in the the second snippet.
It seems that you didn't pass your $row from 1st snippet to 2nd snippet.
You can read this:
PHP Pass variable to next page
You can use session, cookie, get and post.
Or can just simply use "include", then the variables you defined can be used in the second page.
<?php
include "page1.php";
?>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Major</th>
</tr>
</thead>
<tbody>
<?php
$number = $row['number'];
$sql1 = "SELECT name, major FROM students WHERE number='$number'";
$result1 = $conn->query($sql1);
$value = $result1->fetch_object();
echo "<tr>
<td>".$value['name']."</td>
<td>".$value['major']."</td>
</tr>";
?>
</tbody>
</table>
According to godzillante's answer below, the mysql query should be like this:
Anyhow, there's no need to run two queries when you can make it with just one:
SELECT name, major FROM students WHERE number = ...
I notice that you use $row as the key of your second query.
But in the first snippet, the data you fetch is "$row" (it is an array, see PHP - fetch_assoc)
You should use $row['number'] instead.

editable table cell using angularJS

Is there a way to show data inside td and allow user to edit it in a way that the change will take place in the sql (MySQL in my case) table?
im creating a table from database using angularJS:
Creating The json file from the table:
$result = mysql_query("select * from `user script settings`");
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['user_id'] = $row['user id'];
$row_array['script_id'] = $row['script id'];
$row_array['cron_format'] = $row['cron format'];
$row_array['schedule_last_update'] = $row['schedule last update'];
$row_array['next_execution_time'] = $row['next execution time'];
$row_array['script_exec'] = $row['script_exec'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
showing it in the table:
<table class="table table-bordered table-hover">
<thead>
<td>user name</td>
<td>script name</td>
<td>cron format</td>
<td>schedule last update</td>
<td>next execution time</td>
<td>script exec</td>
</thead>
<tbody>
<tr ng-repeat="x in data">
<td>{{x.user_id}}</td>
<td>{{x.script_id}}</td>
<td>{{x.cron_format}}</td>
<td>{{x.schedule_last_update}}</td>
<td>{{x.next_execution_time}}</td>
<td>{{x.script_exec}}</td>
</tr>
</tbody>
</table>
<script>
function customersController($scope,$http) {
$http.get("getData.php")//test3.php return a json file of users table
.success(function(response) {$scope.data = response;});
}
</script>
I want to allow user to change the cron format value and to update the table ...is there "angularish" way to due that?? if not i'll appreciate guidance for a php solution, thx!

Why data from my database is not displaying?

Hey guys I'm pretty new at PHP, I'm not too sure what Ive done wrong and I've been working at this for a few hours and cant seem to see whats wrong with it (there's no error which makes things more fun) what it actually does, it runs fine but it does not display the data from my database and only shows up with the column headers and that's it.
I would appreciate any advice at this point. What my code does is that it grabs some information 'staffID' from a form and uses that to display data that associates with it (like a search function) I'm using a 'join' function just for practice with the database I'm using.
As I said I'm completely new to this so this so I could be completely wrong with my code
<?php $staffidstr = $_GET["staffID"];
$conn = mysql_connect("xxxxxxx", "xxxxxx", "xxxxxxx");
mysql_select_db("xxxxxxxx", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "SELECT orderID, orderDate, shippingDate, staffName
FROM purchase, staff
WHERE purchase.staffID = staff.staffID
AND staff.staffID = '%$staffidstr%'
ORDER BY staff.staffName";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
?>
<?php echo "$staffidstr"; ?>
<table border="1" summary="Purchase Details">
<tr>
<th>Order ID</th>
<th>Order Date</th>
<th>Shipping Date </th>
<th>Staff Name</th>
</tr>
<?php
while ($row = mysql_fetch_array($rs)) { ?>
<tr>
<td><?php echo $row["orderID"]?></td>
<td><?php echo $row["orderDate"]?></td>
<td><?php echo $row["shippingDate"]?></td>
<td><?php echo $row["staffName"]?></td>
</tr>
<?php }
mysql_close($conn); ?>
I'm pretty sure it's following part of the WHERE clause
staff.staffID = '%$staffidstr%'
That should be most likely
staff.staffID = '$staffidstr'
The % character has no special meaning using the = operator, so your query will return not a single row.

Categories