Multiple row & column table data into string - php

Im trying to make a datalist which will have the options as:
ItemCode - Name
Code and Name are in the same table but are in different columns
Ive got it working for just code:
<?php
while($res=mysql_fetch_row($code))
{
$fullname=$res[0];
echo "<option value=$fullname></option>";
}
?>
I tried doing the following for both:
<?php
while(($res=mysql_fetch_row($code)) && ($res2=mysql_fetch_row($name)))
{
$fullname=$res[0]." - ".$res2[0];
echo "<option value=$fullname></option>";
}
?>
However I had no joy, any help would be greatly appreciated.

echo "<option value=$fullname>$fullname</option>";
//instead of $module?

Try this:
<?php
$query="select ItemCode,Name from tablename";
$result=mysql_query($query);
$cols=2;
echo "<table>";
do{
echo "<tr>";
for($i=1;$i<=$cols;$i++)
{ $row=mysql_fetch_array($result);
?>
<td>
<table>
<tr valign="top">
<td>
<b><?=$row['ItemCode'] ?></b><br />
<?=$row['Name'] ?><br />
</td>
<td width="50"> </td> <!-- Create gap between columns -->
</tr>
</table>
</td>
<?
}
} while($row);
echo "</table>";
?>

You may want to use something like this:
while ($row = mysql_fetch_assoc($result)) {
$value = $row['item_code'] . " - " . $row['name'];
echo '<option value="' . $value . '">' . $value . '</option>';
}
Note: mysql_query, mysql_fetch_row and mysql_fetch_assoc are deprecated, use something else.
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.

Related

PHP returning a blank page after executing the script

This code was working perfectlty as most of you said. I had a little issue with the path pointing to this script. The problem now is that I am having issues with the hyperlink with the href code line. I have a field in my database that is labled fulltext . I am trying to create a script that allows me display the content of fulltext (echo "{$row['fulltext']}.";) when I click on the Read More button. The hyperlink should be populated with the echo "{$row['title']}.";
What mistake am I making by inserting a href="fulltext.php?=$row['fulltext']
<table>
<?php
$dbhost = 'localhost';
$dbuser = 'myusernm';
$dbpass = 'mypwd';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT title, introtext, created, created_by, catid FROM mydb_items';
mysql_select_db('muslimtimes360');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo '<tr>'; echo '<td>'; echo '<span class="post-date">'; echo "{$row['created']}."; echo '</span>'; echo '</td>'; echo '</tr>';
echo '<tr>';
echo '<td>'; echo '<h2 class="blog-post-title">'; echo "{$row['title']}."; echo '</h2>'; echo '</td>';
echo '</tr>';
echo '<tr>';
echo '<td>'; echo '<p>'; echo "{$row['introtext']}."; echo '</p>'; echo '</td>'; echo '</tr>';
echo '<p>'; echo '<tr>';
echo '<td>'; echo ''; echo '<input type="button" value="Read More" />'; echo ''; echo '</td>';
echo '</tr>';
echo '</div>';
echo '<div class="blog-meta">';
echo '<img src="img/avatar.png" alt="Avatar" />';
echo '<tr>'; echo '<td>'; echo '<h4 class="blog-meta-author">'; echo "{$row['created_by']}."; '</h4>';
echo '<span>'; echo 'Category:'; echo "{$row['catid']}."; echo '</span>'; echo '</td>'; echo '</tr>';
echo '</table>';
}
echo "";
mysql_close($conn);
?>
Please note mysql_fetch_array only need data (array), no need to give MYSQL_ASSOC, because you're conflating MySQL and MySQLi
and
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
Change this
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
to this:
while($row = mysql_fetch_array($retval))
and inside while just use:
echo $row['created'];
No need of use like this echo "{$row['created']}".
You are Using Old Mysql Syntax Which is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0.
If you are using Latest version of PHP then your code will not Work.Change the appropriate Syntax and Try again.
Try remove the first line table and put inside
example
while($row = mysql_fetch_array($retval))
{
echo '<table>';
I have tried to run your code with only adjusted connection credentials and table/column names and it works fine (using php 5.5 and php 5.3).
Isn't possible there is no record in the database? Another possibility could be some typo.
Edit: Also you have only one table opening tag while as many closing tags as there is records present. Try to inspect source code of the 'blank page'.
Edit2: Try running this snippet instead of your former code and let us know what happens:
<?php
// connection string constants
define('DSN', 'mysql:dbname=muslimtimes360;host=localhost');
define('USER', 'myusernm');
define('PASSWORD', 'mypwd');
// pdo instance creation
$pdo = new PDO(DSN, USER, PASSWORD);
// query preparation
$stmt = $pdo->query("
SELECT title, introtext, created, created_by, catid
FROM mydb_items
");
// fetching results
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// if this returns 0 then it means no records are present
echo count($result) . "\n";
// the loop should print valid table
foreach ($result as $index => $row) {
if ($index == 0) echo '<table>';
echo <<<HTM
<tr>
<td>
<span class="post-date">{$row['created']}</span>
</td>
</tr>
<tr>
<td>
<h2 class="blog-post-title">{$row['title']}</h2>
</td>
</tr>
<tr>
<td>
<p>
{$row['introtext']}
</p>
</td>
</tr>
<tr>
<td>
<p>
<input type="button" value="Read More" />
</p>
</td>
</tr>
<tr>
<td>
<div class="blog-meta">
<img src="img/avatar.png" alt="Avatar" />
<h4 class="blog-meta-author">{$row['created_by']}</h4>
<span>Category: {$row['catid']}</span>
</div>
</td>
</tr>
HTM;
if ($index == (count($result)-1)) echo '</table>';
}

multiple arrays value fetching with session

Insert Is Fine But if I select this value from database All Values are fine but single values fetch array problem I don't know how to solve this task. Please Update this code asap.
This Is Insert Code .....
<?php
if(isset($_POST['sendmessage'])){
$entermessage = $_POST['teachermessage'];
$checkbox_user = $_POST['usernameallcheckbx'];
$arr = implode(',',$checkbox_user);
//$arr2 = explode(',',$arr);
$insert = mysql_query("INSERT into usermessages(fromteacher,toparent,messages) VALUES('".$_SESSION['username']."','$arr','$entermessage')");
if($insert == 1){
echo "<h1>successful</h1>";
}
else{
echo mysql_error();
}
}
?>
<form method="post">
<div style="float:left; width:450px;"><br/><br/>Message: <br/>
<textarea style="width:400px; height:300px;" name="teachermessage"></textarea><br/>
<input type="submit" value="Send" name="sendmessage" /></div>
<div style="float:left; with:200px; padding-top:55px;">
<table>
<tr>
<?php
$select_query1 = mysql_query("SELECT * FROM register_user WHERE teacher='$teachername'");
while($chckbx=mysql_fetch_array($select_query1))
{
?>
<td><?php echo "<input type='checkbox' name='usernameallcheckbx[]' value=". $chckbx['userid']." />"; ?></td>
</tr>
<tr>
<td><?php echo $chckbx['parent_fname']." ".$chckbx['parent_lname']; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</form>
And This Is Select Code....
<h2>Messages</h2>
<?php
$select_query3 = mysql_query("SELECT * FROM usermessages");
$fetch= mysql_fetch_array($select_query3);
$data=$fetch['toparent'];
$arr=explode(',',$data);
//$userids=explode(',',$data);
$sessionshow=$_SESSION['userid'];
$userids=in_array("$sessionshow",$arr);
$select_query2 = mysql_query("SELECT * FROM usermessages WHERE toparent in ('$userids')='".$_SESSION['userid']."'");
?>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<th>Teacher Name</th>
<th>Message</th>
</tr>
<?php
while($fetch_name2=mysql_fetch_array($select_query2))
{
echo "<tr>";
echo "<td>".$fetch_data=$fetch_name2['fromteacher']."</td>";
echo "<td>".$fetch_data=$fetch_name2['messages']."</td>";
echo "</tr>";
}
?>
</table>
I have only put this as an answer to show some incorrect code - remove fetch data from your loop as it doesn't do anything
while($fetch_name2=mysql_fetch_array($select_query2))
{
echo "<tr>";
echo "<td>".$fetch_name2['fromteacher']."</td>";
echo "<td>".$fetch_name2['messages']."</td>";
echo "</tr>";
}
even better is use of a HEREDOC:
while($fetch_name2=mysql_fetch_array($select_query2))
{
echo <<<EOF
<tr>
<td>{$fetch_name2['fromteacher']}</td>
<td>{$fetch_name2['messages']}</td>
</tr>
EOF;
}
I really can't figure out what you're trying to do, but maybe this is the query you want:
SELECT * FROM usermessages WHERE FIND_IN_SET('$sessionshow', toparent)
FIND_IN_SET(str, strlist) searches the comma-separated list in strlist for an element that equals str, and returns the position in the list; if it's not found it returns 0, which counts as false.
I can't see any purpose to any of the code that uses $select_query3.

Display information from MySQL

I have a code that display on the page the information of a specific user, from a MySQL table. However, the informaiton is all displayed on a simple line, back to back. What I want, is to display the information of each line in diffrent blocks. So my question: how can I «brake» the line, to create many diffrent blocks of information, that I can put were I want on my page?
<?php
while ($row = mysql_fetch_array($query)) {
echo $row['Column A'] . " " . $row['Column B'] . " " . $row['Column C'] . " ";
} ?>
First of all you should change your mysql_* functions to another functions like PDO & mysqli
About your question is how to generate HTML from your DB data there are multiple of ways
One could be like this
<?php
while ($row = mysql_fetch_array($query)) {
?>
<h1><?php echo $row['columnA']; ?></h1>
<div class="myclass"><?php echo $row['columnb']; ?></div>
<img src="<?php echo $row['columnC']; ?>">
<?php
} ?>
Two could be
<?php
while ($row = mysql_fetch_array($query)) {
$str = "";
$str .= "<h1>".$row['columnA']."</h1>";
$str .= '<div class="myclass">'.$row['columnb'].'</div>';
$str .= '<img src="'.$row['columnC'].'">';
echo $str;
<?php
} ?>
Or you can use a FW wich make it simpler for you
Or you can use a templating library which is the best way for you if you are not going to use a Framework
check out mustache https://github.com/bobthecow/mustache.php
Of course you can change the HTML structure
I hope this can help :)
I think a table might be what you are looking for...
(Don't forget to change to mysqli* as #Sedz mentioned in his answer)
<table border="1">
<?php
while ($row = mysqli_fetch_array($query)) {
echo '<tr>';
echo '<td>' . $row['Column A'] . '</td>';
echo '<td>' . $row['Column B'] . '</td>';
echo '</tr>';
echo '<tr>';
echo '<td></td>';
echo '<td>' . $row['Column C'] . '</td>';
echo '</tr>';
};
?>
</table>
Arrange the results in rows/cells as you see fit...
Perhaps the best way is you pass the results into an array
$data = array();
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
And the break you are talking about
foreach ($data as $value) {
echo "$value<br>";
}
It is simple user2619310!
Add "\n" in your line.
Example:
<?php
while ($row = mysql_fetch_array($query)) {
echo $row['Column A'] . " " . $row['Column B'] . " " . $row['Column C'] . "\n";
}
?>
Bye! :-D
How you break the lines can vary depending on what your objectives are and where you're going to use them. Here are some ways of having information on different lines:
Use the br tag at the end of each field.
Use DIVs to contain each row.
Use a table for each row.
DIVs will be the best if you're looking at different browsers and efficient sizing. But tables are also easy to implement for certain things.
Here's how I'd break the rows using tables.
<table>
<?php while ($row = mysql_fetch_array($query)): ?>
<tr>
<td>Column A label</td>
<td><?php echo $row['ColumnA']; ?></td>
</tr>
<tr>
<td>Column B label</td>
<td><?php echo $row['ColumnB']; ?></td>
</tr>
<tr>
<td>Column C label</td>
<td><?php echo $row['ColumnC']; ?></td>
</tr>
<?php endwhile; ?>
</table>
I don't have the slightest clue about your DB table structure but going by what you've shown, I have included an example. This is not tested but it should be good.
Also note the alternative PHP syntax for the while loop.

Displaying Reminders page from MySQL Database

I've created a PHP program for adding and viewing reminders. The add page works, but I'm having some trouble displaying them properly. How should I code this to only get the actual data? Also, how could I put this into an HTML table? (i.e. column for name, description, and date; rows are the retrieved data)
Thanks
When I open the file in my browser I get this as an output:
Array ( [reminderID] => 14 [reminderName] => Test [reminderDescript] => Test_Descript [reminderDate] => 2012 05 7 )
Code:
<?php include 'header.php'; ?>
<?php include 'database.php'; ?>
<div id="content">
<h1>Reminder List</h1>
<table align ="center">
<thead>
<tr>
<td>Name</td>
<td>Description</td>
<td>Date</td>
</tr>
</thead>
<?php
$query = 'SELECT * FROM reminder_event';
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
print_r($row);
}
?>
</table>
<p><a href='reminder_add.php'>Add Reminder</a></p>
</div>
<?php include 'footer.php'; ?>
print_r() is a diagnostic tool for debugging, not to be used for real output. Instead, output HTML to a table using the array keys fetched from your row.
// Open a table
echo "<table>";
while($row = mysql_fetch_assoc($result)) {
// Output each row
echo "<tr>
<td>{$row['reminderName']}</td>
<td>{$row['reminderDescript']}</td>
<td>{$row['reminderDate']}</td>
</tr>";
}
// Close the table
echo "</table>";
Better still, escape each of the values for HTML output with [htmlspecialchars()] (http://us3.php.net/manual/en/function.htmlspecialchars.php) before output to prevent cross-site scripting attacks and broken HTML if characters like < > & are encountered in the values.
echo "<table>";
while($row = mysql_fetch_assoc($result)) {
// Encode all values for HTML output
$name = htmlspecialchars($row['reminderName']);
$desc = htmlspecialchars($row['reminderDescript']);
$date = htmlspecialchars($row['reminderDate']);
// Then output the encoded values
echo "<tr><td>$name</td><td>$desc</td><td>$date</td></tr>";
}
echo "</table>";
Change:
while($row = mysql_fetch_assoc($result)) {
print_r($row);
}
To:
while($row = mysql_fetch_assoc($result)) {
echo $row['reminderID'];
echo $row['reminderName'];
echo $row['reminderDescript'];
echo $row['reminderDate'];
}
You can echo those values out in whatever HTML you'd like. So, for example, if you want it in a table you would do something like this:
echo "<table><tr>";
while($row = mysql_fetch_assoc($result)) {
echo "<td>" . $row['reminderID'] . "</td>";
echo "<td>" . $row['reminderName'] . "</td>";
echo "<td>" . $row['reminderDescript'] . "</td>";
echo "<td>" . $row['reminderDate'] . "</td>";
}
echo "</tr></table>";
You can clean that up a bit to take some (or all) of the HTML out of the PHP.
<?php include 'header.php'; ?>
<?php include 'database.php'; ?>
<div id="content">
<h1>Reminder List</h1>
<table>
<thead><tr><td>id</td><td>name</td><td>description</td><td>date</td></tr></thead>
<tbody>
<?php
$query = 'SELECT * FROM reminder_event';
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $row['reminderID']; ?></td>
<td><?php echo $row['reminderName']; ?></td>
<td><?php echo $row['reminderDescript']; ?></td>
<td><?php echo $row['reminderDate']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<p><a href='reminder_add.php'>Add Reminder</a></p>
</div>
<?php include 'footer.php'; ?>

Unexpected output when comparing database column to variable

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";
}

Categories