I am trying to figure out where I went wrong with my code.
I built my navbar with php in the unordered list of the navbar to retrieve the menu elements from an SQL table called "menu" from a database called "shop", with no avail.
I even have a print_r in place, only to show me that my resource is working, but for some reason the whole code isn't creating the menu items as written.
This is the code:
<?php
$menu = [];
mysql_connect('localhost', 'root', '');
mysql_select_db('shop');
$result= mysql_query("SELECT * FROM menu");
if ($result && mysql_num_rows($result)>0){
while($row = mysql_fetch_assoc($result)){
$menu[] = $row;
}
}
echo '<pre>';
$error= print_r($menu);
$error = '' ;
echo '</pre>';
?>
<!DOCTYPE html>
<html>
<head>
<link href="_CSS/style.css" rel="stylesheet" type="text/css"/>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="site-wrapper">
<div class="header">
<div class="navbar">
<ul>
<li>Home</li>
<?php if(count($menu) >0) : ?>
<?php foreach ($menu as $row) : ?>
<li><?php $row = ['link']; ?></li>
<?php endforeach; ?>
<?php endif; ?>
</ul>
</div>
<div class="member">
<ul>
<li>Login</li>
<li>Register</li>
</ul>
</div>
</div>
</div>
The result unfortunately looks like this:
Your problem is this:
<?php $row = ['link']; ?>
It should probably be this:
<?php echo $row['link']; ?>
Maybe you got confused trying to do this:
<?= $row['link']?>
Mistake 1 :
You have used
$row = ['link'];
Where you will get this error Notice: Array to string conversion in ..
So you need to have $row['link'];
Mistake 2 :
You need to output the content using echo
<li><?php echo $row['link']; ?></li>
Warning : Don't use mysql_* functions as it is depreciated instead use mysqli or PDO for safer Operations !
Related
I did one webpage with pagination in php. But i want to include some filter to search in this pagination. So if someone has good advice, will be good received.
Here is the file where i did the pagination. The name is, Index.php:
<?php
require_once 'database.php';
$database_connection = database_connect();
$title='hola';
$content='';
//user input
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 2;
//Positioning
$start = ($page > 1) ? ($page * $perPage) - $perPage : 0;
$art = $database_connection->query("SELECT id FROM coffee");
//Query
$articles = $database_connection->prepare("SELECT id FROM coffee LIMIT $start,$perPage");
$articles->execute();
$articles = $articles->fetchAll();
$resultado = $database_connection->query("SELECT COUNT(*) AS total FROM coffee");
$fila = $resultado->fetch(PDO::FETCH_ASSOC);
$total = $fila["total"];
$pages = ceil($total/$perPage);
include 'Template_1.php';
?>
And here is my html website. Template:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><?php echo $title; ?></title>
<link rel="stylesheet" type="text/css" href="Styles/Stylesheet.css" />
</head>
<body>
<div id="wrapper">
<div id="banner">
</div>
<nav id="navigation">
<ul id="nav">
<li>Home</li>
<li>Coffee</li>
<li>Shop</li>
<li>About</li>
</ul>
</nav>
<div id="content_area">
<?php
require_once("tool.php");
foreach ($articles as $article):
echo $article['id'];?>
</br><?php
endforeach;?></br><?php
for($x=1;$x<=$pages;$x++):?>
<?php echo $x;?>
<?php endfor;?>
</br>
<?php echo $content; ?>
</div>
<div id="sidebar">
</div>
<footer>
<p>All rights reserved</p>
</footer>
</div>
</body>
</html>
I'm not sure if i know what you mean by "But i can't combine search with my pagination." But as i understand you want to add some kind of a 'where' statement in your query.
Here are examples of doing it and i think the last code from this site is what you want: http://www.webreference.com/programming/php/search/2.html
In the first page of my site the user suppose to see some categories, under each category there are some sub-categories. I am fetching these categories and sub-categoires from database. There are two tables in the database called "category" and "subcategory" and i have tried to merge these two tables. The ouput should be something like this
but i am getting this ouput
here is my code
<?php
$host="localhost";
$user="root";
$pass="";
$db="doc";
$conn=mysqli_connect($host,$user,$pass,$db);
$show=mysqli_query($conn,"SELECT DISTINCT a.id, a.category_name, b.subcat_name, b.cat_name
FROM category a, subcategory b
WHERE a.category_name = b.cat_name");
?>
<html lang="en">
<head>
<title>Home</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
<link href="css/custom.css" rel="stylesheet">
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="bootstrap/bootstrap.min.js"></script>
<script src="js/jquery.min.js"></script>
</head>
<body>
<div class="col-lg-3 sidebar">
<?php
while($showsub = mysqli_fetch_assoc($show)) { ?>
<ul>
<li><i class="fa fa-cube"></i><?php echo $showsub['category_name']; ?>
<ul style="list-style-type:circle">
<li><?php echo $showsub['subcat_name']; ?></li>
</ul>
</li>
</ul>
<?php
}; ?>
</div>
</body>
</html>
I am stuck here for last 2 days.
You should format the array first accordingly -
$categories= $subcats= array();
while($showsub = mysqli_fetch_assoc($show)) {
$categories[]= $showsub['category_name']; // array of categories
$subcats[$showsub['category_name']][]= $showsub['subcat_name']; // array of sub categories with category as indexes
}; ?>
Then the HTML -
foreach($categories as $cat) { // Loop through the categories array
?>
<ul>
<li><i class="fa fa-cube"></i><?php echo $cat; ?>
<?php foreach($subcats[$cat] as $subcat) {?> // loop through the subcategories depending on categories
<ul style="list-style-type:circle">
<li><?php echo $subcat; ?></li>
</ul>
<?php } ?>
</li>
</ul>
<?php
}
<?php
$host="localhost";
$user="root";
$pass="";
$db="doc";
$conn=mysqli_connect($host,$user,$pass,$db);
?>
<html lang="en">
<head>
<title>Home</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
<link href="css/custom.css" rel="stylesheet">
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="bootstrap/bootstrap.min.js"></script>
<script src="js/jquery.min.js"></script>
</head>
<body>
<div class="col-lg-3 sidebar">
<?php
$cat = mysqli_query($conn,"SELECT DISTINCT id, category_name FROM category");
while($rowCat = mysqli_fetch_assoc($cat))
{
$catName = $rowCat['category_name'];
?>
<ul>
<li>
<i class="fa fa-cube"></i>
<a href="category.php?id=<?php echo $rowCat['id']; ?>">
<?php echo $rowCat['category_name']; ?>
</a>
<?php
$subCat = mysqli_query($conn,"SELECT * FROM subcategory WHERE cat_name='$catName'");
while($rowSubCat = mysqli_fetch_assoc($subCat))
{?>
<ul style="list-style-type:circle">
<li><?php echo $rowSubCat['subcat_name']; ?></li>
</ul>
<?php }?>
</li>
</ul>
<?php
}?>
</div>
</body>
</html>
Just two general advices: Learn a templating system to be able to split presentation (html) and Logics (php) and look into using prepared statements for MySQL - that will make your life a lot easier a little bit down along the road
What you get is exactly what would be expected from the code you have shown. You ask for each subcategory with its category. You have two different ways of solving this:
Either - as Sougata said - make two different tables and join then accordingly. But it is also possible to make the two-level list from one table. Then you need to make sure that the categories and subcategories comes in an order that makes sense:
$show=mysqli_query($conn,"SELECT DISTINCT a.id, a.category_name, b.subcat_name, b.cat_name
FROM category a, subcategory b
WHERE a.category_name = b.cat_name
order by category_name, subcat_name");
If you just add on "order by" to Your sql-query, Your output should look like
Category 1
Subcat 1
Category 1
Subcat 3
Category 1
Subcat 5
Category 2
Subcat 2
Category 2
Subcat 4
The next step will be to add some logics to supress repeating categories:
<ul>
<?php
$oldcat="";
$started=0;
while($showsub = mysqli_fetch_assoc($show)) {
$cat=$showsub['category_name'];
$subcat=$showsub['subcat_name'];
if ($oldcat != $cat){
if($started){print("</ul>");}
print("<li>$cat</li><ul>\n");
}
print("<li>$subcat</li>")
}
print("</ul></ul>\n");
?>
This is not a direct replacement of your code, but I hope you get the idea. Read it as a php-heavy pseudo code...
and again, please do yourself a favour and start using a templating system..
What I would like to know is when I grab data from a Database how can I format it with PHP so it looks nice. All i seem to be getting is a Blank white page and when i inspect the page with google chromes inspect element it says that i've got a 500 internal error.
For example, I'm using PDO to connect to the database. Heres my code:
<?php
$hostname='localhost';
$username='root';
$password='root';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=fitness", $username, $password);
$sql = "SELECT * FROM fitness";
$fitnessResult = $dbh->query($s ql);
$fitness = $dbh->fetchObject($fitnessResult);
foreach ($fitness AS $fit) {
$fitnessArray[] = ['name' => $fit->name, 'id' => $fit->description];
}
$dbh = null;
}
catch (PDOexception $e) {
echo "Error is: " . $e-> etmessage();
}
and here is my html im using the twitter bootstrap framework.
<?php
include'inc/connect.inc.php';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fitness</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap- theme.min.css">
<link rel="stylesheet" href="css/style.css" />
<!-- Latest compiled and minified JavaScript -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-4">
<?php foreach ($fitnessArray AS $fitness) { echo '<h2>'. $fitness['name'] .'</h2>'; echo '<p>' . $fitness['description'] . '</p>';} ?>
</div>
<div class="col-xs-8">
<p>Dummy Text</p>
</div>
</div>
</div>
</body>
</html>
So how would I put the name into a H1 tag and the description into P tag.
Thanks
You might want to try something like the following which keeps the objects and fetchs all in an arrary
$fitnessResult = $dbh->query($sql);
$fitnessArray = $fitnessResult->fetchAll(PDO::FETCH_OBJ);
then in your html
<?php foreach ($fitnessArray AS $fitness): ?>
<h2><?=$fitness->name ?></h2>
<p><?=$fitness->description ?></p>
<?php endforeach; ?>
see official docs for fetchAll()
I have my footer.php with admin button in it and when i include it at the end of my page the button doesn't appear.. But if i put it before this code:
<?php if ($row["rights"]=="2"):?>
<div id='cssmenu-admin'>
<ul>
<li name='admin' class='active'><a href='administration.php'><span>Admin</span></a></li>
</ul>
</div>
<?php endif; ?>
from footer.php before while cycle it works like it should.
This my footer.php file:
<div id="footer">
<hr>Copyrighted (C) 2014 by djdanas#gmail.com<br>
<?php if ($row["rights"]=="2"):?>
<div id='cssmenu-admin'>
<ul>
<li name='admin' class='active'><a href='administration.php'><span>Admin</span></a></li>
</ul>
</div>
<?php endif; ?>
</div>
<br><hr>
And this is my page file:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Pagrindinis</title>
<link href="CSS/stilius.css" rel="stylesheet" type="text/css"/>
<link href="CSS/menu.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<?php require("includes/validate.php");?>
<?php require("includes/stilius.php");?>
<?php
require("includes/connection_to_db.php");
$sql = "SELECT prekės.* , CONCAT(vartotojai.name) as v_name
FROM prekės
LEFT JOIN vartotojai
ON vartotojai.V_ID=prekės.V_ID
ORDER BY prekės.date
DESC LIMIT 8";
$result = mysql_query("$sql");
?>
<?php mysql_close(); ?>
<?php while ($row = mysql_fetch_assoc($result)) : ?>
<?php $image = '<td><img src="data:image/jpeg;base64,'.base64_encode($row['image']).'" name="pix" width="270" height="200"/></td>' ?>
<table class="two">
<th><?php echo $row['name'] ?></th>
<th>Prekės savininkas: <?php echo $row['v_name']?></th>
<th><input type="button" value="Mainyti"></th>
<tr>
<?php echo $image?>
<td><textarea disabled style="resize:none; background-color:white" name="about" rows="12" cols="65"><?php echo $row['specs']?></textarea><td>
</table>
<?php endwhile; ?>
<?php require("includes/footer.php");?>
</body>
</html>
EDIT:
Ok, i solved my problem by adding new variable
$rights = $row['rights'];
right after
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Pagrindinis</title>
<link href="CSS/stilius.css" rel="stylesheet" type="text/css"/>
<link href="CSS/menu.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<?php require("includes/validate.php");?>
<?php require("includes/stilius.php");?>
in my page file and changed 1 line in my footer.php file from
<?php if ($row['rights']=="2"):?>
to
<?php if ($rights="2"):?>
now it's working like a charm :)
I'll take a stab in the dark here and say that your test
if ($row["rights"]=="2")
means you are checking to see if the user logged in has the "rights" of 2?
Then when you loop through your query...
while ($row = mysql_fetch_assoc($result))
You are overwriting your $row variable. So whatever you thought was in there to begin with, isn't anymore. You should use a different variable for either your user or looping through the query.
EDIT:
It's also possible that the variable isn't in scope once you get to where you are testing it. You could try using a print_r($row) in footer.php to see what is currently inside of $row -- that should help.
I am adding an ancillary page to my wordpress site ( without the site's styling, menu, etc ) using the following template and it is not returning any results from the database. I've read countless web pages and a couple of WP books and I am at a lost. I can see the four records in the database but the page shows none. Here's my template:
<?php
/*
Template Name: Media Player Page
*/ ?><!DOCTYPE html> >
<head>
<meta charset="<?php bloginfo('charset'); ?>" />
<title>Online Media Player</title>
<?php wp_head(); ?>
<link rel="stylesheet" href="/assets/css/music-player.css" type="text/css" media="screen" charset="utf-8">
<script src="/assets/js/jquery-1.8.3.js"></script>
</head>
<body>
<div class="main-center">
<h1>Please select your choice of music</h1>
<?php
global $wpdb;
$rows = $wpdb->get_results("select * from ppm_playlists");
foreach($rows as $row) :
?>
<a class="openplayer" data-genre="<?php echo $row['id']; ?>" href="#"><?php echo $row['playlist']; ?></a>
<?php endforeach; ?>
</div> <!-- /.main-center -->
<script type="text/javascript">
(function($) {
$('.main-center').on('click', '.openplayer', function(e){
var genre = $(this).data('genre');
e.preventDefault();
alert(genre);
});
})(jQuery);
</script>
</body> </html>
$wpdb->get_results will return an array of objects, not an array of arrays, unless you pass it a second parameter instructing otherwise. If you had debugging enabled, you would see Fatal Error: Cannot use object of type stdClass as array....
You want to be using object syntax:
foreach($rows as $row) : ?>
<a class="openplayer" data-genre="<?php echo $row->id; ?>" href="#"><?php echo $row->playlist; ?></a>
<?php endforeach; ?>
Or pass a second parameter to get_results
$rows = $wpdb->get_results("select * from ppm_playlists", ARRAY_A);