I am trying to get this PHP table cell to write a color depending on a condition but I am missing something that is causing a Syntax error?
Here is the code:
$table = '<table>
<tr>
<th> Qty </th>
<th> Length </th>
<th> Description </th>
<th> Color </th>
</tr>
<tr>
<td></td>
<td></td>
<td>'.$gauge. ' ' .$panel. '</td>'
if ($sscolor == "None")
{
'<td>' .$color. '</td>';
}
else
{
'<td>' .$sscolor. '</td>';
}
'</td>
</tr> ';
Yes. You can't put an if/else conditional inside a string. You can use a ternary though.
$str = 'text'.($sscolor == 'None' ? $color : $sscolor).' more text'; // etc
Otherwise you'll need to end the string before the if, then concatenate more onto it using .=
You can't place a IF condition in a variable after you write some string to it
I suggest this is how you do it
if ($sscolor == "None")
{
$extra_string = '<td>' .$color. '</td>';
}
else
{
$extra_string = '<td>' .$sscolor. '</td>';
}
$table = '<table>
<tr>
<th> Qty </th>
<th> Length </th>
<th> Description </th>
<th> Color </th>
</tr>
<tr>
<td></td>
<td></td>
<td>'.$gauge. ' ' .$panel. '</td>' . $extra_string . '
</tr> ';
The problem is that you need to close the string concatenation with a semicolon, ;, before the if statement. If you do not then you will get a syntax error:
<td>'.$gauge. ' ' .$panel. '</td>' <-- Semicolon here
if ($sscolor == "None") <-- Syntax error, unexpected if token
A good way to avoid stuff like this is to use a heredoc string:
// Figure out the color before going into the string
if ($sscolor === 'None') {
$color = $sscolor;
}
// heredoc string, with string interpolation
$table = <<< HTML
<table>
<tr>
<th>Qty</th>
<th>Length</th>
<th>Description</th>
<th>Color</th>
</tr>
<tr>
<td>-</td>
<td>-</td>
<td>{$gauge} {$panel}</td>
<td>{$color}</td>
</tr>
</table>
HTML;
Learn more about strings.
Also, even the best PHP programmers have to deal with errors. It is a part of learning PHP. So, you should get in the habit of googling error messages; they are easy to find, and you will be able to help yourself and learn at the same time.
You need to concatenate the lines withint the if statement.
<td>'.$gauge. ' ' .$panel. '</td>';
if ($sscolor == "None") {
$table .= '<td>' .$color. '</td>';
} else {
$table .= '<td>' .$sscolor. '</td>';
}
$table .= '</td>';
Related
I am attempting to display mySQL data in a HTML table through php. The first row is displaying correctly, however the other row sets are not being organised and displayed in my table, rather just echoing out at the bottom of the container with no structure.
I think that since the data is being displayed, albeit not in the table, that my query is correct, im just unsure on how to proceed.
Is this an issue with my table structure?
I tried adding a second:
echo '<td>' . $data['studentNumber'] . '</td><td>' . $data['handle'] . '</td><td>' . $data['email'] . '</td>';
underneath my first echo, but it just duplicated everything.
Here is the entire code in question: Screenshot Here
<div class="container-fluid">
<div class="row">
<div class="col-md details">
<p class="details_title"></p>
<?php
$getAllStudentsTable = "SELECT * FROM users WHERE accessLevel = 3";
$result = (mysqli_query($conn, $getAllStudentsTable));
echo '<table class="table">
<thead class="thead-dark">';
echo' <tr>
<th scope="col">Student Number</th>
<th scope="col">Handle</th>
<th scope="col">Email Address</th>
</tr>
</thead>'; //table headers
while ($data = mysqli_fetch_array($result)) {
echo' <tbody> <tr>';
echo '<td>' . $data['studentNumber'] . '</td><td>' . $data['handle'] . '</td><td>' . $data['email'] . '</td>';
echo'</tr> </tbody> </table>';
}
?>
Can anyone point me in the right direction on this?
(I am relatively new to PHP, SO and this is the first attempt ever at trying to display database data into an HTML table.)
I have attached a link for a screenshot of the issue (Not yet allowed to post pictures lol).
Thanks!
You're echoing most of the table structure in your loop, where you should just be echoding the rows. As a necessary debugging step, take a look at the View Source in your browser and see what the table structure is. You'll find multiple <tbody> elements and multiple closing </table> tags, confusing the browser.
Basically, remove the various <tbody> and <table> tags from your loop and just echo them around the loop. Something like this:
echo '<tbody>';
while ($data = mysqli_fetch_array($result)) {
echo '<tr>';
echo '<td>' . $data['studentNumber'] . '</td><td>' . $data['handle'] . '</td><td>' . $data['email'] . '</td>';
echo '</tr>';
}
echo '</tbody></table>';
All you want to repeat in the loop is each <tr> element and its children.
Hello i have these code.
<div class="col-md-6"> <br><br>
<table class="table">
<thead>
<th> Subject </th>
<th> Schedule </th>
<th> Day </th>
<th> Slots </th>
<th> Sections </th>
<th> Action </th>
</thead>
<tbody>
<?php
foreach($Subjects as $row)
{
$course = $this->session->userdata('course');
if($course == 'BSITWMA' || $course == 'BSCSSE' || $course == 'BSITDA' || $course == 'BSITGDD')
{
if($row->ite == '1' ) {
echo '<tr>';
echo '<td id="subj_code" name="subj_code">' .$row->subject_code. '</td>';
echo '<td id="sched_time" name="sched_time">' .$row->schedule_timestart. ' - ' .$row->schedule_timeend.' </td>';
echo '<td id="day" name="day">' .$row->schedule_day. '</td>';
echo '<td id="slot" name="slot">' .$row->slots. '</td>';
echo '<td id="sect_code" name="sect_code">' .$row->section_code. '</td>';
echo '<td > <button id = "btn-add" class="btn" > Reserve </button > </td>';
echo '</tr>';
}
}
else {
if($row->coe == '1' ) {
echo '<tr>';
echo '<td id="subj_code" name="subj_code">' .$row->subject_code. '</td>';
echo '<td id="sched_time" name="sched_time">' .$row->schedule_timestart. ' - ' .$row->schedule_timeend.' </td>';
echo '<td id="day" name="day">' .$row->schedule_day. '</td>';
echo '<td id="slot" name="slot">' .$row->slots. '</td>';
echo '<td id="sect_code" name="sect_code">' .$row->section_code. '</td>';
echo '<td > <button id = "btn-add" class="btn" > Reserve </button > </td>';
echo '</tr>';
}
}
}
?>
</tbody>
</table>
</div>
I have updated my code and this is what it looks like now.
what i want is to when i press the button. i will retrieve all the values and use it to insert into the database.
i dont have any code yet for the retrieving of value part.
i have the jquery part like this, and i still dont have any idea how to get the values in each TD.
$('button').on('click',function() {
var rowCount = $('#mhTable >tbody >tr').length;
});
You could get the ancestor <td> element of the button and get the values by accessing the text element of the sibling <td> elements using the jQuery .each() function.
The code should look something like this:
$(document).ready(function() {
$("#btn-add").on('click', function() {
var values = [];
$(this).parent('td').siblings().each(function() {
values.push($(this).text());
});
console.log(values);
});
});
Here I pass the values to an array for simplicity but you can pass these values using ajax or whatever other method you use to send values to the database.
Here is a fiddle with this example in practise
Why not do something like this for each of your variables within your foreach?
$subject_code = $row->subject_code;
and then you can use that variable for whatever you choose (such as your query)
Here is the table below that I'm trying to delete rows out of:
<form method="POST" >
<table class="sortable">
<thead>
<tr>
<th id="makehead">Make </th>
<th id="modelhead">Model </th>
<th id="idhead">Delete </th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
foreach ($carArray as $k => $carInfo) {
$i++;
echo '<tr>';
if ($i % 2) {
echo '<td class="make">' . $carInfo['make'] . '</td>
<td class="model">' . $carInfo['model'] . '</td>
<td class="id"><input type="checkbox" name="id" value="' . $carInfo['id'] . '">' . $carInfo['id'] . '</td>';
} else {
echo '<td class="makelight">' . $carInfo['make'] . '</td>
<td class="modellight">' . $carInfo['model'] . '</td>
<td class="idlight"><input type="checkbox" name="id" value="' . $carInfo['id'] . '">' . $carInfo['id'] . '</td>';
}
}
?>
</tr>
</table>
</tbody>
<td>
<input Onclick="return ConfirmDelete();" name="delete" type="submit" id="delete" value="Delete"></input>
</td>
</table></form>
As you can see i'm using checkboxes to tick each row then the delete button will have a confirm message then should delete but it doesn't here is my if statement:
if ($_REQUEST['delete']) {
$dbid = $_REQUEST['id'];
$db->setdbid($dbid);
So when this wasn't working I had a look on here and on other questions people said I need a setter function so i did this: EDIT: this is my class file.
public function setdbid($dbid){
$this->dbid=$dbid;
}
for this main function to delete things:
public function delete($dbid) {
try {
$sql = "DELETE FROM cars WHERE id = '$dbid'";
$this->db->exec($sql);
echo "Car has been deleted.";
} catch (PDOException $e) {
echo $e->getMessage();
}
}
So that's all the relevant code I think, please help me if you can.
You just have to replace some piece of code in PHP :
if ($_REQUEST['delete']) {
$dbid = $_REQUEST['id'];
$db->delete($dbid); //Assuming delete is well a $db method, else replace it by the correct delete call
}
As you are using checkboxes with the same name, you have to change it so it's an array (and this way you'll be able to delete multiple rows at once) :
<td class="id"><input type="checkbox" name="ids[]" value="' . $carInfo['id'] . '">' . $carInfo['id'] . '</td>';
Then in your php code, treat this data as such :
if ($_REQUEST['delete']) {
foreach($_REQUEST['ids'] as $id){
$xxx->delete(intval($id)); //convert to integer to avoid sql injection.
}
}
Note that you don't need to set $db->setdbid since you pass that id as a parameter of your delete method.
I am trying to populate dropdown list values from mysql and show it inside the td of html table,i tried with below code but it not populating values from mysql can any help me how to do that.
<table id="CPH_GridView1" style="width:1452px">
<thead>
<tr>
<th style=" width:102px">Clien ID </th>
<th style=" width:100px">Country</th>
<th style=" width:248px">Network Name </th>
<th style="text-align:center; width:102px" >cppn </th>
</tr>
</thead>
<tbody>
<?php
$sql = mysql_query("SELECT * FROM clientpricenotifications");
while($rows=mysql_fetch_array($sql))
{
if($alt == 1)
{
echo '<tr class="alt">';
$alt = 0;
}
else
{
echo '<tr>';
$alt = 1;
}
echo '<td id="CPH_GridView1_clientid" style="width:140px" class="edit clientid '.$rows["id"].'">'.$rows["clientid"].'</td>
<td id="CPH_GridView1_country" style="width:160px" class="edit country '.$rows['id'].'">'.$rows["country"].'</td>
<td id="CPH_GridView1_networkname" style="width:156px" class="edit networkname '.$rows["id"].'">'.$rows["networkname"].'</td>';
?>
<td>
<select name=' . customer_name . '>
<?php
$query = 'SELECT cppn FROM clientpricenotifications';
$result = mysql_query($query, $db) or die(mysql_error($db));
while ($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['id'] . '"> ' . $row['cppn'] . '</option>';
}
?>
</select>
</td>
</tr>'
}
?>
There seems to be a problem with this line:
<td> <select name='customer_name'>
Shouldn't it actually say either this:
<td> <select name="customer_name">
Or:
<td> <select name=' . customer_name . '>
And, that line is part of an echo statement that contains a string in single-quotes, but I can't see where the echo statement's closing single-quote is.
As a result, I think a large bulk of your output is being ignored by the browser because the tag is not being closed properly as some of the output is getting mangled. Check your output with View Source!
If your above code is complete, then I would guess that you're missing the connection to the MySQL server. See: http://www.php.net/manual/en/function.mysql-connect.php
For a related question with code sample, check the answer at: Create table with PHP and populate from MySQL
Not asked, but your table has non matching column widths defined in the styles: Clien(t) ID header 102px, while data cells are 140px.
Another place to look for is following line:
<td style="width:65px" class=" '.$rows["id"].'">
I would expect it should be the following:
<td style="width:65px" class="<?php echo $rows["id"] ?>">
As Vexen Crabtree mentioned, if you also check/post the html code of the HTML output, it would make it easier to diagnose the problem.
I have code which retrieves information about players from a MySQL database. I want to apply a special case to the HTML output if their ranking changes. I want it to look like this: http://i27.tinypic.com/f406tz.png
But i cant get it to be like i want, instead it prints the rank on every row:
$old_rank = '';
while ($g = mysql_fetch_object($q)) {
if ($g->rankname != $old_rank) {
echo "<tr><td>$g->rankname</td>\n";
$old_rank = "<tr><td> </td>\n";
}
echo " <td>$g->name</td></tr>\n";
}
What I want:
<tr>
<td>One</td>
<td>Kraven the Hunter</td>
</tr>
<tr>
<td> </td>
<td>Kull the Conqueror</td>
</tr>
<tr>
<td> </td>
<td>Zazi The Beast</td>
</tr>
<tr>
<td>Vice-leader</td>
<td>Igos du Ikana</td>
</tr>
<tr>
<td> </td>
<td>Saint Sinner</td>
</tr>
<tr>
<td> </td>
<td>Midvalley the Hornfreak</td>
</tr>.......................
What I get:
<tr><td>One</td>
<td>Tester</td></tr>
<tr><td>One</td>
<td>Kraven the Hunter</td></tr>
<tr><td>One</td>
<td>Kull the Conqueror</td></tr>
<tr><td>One</td>
<td>Zazi The Beast</td></tr>
<tr><td>Vice-Leader</td>
<td>Midvalley the Hornfreak</td></tr>
<tr><td>Vice-Leader</td>
<td>Saint Sinner
</td></tr>
<tr><td>Vice-Leader</td>
<td>Igos du Ikana</td></tr>
$old_rank is never equal to $g->rankname because the way you are setting $old_rank, it will contain HTML tags, and the $g->rankname that you get from the DB will never have HTML tags.
Try changing your if statement to something like this:
if ($g->rankname != $old_rank) {
echo "<tr><td>$g->rankname</td>\n";
$old_rank = $g->rankname;
} else {
echo "<tr><td> </td>\n";
}
It prints the rank name if it's a new rank name, else it prints empty space.
The following (notwithstanding typos) separates out the display logic from the database loop. This has the advantages:
- You don't need to depend on the order of the results returned
- You don't need to maintain dodgy logic (like 'old_rank')
- You can display them more nicely (with a rowspan for repeated ranks
I believe the total code is more compact too.
// fill ranks array
$ranks = array();
while ( $g = mysql_fetch_object($q) ) {
if ( !in_array($g->rankname, $ranks) ) {
$ranks[htmlentities($g->rankname)] = array();
}
$ranks[$g->rankname][] = htmlentities($g->name);
}
// do other program logic here
// end of program
?>
<!-- display the page -->
<table>
<tr>
<th>Rank</th><th>Users</th>
</tr>
<?php foreach($ranks as $rankName => $userList): ?>
<tr>
<td rowspan="<?php echo (string)sizeof($userList); ?>">
<?php echo $rankName; ?>
</td>
<td> <?php echo implode('</td></tr><tr><td>', $userList); ?> </td>
</tr>
<?php endforeach; ?>
</table>
I prefer breaking things up a bit more than that. Keeping things separate makes it easier to modify. This should work.
$old_rank = '';
while ($g = mysql_fetch_object($q)) {
echo '<tr>' . "\n";
echo '<td>';
if ($g->rankname != $old_rank) {
$old_rank = $g->rankname;
echo $old_rank;
} else {
echo ' ';
}
echo '</td>';
echo '<td>' . $g->name . '</td>' . "\n";
echo '</tr>' . "\n";
}