Here is my code. I am fairly new to PHP and mySQL. I'm having a hard time figuring out why my fetch is returning the string "Array". Also, is there a better way to write all of the echo statements? What's proper php coding rules?
while($row = mysql_fetch_array($question))
{
$answerID = $row['intQAID'];
$getAnswer = mysql_query("SELECT cBody FROM tblQA WHERE intResponseID = $answerID AND intPosterID = '17'");
$answerBody = mysql_fetch_array($getAnswer);
echo "<tr class='forum'>";
echo "<td class='forum'>" . $row['intQAID'] . "</td>";
echo "<td class='forum'>" . substr($row['cBody'], 0, 150) . "</td>";
echo "<td class='forum'>" . $row['cCategory'] . "</td>";
echo "<td class='forum'>" . $row['username'] . "</td>";
echo "<td class='forum'>" . $row['post_time'] . "</td>";
echo "</tr>";
echo "<tr class='forum'>";
echo "<td class='forum'></td>";
echo "<td class='forum'>$answerBody</td>";
echo "<td class='forum'></td>";
echo "<td class='forum'></td>";
echo "<td class='forum'></td>";
}
echo "</table></div></div>";
It is returning Array because mysql_fetch_array is supposed to return an array. This is specified in the documentation and the name of the function!
Because it returns an array, it will still return one even if that array only has one item in it.
Your syntax is wrong. The mysql_fetch_array returns an array by default. If you try echo an array PHP outputs "Array". There are a lot of good examples in the PHP manual on the command.
The heredoc format is great for echoing large blocks. Alternatively you could end your php block and just start it again when needed (which is probably what I would do in this situation).
<?php
// lots of PHP statements
?>
<table>
....
<td><?php echo $variable; ?></td>
....
<?php
// resume php
?>
Some people use short tags in their code for echo. I personally don't although it's a matter of personal preference. The new versions of PHP have them enabled by default but older server installations may not support them.
Try this
<?php
$query = mysql_query("SELECT cBody FROM tblQA WHERE intResponseID = $answerID AND intPosterID = '17'");
while($row = mysql_fetch_assoc($query)):
?>
<tr>
<td><?php echo $row['field_name']; ?></td>
<td><?php echo $row['field_name']; ?></td>
<td><?php echo $row['field_name']; ?></td>
<td><?php echo $row['field_name']; ?></td>
<!-- and so on -->
</tr>
<?php endwhile; ?>
Related
I am trying to show a table as per the screen shot below.
Screen Shot
The goal is to have the 'folder' image as a clickable link getting the link data from the MySql table.
However, when i try to do this (step by step) the hyperlinks sit outside the table. When i add tags around the following
echo ''.$row['file'].'' ;
like this
echo "<td>" ''.$row['file'].'' "</td>";
The subsequent PHP page will not load
// Attempt select query execution
$sql = "SELECT * FROM versioncontrol";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table class='table table-bordered table-striped'>";
echo "<thead>";
echo "<tr>";
echo "<th>Image Link</th>";
echo "<th>Manual Link File</th>";
echo "<th>Operating Procedure ID</th>";
echo "<th>Operating Procedure Name</th>";
echo "<th>Operating Procedure Version</th>";
echo "<th>Upload Date and Time</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>
<a href=\"sopversioncontrolKL001.php" . $record['images'] . "\" >
<img src=\"images/document.jpg" . $record['images'] . "\" height=\"30\"
/></a></td>";
echo ''.$row['file'].'' ;
echo "<td>" . $row['SOP_ID'] . "</td>";
echo "<td>" . $row['SOP_Name'] . "</td>";
echo "<td>" . $row['SOP_Version'] . "</td>";
echo "<td>" . $row['reg_date'] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "<p class='lead'><em>No records were found.</em></p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
echo "<td>" ''.$row['file'].'' "</td>";
The subsequent PHP page will not load
Well, it wouldn't. That's a syntax error.
After echo "<td>" you need to have either a ; or an operator.
You can't just run straight into another string literal.
Put the <td> and </td> inside the string literals you already have.
echo '<td>'.$row['file'].'</td>';
Better yet, get rid of the enormous pile of echo statements and just output HTML.
?>
...
<td><?php echo $row['file']; ?></td>
...
<?php
(You should probably make use of htmlspecialchars to protect yourself against stored XSS attacks too).
I have a strange issue, where I have a table being populated by info from a database.
When I select from the database, the information comes back exactly as I would expect.
For some reason in my HTML table I have an odd field I can't see the source off.
My table header row:
echo "<tr>\n";
echo "<th><h3>ID</h3></th>\n";
echo "<th><h3>First Name</h3></th>\n";
echo "<th><h3>Last Name</h3></th>\n";
echo "<th><h3>Odd additional field</h3></th>\n";
echo "<th><h3>Country</h3></th>\n";
echo "<th><h3>Room type</h3></th>\n";
echo "<th><h3>Number</h3></th>\n";
echo "<th><h3>Checkin Date</h3></th>\n";
echo "<th><h3>Nights</h3></th>\n";
echo "</tr>\n";
The field I have called 'Odd additional field appears even if I take it out, it just isn't named.
My code to populate the table:
while($row = $sth->fetch()){
echo "<tr url=\"edit.php?id=" . $row['id'] . "\">\n";
echo "<td>" . $row['id'] . "</td>\n";
echo "<td>" . $row['firstName'] . "</td>\n";
echo "<td>" . $row['lastName'] . "</h3><td>\n";
echo "<td>" . $row['country'] . "</td>\n";
echo "<td>" . $row['roomtype'] . "</td>\n";
echo "<td>" . $row['roomnumber'] . "</td>\n";
echo "<td>" . $row['checkin'] . "</td>\n";
echo "<td>" . $row['nights'] . "</td>\n";
echo "</tr>\n";
}
The resultant HTML that goes to the browser:
<table width = "80%" align="center" id="example">
<tr>
<th><h3>ID</h3></th>
<th><h3>First Name</h3></th>
<th><h3>Last Name</h3></th>
<th><h3>Country</h3></th>
<th><h3>Room type</h3></th>
<th><h3>Number</h3></th>
<th><h3>Checkin Date</h3></th>
<th><h3>Nights</h3></th>
</tr>
<tr url="edit.php?id=1">
<td>1</td>
<td>Joe</td>
<td>Schmoe</h3><td>
<td>canada</td>
<td>mdorm</td>
<td></td>
<td>2012-11-16</td>
<td>5</td>
</tr>
</table>
Which all seems fine, and yet when viewing in a browser, this is what I see.
How can I trace this mysterious field?
echo "<td>" . $row['lastName'] . "</h3><td>\n";
should be
echo "<td>" . $row['lastName'] . "</td>";
OP Asked for an example on the preferred way to write html for his example. Please don't treat this as an actual answer to his question:
<?php while($row = $sth->fetch()): ?>
<tr data-url="edit.php?id=<?php echo $row['id']; ?>">
<td><?php echo $row['id'] ; ?></td>
<td><?php echo $row['firstName']; ?></td>
<td><?php echo $row['lastName']; ?></h3><td>
<td><?php echo $row['country']; ?></td>
<td><?php echo $row['roomtype']; ?></td>
<td><?php echo $row['roomnumber']; ?></td>
<td><?php echo $row['checkin']; ?></td>
<td><?php echo $row['nights']; ?></td>
</tr>
<?php endwhile; ?>
Here's why this is preferred, though the opinion may vary from person to person:
Maintainability:
if code is easier to read, it is easier to maintain. when you echo html in php you are subject to escaping html, making it more cluttered to read...
<?php echo "<div class=\"someclass\">" . $content . "</div>"; ?>
effectively the same as:
<?php echo '<div class="someclass">' . $content . '</div>'; ?>
except that the second example (single quotes is string literal) does not require escaping the double quotes. However, in either case, anyone who has to maintain this would much prefer this:
<div class="someclass"><?php echo $content; ?></div>
Because it is cleaner. Why? It just is. Also, many of the editors people use will highlight syntax differently for each language, so that in part makes it easier to read.
There may be cases where echoing html in php makes some sense, but treat it very sparingly. Anyone that reads your code after you will appreciate it.
Side note - you might want to change the html attribute "url" in your example to "data-url" as this is another convention you should use to keep people happy. Custom attributes are supported, but it is not a good idea to just make them up as you go. But if you have to, data- is the standard prefix for custom attributes.
This is the first time I'm using this website, I have recently started working on a project where the webpage will display two table, one of the table will gather all the information from a SQL Database and place them in the table along with a button next to each rows allowing you to insert that record to another to the other table, so far, this is the code I have written:
//Include the Following Files
include 'connect.php';
//Select All Price Plans
$query = "SELECT * FROM pricing";
$result = mysql_query($query);
//Print all Plans in Table
while ($pricing = mysql_fetch_array($result))
{
echo "<table border=1>";
echo "<tr>";
echo "<td>" .$pricing['planID']. "</td>";
echo "<td>" .$pricing['planTitle']. "</td>";
echo "<td>" .$pricing['planDescription']. "</td>";
echo "<td>" .$pricing['planPricing']. "</td>";
echo "<td>" . **BUTTON HERE** . "</td>";
echo "</tr>";
echo "<table>";
}
//Assign $link to Case
$link = '?run=planA';
//Pre-defined Functions
function planA()
{
$query = "INSERT into restaurant_plan (`planID`, `planTitle`, `planDescription`, `planPricing`) SELECT * FROM pricing WHERE planID='2' ";
$result = mysql_query($query);
}
//Setting Case to Run Each Functions
if (isset($_GET['run'])) $linkchoice=$_GET['run'];
else $linkchoice='';
switch($linkchoice)
{
case 'planA':
planA();
break;
case 'planB':
planB();
break;
}
Could anyone suggest any guide or possibly an example how I could assign a function to each rows? Thanks a lot!
your code prints one table for each record in table "pricing", use this code instead :
//Select All Price Plans
$mysqli = new mysqli("hostname", "username", "pass", "dbname");
$query = "SELECT * FROM pricing";
$result = $mysqli->query($query);
//Print all Plans in Table
echo "Available Price Plans";
echo "<table border=1>";
while ( $pricing = $result->fetch_assoc() ) {
echo "<tr>";
echo "<td>" .$pricing['planID']. "</td>";
echo "<td>" .$pricing['planTitle']. "</td>";
echo "<td>" .$pricing['planDescription']. "</td>";
echo "<td>" .$pricing['planPricing']. "</td>";
echo "<td>" .'<img style="border:none;" src="'. $icon .'" />'. "</td>";
//print a button as you mentioned
echo "<td>"."<form action='#' method='get'><input type='hidden' name='id' value='".$pricing['planID']."'/><input type='submit' value='copy'/></form></td>";
echo "</tr>";
}
echo "</table>";
and your function :
function planA()
{
// get selected plan info
$query = "SELECT * FROM pricing";
$result = $mysqli->query($query);
$row = $res->fetch_assoc();
//copy info to table 'restaurant_plan'
$query = "INSERT into restaurant_plan (".$_GET["id"].", ".$row["planTitle"].", ".$row["planDescription"].", ".$row["planPricing"].")";
$result = $mysqli->query($query);
}
Not an answer, but if you want your code to be cleaner & more readable/maintainable, you should use HTML with PHP inserted, rather than echoing HTML via PHP:
<?php
//Select All Price Plans
$query = "SELECT * FROM pricing";
$result = mysql_query($query);
//Print all Plans in Table
?>
Available Price Plans
<?php while ($pricing = mysql_fetch_array($result)) : ?>
<table border=1>
<tr>
<td><?= $pricing['planID'] ?></td>
<td><?= $pricing['planTitle'] ?></td>
<td><?= $pricing['planDescription'] ?></td>
<td><?= $pricing['planPricing'] ?></td>
<td><img style="border:none;" src="<?= $icon ?>" /></td>
</tr>
<table>
<?php endforeach; ?>
Also, as I mentioned in the comments above, you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this article.
Change your table output to the following:
<table border="1">
<?php
while ($pricing = mysql_fetch_array($result)) {
?>
<tr>
<td><?php echo $pricing['planID']; ?></td>
<td><?php echo $pricing['planTitle']; ?></td>
<td><?php echo $pricing['planDescription']; ?></td>
<td><?php echo $pricing['planPricing']; ?></td>
<td><a href='<?php echo $link; ?>'><img style="border:none;" src='<?php echo $icon; ?>' /></a></td>
</tr>
<?php
}
?>
<table>
Double check you database connection as well to ensure data can be retrieved.
I'm trying to make a page that once someone logs in, they can view the contents of the database that is associated with them in a clear, concise and organized way. Currently, I just have PHP echoing HTML and variables to make the page. i.e. I did what I knew would work.
I am new to everything programming and have done Javascript DOM manipulation so I can't see this echo thing can't being the right.
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['First_Name'] . "</td>";
echo "<td>" . $row['Last_Name'] . "</td>";
echo "<td>" . $row['Employee_No'] . "</td>";
echo "<td>" . $row['Job_No'] . "</td>";
echo "<td>" . $row['Job_Name'] . "</td>";
echo "</tr>";
}
echo "</table>";
I know that technically, this will work, but I am just looking for basic information on how to do this properly, preferably in an easy to understand format.
http://php.net/manual/en/book.dom.php
I found this, it looks like it is potentially what I need, but I am not experienced enough to know and it's not the most beginner friendly documentation.
In PHP when you create HTML output, you're not bound to the DOM. Because different to javascript, there is no DOM to share with the browser. Instead you can just create text output like with echo in your question. That's perfectly alright.
if you want, you can also divide your php code from html code in this way:
phpcode.php
while($row = mysql_fetch_array($result))
{
global $firstName, $lastName;
$firstName=$row['First_Name'];
$lastName=$row['Last_Name'];
include('htmlcode.php');
}
htmlcode.php
<?php global $firstName, $lastName; ?>
<tr>
<td><?php echo $firstName; ?></td>
<td><?php echo $lastName; ?></td>
<tr>
This is not needed most of times but can be helpful in some cases if you want a better readable code.
Just add echo "<table>"; before the while loop and the table should be rendered properly. You may need to use CSS style to further beautify the table
Have a look at PHP PDO. It will be easier when interacting with the database. Your code will look something like this:
echo "<table>";
foreach ($conn->query($query) as $row) {
echo "<tr>";
echo "<td>" . $row['First_Name'] . "</td>";
echo "<td>" . $row['Last_Name'] . "</td>";
echo "<td>" . $row['Employee_No'] . "</td>";
echo "<td>" . $row['Job_No'] . "</td>";
echo "<td>" . $row['Job_Name'] . "</td>";
echo "</tr>";
}
echo "</table>";
I always prefer the following, using pinouchon's code.
<table>
<?php foreach ($conn->query($query) as $row): ?>
<tr>
<td> <?= $row['First_Name'];?></td>
<td> <?= $row['Last_Name'];?></td>
<td> <?= $row['Employee_No'];?></td>
<td> <?= $row['Job_No'];?></td>
<td> <?= $row['Job_Name'];?></td>
</tr>
<?php endforeach;?>
</table>
<?php>
while($row = mysql_fetch_array($result2))
{
echo "<tr>";
echo "<td>" . $row['IDNO'] . "</td>";
echo "<td>" . $row['ADDRESS'] . "</td>";
echo "<td>" . $row['LASTNAME'] . "</td>";
echo "<td>" . $row['FIRSTNAME'] . "</td>";
echo "<td>" . <a href='update.php'>view</a> . "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
That's my code, I really don't know the correct format of putting links inside the php tags:
echo "<td>" . <a href='update.php'>view</a> . "</td>";
Please help
When using PHP to make webpages, the strings you echo out are pretty much always in the context of a HTML document. That is, if you want to output a HTML link, just echo it:
echo "<td><a href='update.php'>view</a></td>";
PHP is a templating language, there's no need to be throwing HTML around in strings.
<?php while ($row= mysql_fetch_array($result2)) { ?>
<tr>
<td><?php echo htmlspecialchars($row['IDNO']); ?></td>
<td><?php echo htmlspecialchars($row['ADDRESS']); ?></td>
<td><?php echo htmlspecialchars($row['LASTNAME']); ?></td>
<td><?php echo htmlspecialchars($row['FIRSTNAME']); ?></td>
<td>
view
</td>
</tr>
<?php } ?>
Note the use of HTML-escaping. Without this, < and & characters in your strings will be copied into the raw HTML, causing potential cross-site scripting security problems. Whether using PHP templating or sticking strings together, always HTML-escape plain text output.
If you are not pulling any dynamic values into the HTML for the cell with the link, you do not have to do any string concatenation here. Simply print out the HTML as a string:
echo "<td><a href='update.php'>view</a></td>";
However, it does not seem very useful to have the same link in every row of the table. Maybe you need to add a querystring parameter to the linked URL? To do this you will need to do string concatenation. The example below should get you started (notice the position of the quotes):
echo "<td><a href='update.php?id=" . $row['ID'] . "'>view</a></td>";
your "link" is the same HTML tag as <TD>. So, treat it as well
echo "<td><a href='update.php'>view</a></td>";
or if you want to pass parameter try
echo "<td><a href='update.php/value=".$val."'>view</a></td>";