The following code nicely outputs the column of users i have in a mysql database table in the browser.
<?php
$len = count($name);
for($i=0;$i<$len;$i++){
echo $name[$i];
echo "<p/>";
}
?>
However i would like each name to serve as a link to an external website. The website corresponding to each $name[] in the array is on the same row in the same table. So let us say that $name[0] has website w[0].
How on earth would i go about outputting the php in the browser so that each name linked to the corresponding website? Many thanks in advance. I hope i have been clear enough. Cheers
Sorry, i should probably add the above that appears in my php script:
$name = array();
$w = array();
$i=0;
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['username'];
$w[$i] = $result['website'];
$i++;
}
while($result = mysql_fetch_array($hof)){
echo ''.$result['username'].'<br>';
}
<?php
$len = count($name);
echo '<p>'
for($i=0;$i<$len;$i++){
echo '' . $name[$i] . '';
}
echo "<p/>";
?>
However, you should start learning some HTML basics before asking questions here.
Let's go!
Step #1.
Mysql Users table exmaple:
ID | Username | Website
1 | user_1 | user-1.com
2 | user_2 | user-2.com
3 | user-3 | user-3.com
Step #2
PHP
$mysqli = new mysqli("mhost", "muser", "mpassword", "databse");
if (! mysqli_connect_errno()) {
$query = "SELECT Username,Website FROM Users ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_row()) {
echo '' . $row[1] . '';
}
$result->close();
}
Easy just use ' instead of " in echo or string variable. Just like
<?php
echo ' Power Point Website';
?>
Related
everyone. I'm having a bit of a PHP conundrum here and I couldn't find a good answer that already existed. You see, I'm working on a project where I have to take a classmate's discography website and revamp it with PHP, to where, instead of having the album covers and tracklists hard-coded in, it would query the database for them. My problem is that I have to keep the general style of his site intact, and I'm having trouble doing that. Basically his styles depend on having the album cover, name, and tracklists in div tags, and the style he's got in place is achieved through both Bootstrap and his own, custom CSS stylesheet.
Before I start to ramble, my question is: is there any way to wrap looping output in HTML tags? I need to get the album cover, album name, and tracklists in a div tag, but only the tracklists loop. Here is the code I have in place to query the database:
<?php
require ('mysqli_connect.php');
// Connect to database server
mysql_connect("localhost", "admin", "instructor") or die(mysql_error());
// Select database
mysql_select_db("phprediscography") or die(mysql_error());
// SQL query
$q = "SELECT DISTINCT albums.albumname, albums.albumID, albums.coverart
FROM albums
JOIN tracks
ON albums.albumID=tracks.albumID"; //select UNIQUE results from database
$t = "SELECT trackname FROM tracks WHERE albumID = 1";
$b = "SELECT trackname FROM tracks WHERE albumID = 2";
$n = "SELECT trackname FROM tracks WHERE albumID = 3";
$r = "SELECT trackname FROM tracks WHERE albumID = 4";
$result = mysqli_query($dbcon, $q);
$result1 = mysqli_query($dbcon, $t);
$result2 = mysqli_query($dbcon, $b);
$result3 = mysqli_query($dbcon, $n);
$result4 = mysqli_query($dbcon, $r);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { //loop through database to get each album
echo '<img class="img-responsive" src=' . $row['coverart'] . '>' . '<br />';
echo '<h2>' . $row['albumname'] . "</h2><br />";
if ($row['albumID'] == 1) {
foreach($result1 as $row1) { //loop through tracks and output to page
echo '<p>' . $row1['trackname'] . '</p>';
}
}
if ($row['albumID'] == 2) {
foreach($result2 as $row2) { //loop through tracks and output to page
echo '<p>' . $row2['trackname'] . '</p>';
}
}
if ($row['albumID'] == 3) {
foreach($result3 as $row3) { //loop through tracks and output to page
echo '<p>' . $row3['trackname'] . '</p>';
}
}
if ($row['albumID'] == 4) {
foreach($result4 as $row4) { //loop through tracks and output to page
echo '<p>' . $row4['trackname'] . '</p>';
}
}
}
// Close the database connection
mysql_close();
?>
If I need to post anything else, let me know, this is my first-ever question so I'm just kind of feeling it out.
By doing your $t = "SELECT trackname FROM tracks WHERE albumID = #"; and if($row['albumID']==#) you are essentially still hardcoding similar to your friend. Just do 1 query, where you join all the tracks. Then when looping, group by the albumname -
<?php
require('mysqli_connect.php');
// SQL query
$q = "SELECT albums.albumname, albums.albumID, albums.coverart, tracks.trackname
FROM albums
JOIN tracks
ON albums.albumID=tracks.albumID";
$result = mysqli_query($dbcon, $q);
$current_albumID = ""; //create current albumID var to be used below.
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){//loop through database to get each album
if($row['albumID'] != $current_albumID){
echo '<img class="img-responsive" src='.$row['coverart'] . '>' . '<br />';
echo '<h2>' . $row['albumname'] . "</h2><br />";
$current_albumID = $row['albumID']; // set current albumID to this albumID
}
echo '<p>' . $row['trackname'] . '</p>';
}
?>
Try something like this instead: Get all the data you're after in your first query, then use php to process that into your output:
$q = "SELECT albums.albumname, albums.albumID, albums.coverart, tracks.trackname
FROM albums
JOIN tracks ON albums.albumID=tracks.albumID";
$result = mysqli_query($dbcon, $q);
$lastAlbumId = null;
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
if ($lastAlbumId != $row['albumID']) {
echo '<img class="img-responsive" src="'.htmlentities($row['coverart']).'"><br />';
echo '<h2>'.htmlentities($row['albumname']).'</h2><br />';
}
echo '<p>'.htmlentities($trackname).'</p>';
$lastAlbumId = $row['albumID'];
}
A few things to note:
I added use of htmlentities to escape the user data so malicious people can't type in HTML somewhere and have it appear on your site. This is something you should do almost everywhere you're displaying data from a database in a html site, except for very rare cases where you know what you're doing.
You probably don't need those <br /> tags - <h2> is a block level element so it'll force itself onto it's own line anyway (unless there's some silly CSS rules somewhere).
Also note - the above code is untested - typed straight into browser. There may be some syntax errors - let me know if you see any problem and I'll happily edit the answer. (or you can suggest an edit).
I am showing results arranged in table from mysql database using php, but I am not being able to find a way to paginate my results, because of the data being arranged in table and because some of the rows are missing and as webpage will be dynamic so user will be able to delete rows and insert new rows again and again, so because of that I can't get my results paginated using auto_increment value as well.
Following is my script:
<?php
$mysql_session = mysql_query("SELECT * FROM session");
$no_of_rows_session = mysql_num_rows($mysql_session);
$msg_session='';
$last_row = mysql_query("SELECT * from session ORDER BY id DESC LIMIT 1");
$last_id = '';
while($select_id_of_last_row = mysql_fetch_array($last_row)) {
$last_id = $select_id_of_last_row['id'];
}
?>
<?php echo $msg_session; ?>
<?php
if($no_of_rows_session < 1) {
$msg_session = 'No Session has been added yet';
} else {
for($i = 1; $i<=$last_id; $i++) {
${'mysql_session_every_single_query_' . $i} = mysql_query("SELECT * FROM session WHERE id LIKE '%$i%'");
${'mysql_existance_of_session_id_' . $i} = mysql_num_rows(${'mysql_session_every_single_query_' . $i});
while(${'mysql_every_session_data_' . $i} = mysql_fetch_array(${'mysql_session_every_single_query_' . $i})){
${'id_session_' . $i} = ${'mysql_every_session_data_' . $i}['id'];
${'session_start_' . $i} = ${'mysql_every_session_data_' . $i}['start'];
${'session_end_' . $i} = ${'mysql_every_session_data_' . $i}['end'];
echo "<table>";
echo "<tr id='tr_session_hover_" . $i . "'
class='tr_session_hover'
onClick=\"document.location='session_edit.php?ss=${'session_start_' . $i}&se=${'session_end_' . $i}';\">
<td>" . ${'session_start_' . $i} . "-" . ${'session_end_' . $i} . "</td>
</tr>";
echo "</table>";
}
}
}
?>
I think you are on wrong way. The things like this is simple when you choice the some order criteria and implement it into your table - for example the time of last edit or creation of the row. After that, when you have a page length and number of the page you have to use OFFSET / LIMIT clauses for SELECT, ordered by criteria - in this way you let the MySQL engine generate the proper pages.
I have got a solution.
If you are also facing such kind of problem and want to proceed with variables only (like me):
suppose you need to show 6 results on one page and your auto_increment (suppose a column named id is the auto_increment one, in your table) values are't regular, then what you can do is, get id of the 6th element by
I am supposing that you have already connected to phpmyadmin and selected a database
$no_of_results_per_page = 6;
if(isset($_GET['page_no'])) {
$page_no = $_GET['page_no'];
} else{
$page_no = 1;
}
$upper_limit = ($page_no - 1)*$no_of_result_per_page - 1;
if($page_no > 1){
$mysql_getting_id_le = mysql_query("SELECT id FROM table LIMIT $upper_limit, 1");
while($getting_id_last_elem = mysql_fetch_array($mysql_getting_id_le)) {
$id_last_element = $getting_id_last_elem['id'];
}
} else {
$mysql_getting_id_le = mysql_query("SELECT id FROM table LIMIT 0, 1");
while($getting_id_last_elem_p_1 = mysql_fetch_array($mysql_getting_id_le)) {
$id_last_element = $getting_id_last_elem_p_1['id'];
$id_last_element = $id_last_element - 1;
}
}
The above query will help us in getting id of the last element of the page
Now we will be creating the buttons to navigate from one page to another.
$final_mysql_query = mysql_query("SELECT * FROM table WHERE id > '%id_last_element%' LIMIT $no_of_results_per_page");
//Now, we can get all data limited to show no. of results you have defined per page using a loop
$total_results = mysql_query("SELECT * FROM table");
$total_results_count = mysql_num_rows($total_results);
$total_pages = ceil($total_results_count/$no_of_results_per_page);
$page_no = '';
for($i = 1; $i <= $total_pages; $i++) {
$page_no .= "<a href='?page_no=" . $i . "'>" . $i . "</a>";
}
First of sorry for my English, But i'll try to make my idea clear.
My goal : use one input field to search in multiple columns. i'll give an example to make it easier and clear for u guys to understand.
I've many CPUs for different brand. so if i'm going to write "CPU" it will give me all CPUs for all brands, but if i'm going to continue writing "CPU Lenovo" it will show me the CPU only for lenovo brand. so more detail gives more specific results.
here is my code :
<?php
require ('connection.php');
if (!empty($_POST['partname'])) {
$search = explode(" ", rtrim($_POST['partname'], " "), 2);
$prlist_name = "";
$prlist_model = "";
foreach ($search AS $s) {
$prlist_name .= "`prlist_name` LIKE '%" . mysql_real_escape_string($s) . "%' AND ";
$prlist_model .= "`prlist_model` LIKE '%" . mysql_real_escape_string($s) . "%' OR ";
}
$prlist_name = substr($prlist_name, 0, -4);
$prlist_model = substr($prlist_model, 0, -4);
$query = mysql_query("SELECT * FROM `prlist` WHERE ($prlist_name) AND ($prlist_model)");
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_assoc($query)) {
echo "<tr>";
echo "<td>" . $row['prlist_name'] . "</td>";
echo "<td>" . $row['prlist_model'] . "</td>";
echo "</tr>";
}
}
} else {
header('Location: index.php');
exit();
}
?>
The problem with my code is searching separately. i mean that if i'm going to write "CPU Lenovo". it will show me the whole parts for Lenovo. example:
CPU | Lenovo G580
RAM | Lenovo T430
CPU | Lenovo Z500
That's it. Thanks all :)
SELECT * FROM prlist WHERE MATCH (prlist_name,prlist_model)
AGAINST ('+CPU +Lenovo' IN BOOLEAN MODE);
http://dev.mysql.com/doc/refman/5.6/en/fulltext-boolean.html
OK I try this for days and I can't do it so I try to take it step by step first I need to get the info from the database correctly and show it in a form here is the database
CategoryID | CategoryName | ParentID
----------------------------------------
1 | FirstMenuCat1 | 0
2 | FirstMenuCat2 | 0
3 | SubMenuCat1 | 1
4 | SubMenuCat2 | 1
5 | SubMenuCat3 | 2
and here is my last attemp that worked so I know I get the correct data from database but I don't know how to make it a form:
<?php
require_once ('mysqli_connect.php');
$q = "SELECT CategoryName FROM menus where ParentID = '0' ORDER by CategoryID";
$r = #mysqli_query ($dbc, $q) or die("Error: ".mysqli_error($dbc));
/* associative array */
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
printf ("%s\n", $row["CategoryName"]);
}
?>
Here is my attempt to make it but its not working
/* associative array */
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
foreach($row){
echo "<option value=\"". urlencode( $_ ) ."\" $selected >$_</option>\n";
$selected = ""; // only the first element will be marked as selected
}
}
?>
Any ideas?
By looking at option tag i think you are trying to create a combobox list. If it is then First of all do not use \n. The options in a combobox list already shown line by line.
Secondly you have not printed the select tag. Without it the list will not be rendered properly. Try the following code:
echo "<select name='mylist'>";
$selected = "selected";
while (($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) !== FALSE){
echo "<option value='". $row['key']."' $selected >".$row['value']."</option>";
$selected = ""; // only the first element will be marked as selected
}
echo "</select>";
hopefully it may help.
Check this
echo '<select name="" id="">';
/* associative array */
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
// Check the $_ correctly
foreach($row){
echo "<option value='". urlencode( $_ ) ."'>$_</option>\n";
}
}
echo '</select>';
Note*: First element by default will be selected for the dd.
Not sure but I think this is what you need
$optionString = '';
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$value = urlencode($row['CategoryName']);
$optionString .= "<option value='{$value}'>{$row['CategoryName']}</option>";
}
echo "<select>$optionString</select>";
$selected = 'selected';
$htmlSelect = '<select name="elementName" id="elementId">';
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
$htmlSelect .= '<option value="' . urlencode( $_ ) . '" ' . $selected . ' >' . $_ . '</option>';
$selected = ""; // only the first element will be marked as selected
}
$htmlSelect .= '</select>';
echo $htmlSelect;
Note 1: It's better to use double quote " instead of single quote ' on element attributes. Some browsers don't like single quotes.
Note 2: Couldn't understand why you're using foreach again in the while statement.
Note 3: If you will not remember which option was selected there is not any need to specify which element is selected, first one will be selected by default.
I have a database to store people's quick links. This is a very basic quick link storage method. The database looks like this:
full_name | 1url | 1name | 2url | 2name | 3url |3 name | 4url |4name | 5url | 5name
^This goes on until 10. I know this is a bad way, but this is for an unprofessional website.
I will want to put the result into an ordered list. But I am unsure how to change the number (1url or 2url) each time?
So currently I have it set up like this in PHP
$result = mysql_query(SELECT * FROM `links` WHERE `full_name`='$loggedin')or die (mysql_error());
while($row = mysql_fetch_array($result)){
echo '<li><a href="';
echo $row['1url'];
echo '"></a></li>';
}
But I am having no luck with that! I'm very unsure of what I should do. I want it to display another <li> with an <a> and the link plus name of the link for each row found.
Thanks! Please be specific with me, as this is new ground! :D
EDIT:
I have also run into another problem. I have used code from peoples' answers and most of them work. However, If one of the fields is blank (so a user has only 6 quick links) it still shows an <li>. Now I can't see anyway round this issue. :/
SOLUTION:
Here is what works:
while($row = mysql_fetch_array($result)){
for($i = 1; $i < 10; $i++) {
if(!trim($row[$i . 'url'])=='') {
echo '<li><a href="';
echo $row[$i . 'url'];
echo '">';
echo $row[$i . 'name'];
echo '</a></li>';
} //end of didn't trim
}//end for for
}//end of while
$result = mysql_query("SELECT * FROM `links` WHERE `full_name`='$loggedin'")or die (mysql_error());
while($row = mysql_fetch_array($result)){
for($i = 1; $i < 10; $i++)
{
echo '<li><a href="';
echo $row[$i . 'url'];
echo '"></a></li>';
}
}
Mind you, this is pretty hacky... I would have just implemented it with 3 columns (maybe 4 using an autoincrement to sort) and then select the rows based on the user, emitting each row. That removes the 10 url limit.
Edit
For your second question, have a look at the PHP 'empty' function and break/continue the loop if the function returns true.
It would be a lot cleaner and easier to change your database setup a little bit. You could have two tables:
users
id: a unique ID for each user, probably an auto increment int of some sort
full_name: just as you've used it in your table
quick_links
id: quick link id, probably an auto increment int (or you could do a primary index on user_id+order)
user_id: the user ID to tell us who this quick_link belongs to
name: the name of the quick link
url: the url of the quick link
order: what order to show this link in
Then you can simply do something like
$userid_result = mysql_query(
"SELECT `id` from `users` WHERE `full_name` = $loggedin;"
);
$row = mysql_fetch_row($userid_result);
$userid = $row[0];
$links_result = mysql_query(
"SELECT * from `quick_links` WHERE `user_id` = $userid ORDER BY `order` ASC;"
);
while($quick_link = mysql_fetch_object($links_result))
{
printf("<li>%s</li>", $quick_link->url, $quick_link->$name);
}
Of course you'd need some error checking in there, but that gives you an idea.
You need to put some double quotes around your select statement:
$result = mysql_query("SELECT * FROM `links` WHERE `full_name`='$loggedin'") or die (mysql_error());
while($row = mysql_fetch_array($result)){
echo '<li><a href="';
echo $row['1url'];
echo '"></a></li>';
}
while ($row = mysql_fetch_array($result))
{
$full_name = array_shift($row);
for ($i = 0; $i < 10; ++$i)
{
echo '<li><a href=' . htmlspecialchars(array_shift($row)) . '>';
echo array_shift($row);
echo '</a></li>';
}
}
array_shift returns the first element from an array and removes it from the array at the same time. So the code above removes the full_name field from the record and then iterates over the rest of the record, removing and printing a URL and its corresponding name on each iteration.
htmlspecialchars is used to ensure that a valid a-tag is created. Depending on where the name of the link comes from, it should also be used on the name of the link.
You SQL query needs to be passed as a string enclosed in "...":
$result = mysql_query( "SELECT * FROM `links` WHERE `full_name`='$loggedin'" )
or die (mysql_error());
$i = 0;
while($row = mysql_fetch_array($result)){
$attributeURL = $i . 'url';
$attributeName = $i++ . 'name';
echo '<li>'
. '' . $row[ $attributeName ] . '
. '</li>'
;
}