Php pdo: Showing topics out database - php

I need some help finding out how to show all the topics from the mysql (phpmyadmin) database on my website.
This is how it looks like now
The code for that is:
<section class="col-md-4 connectedSortable">
<!-- TABLE: LATEST ORDERS -->
<div class="box box-info">
<div class="panel panel-default">
<div class="panel-heading main-color-bg">
<h3 class="panel-title">Topics</h3>
</div>
<div class="container-fluid">
<div class="row content">
<ul class="nav nav-pills nav-stacked">
<li class="active">Home</li>
<li>Friends</li>
<li>Family</li>
<li>Photos</li>
</ul><br>
</div>
</div>
</div>
</div><!-- /.box -->
</section><!-- right col -->
I want this list to be the list of topics out of the database
How the database looks like
this is my config.php:
<?php
date_default_timezone_set('Europe/Amsterdam');
error_reporting(E_ALL & ~ E_DEPRECATED);
ini_set('display_errors','ON');
$CONFIG = array();
$CONFIG['root'] = '####';
$CONFIG['rootwebsite'] = '####';
$CONFIG['website'] = '####';
$CONFIG['dbhost'] = 'localhost';
$CONFIG['dbuser'] = '####';
$CONFIG['dbpass'] = '####';
$CONFIG['dbdatabase'] = 'tom';
?>
What I tried:
class Forum
{
private $dbh; //dbh = database handler.
public function __construct($database)
{
$this->dbh = $database;
}
/* function that gets the main forum board */
public function getForum()
{
$query = $this->dbh->prepare('SELECT * FROM `topics` ORDER BY `id` ASC');
$query->execute();
$results = $query->fetchAll();
foreach( $results as $row ){
print_r( $row );
}
}
}

Here goes from the PDO perspective:
<?php
// Connect to DB
try {
$yourdsn = 'mysql:dbname=<YOURDBNAME>;host=<YOURDBHOST>;
$data = new PDO($yourdsn, $youruser, $yourpassword);
$data->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data->exec("set names utf8");
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Then query your table
$sql = "SELECT * FROM topics ORDER BY id DESC";
$topics = $data->prepare($sql);
$topics->execute();
$tops = $topics->fetchAll(PDO::FETCH_OBJ);
Finally loop results in HTML template
<? foreach($tops as $top):?>
<h1><?=$top->onderwerp?></h1>
<p><?=$top->omschrijving?></p>
<? endforeach;?>

Related

Data from MySQL not showing while building dynamic menu in PHP

I'm building a dynamic menu using PHP and MySQL but results are not showing:
The website structure is built below:
<div id="container">
<ul class="nav">
<li>home</li>
<li>
destinations &triangledown;
<div id="subMenu">
<div class="nav-column">
Europe
</div>
<div class="nav-column" >
Africa
</div>
<div class="nav-column" >
Asia
</div>
<div class="nav-column">
Oceania
</div>
<div class="nav-column">
North America
</div>
<div class="nav-column">
South America
</div>
</div>
</li>
<li>about</li>
<li>contact</li>
</ul>
</div>
Then i have a continents DB and then another DB with countries, which connect to their respective continent.
So, in the subMenu div, i want to call each continent and then in each div cnt_submenu_, loop through a unordered list of 9 results and then show another with the same number of results and so on until all the countries with the same id reaches the end.
Here is what i'm trying to do with the PHP code below:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<div id="container">
<ul class="nav">
<li>home</li>
<li>destinations
<div id="subMenu">
<?php
$servername = "localhost:3306";
$username = "root";
$password = "";
$dbname = "site_comboios";
//Open DB connection
$mysqli = new mysqli($servername, $username, $password, $dbname);
//check connection
if($mysqli->connect_errno) {
echo 'Error connecting to database';
exit();
}
//show sub-menu
$query = "SELECT * FROM continentes ORDER BY id";
$result = mysqli_query($mysqli, $query);
$div = 0;
while ($row = mysqli_fetch_assoc($result)) {
$país = $row['continente'];
echo "<div class='nav-column'><a href='#' class='continente' data-id='cnt_submenu'>" .($país). "</a></div> "; </div> ";
}
?>
</div>
</li>
<li>about</li>
<li>contact</li>
</ul>
</div>
<div id="cnt_submenu_" class="submenu_continente active">
<?php
//retrieve european countries from DB and open <ul> with 9 results
$conn = mysqli_connect("localhost:3306","root","","site_comboios");
$sql_countries = "SELECT * FROM countries ORDER BY id WHERE id_continentes = 1" ;
$res_countries = mysqli_query($conn, $sql_countries);
if($res_countries > 0) {
while ($row_countries = mysqli_fetch_assoc($res_countries)) {
$país = $row_countries['id_continente'];
echo "<ul><li><a href='#'>". $país ."";
}
} else if ($res_countries == 9) {
echo '</li></ul>';
}
?>
<span class="close">x</span>
</div>
Thanks for pointing me out in the right direction.
Edited I'm trying to show through 9 results onto a , close it and open another with 9 results until the end of the countries with id = 1.
Added the jquery to open each continent div below but i'm not doing it right:
//Open and close each div with country list
$('.continente').hover(function(){
menuHide('submenu_continente' . $(this).data("id") );
$('#cnt_submenu_' . $(this).data("id") ).show();
},function(){
$('#cnt_submenu_' . $(this).data("id")).mouseleave( function() {
$(this).hide();
});
});

Object of class __PHP_Incomplete_Class could not be converted to string

Hi I have this error "Catchable fatal error: Object of class __PHP_Incomplete_Class could not be converted to string in C:\xampp\htdocs\ProjectTA\dao\CustomerDao.php on line 161" like this, I have no idea to solve this problem I check all and everything is fine to me
this my Customer dao
public function getOneCustomer($id) {
try {
$conn = Connection::getConnection();
$query = "select * from Customer c join Company comp on c.Company_IdCompany = comp.IdCompany JOIN City cit ON c.City_Id = cit.IdC WHERE c.IdCustomer = ?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $id);
$stmt->execute();
$row = $stmt->fetch();
$customer = new Customer();
$customer->setIdCustomer($row['IdCustomer']);
$customer->setCustomerName($row['CustomerName']);
$customer->setPhoneNumber($row['PhoneNumber']);
$customer->setBankNumber($row['BankNumber']);
$customer->setCAddress($row['AddressC']);
$customer->setCEmail($row['EmailC']);
$customer->setPassword($row['Password']);
$customer->setCustomerStatus($row['CustomerStatus']);
$customer->setPhoto($row['Photo']);
$company = new Company();
$company->setIdCompany($row['IdCompany']);
$company->setCompanyName($row['CompanyName']);
$company->setWebsite($row['Website']);
$company->setPhone($row['Phone']);
$company->setEmail($row['Email']);
$company->setAddress($row['Address']);
$company->setLogo($row['Logo']);
$city = new city();
$city->setIdC($row['IdC']);
$city->setNameC($row['NameC']);
$customer->setCompany_IdCompany($company);
$customer->setCity_Id($city);
} catch (PDOexception $e) {
echo $e->getMessage();
die();
}
$conn = null;
return $customer;
}
and I want to display this in my customer view
<?php
if (isset($_SESSION['IdCustomer'])) {
$dao = new CustomerDao();
$id = $_SESSION['IdCustomer'];
$dataInfo = $dao->getOneCustomer($id);
echo '<div class="col-md-12">
<div id="fh5co-tab-feature-vertical" class="fh5co-tab">
<ul class="resp-tabs-list hor_1">
<li><i class="fh5co-tab-menu-icon ti-ruler-pencil"></i> Company</li>
<li><i class="fh5co-tab-menu-icon ti-paint-bucket"></i> Project & Task</li>
<li><i class="fh5co-tab-menu-icon ti-shopping-cart"></i> Proof of Payment</li>
</ul>
<div class="resp-tabs-container hor_1">
<div>
<div class="row">
<div class="col-md-12">
<h2 class="h3">Company</h2>
</div>
<div class="col-md-6">
<h2>'.$dataInfo->getCustomerName().'</h2> // i want diplay customer name
</div>
</div>
</div>
</div>
</div>
</div>
</div>';
}?>
Thank You
so, I have a solution to this problem. I was wrong when validate data login in the customer login session

MySQL Database row in a Button

I have a database for my ToDo App which has following cloumns:
| ID | ShortDescription | Description | Date | Status |
I already can add a Task to the Datatable and can see it in phphmyadmin.
I have following code till now:
$id = mysql_real_escape_string($_GET['id']);
$out = 'SELECT * FROM ToDo1 WHERE `id` = '.$id.' LIMIT 1';
$result = mysqli_query($link, $out);
$row= mysqli_fetch_array($result);
?>
<div id= "OutShortDescription">
<?php
echo $row['ShortDescription'];
?>
</div>
<div id= "OutDescription">
<?php
echo $row['Description'];
?>
</div>
<div id= "OutDate">
<?php
echo $row['Date'];
?>
</div>
<div id= "OutStatus">
<?php
echo $row['Status'];
?>
</div>
Now I want to put every ID row on a own Site.
For that I want to make a table of Buttons (Buttonnumber=ID).
On this Button should only be shown the ShortDescription and when I click it I want to go to a the Site which matches to the Button.
Can someone help me?
EDIT
okay thanks now I have this code but it wont work:
<?php
$dbname= 'Groups';
$dsn = 'mysql:host=localhost;dbname='.$dbname;
$user = 'root';
$pass = '';
$db = new PDO($dsn, $user,$pass);
$query = "SELECT * FROM groups2 WHERE id = :id LIMIT 1";
$ps = $db->prepare($query);
$ps->bindParam(':id', $id);
$ps->execute();
$row = $ps->fetch(PDO::FETCH_ASSOC);
?>
<div class="searchwindow">
<?php
$data = $link->query('SELECT * FROM Groups2');
foreach($data as $row) {
echo '<p><input type="button" onclick="window.location = All_Groups.php?id=' . $row['ID'] . ' value='.$row['ShortDescription'].' /></p>';
}
I have now following code
<div data-role="page" id="SearchPage" data-title="SearchPage">
<div data-role="header">
<h1>Search</h1>
</div>
<div data-role="content">
<div data-role="header">
<form>
<fieldset data-role="controlgroup" data-type="horizontal" data-mini="true" align="center" id="selectMenu">
<select name="selectStatus" id="selectStatus">
<option value="0">Status</option>
<option value="1">Done</option>
<option value="2">In Progress</option>
</select>
</fieldset>
</form>
</div>
<?php
$dbname= 'Groups';
$dsn = 'mysql:host=localhost;dbname='.$dbname;
$user = 'root';
$pass = '';
$db = new PDO($dsn, $user,$pass);
$query = "SELECT * FROM groups2 WHERE id = :id LIMIT 1";
$ps = $db->prepare($query);
$ps->bindParam(':id', $id);
$ps->execute();
$row = $ps->fetch(PDO::FETCH_ASSOC);
?>
<div class="searchwindow">
<?php
$data = $link->query('SELECT * FROM Groups2');
foreach($data as $row) {
$path = $row['ID'];
$description = $row['ShortDescription'];
echo ("<form action='All_Groups.php?id=$path'><button type='submit' value='$description'/>$description</form>" );
}
?>
</div>
</div>
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Search</li>
<li>New</li>
<li>More</li>
</ul>
</div><!-- Ende navbar -->
</div><!-- Ende footer -->
</div>
And this is my All_groups.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Unbenanntes Dokument</title>
</head>
<body>
<?php
$servername ="localhost";
$username = "root";
$password = "";
$dbname = "Groups";
$link = mysqli_connect($servername, $username, $password, $dbname);
if (!$link) {
die('Verbindung nicht möglich : ' . mysqli_error($link) );
}
?>
<?php
$row="";
$Date="";
$Status="";
$ShortDescription="";
$Description="";
mysqli_select_db($link, "groups");
?>
</div>
<?php
$id = mysql_real_escape_string($_GET['id']);
$out = "SELECT * FROM groups2 WHERE ID = '$id' ";
$result = mysqli_query($link, $out);
$id = mysqli_fetch_array($result);
?>
<div id= "OutShortDescription">
<?php
echo $id['ShortDescription'];
?>
</div>
<div id= "OutDescription">
<?php
echo $id['Description'];
?>
</div>
<div id= "OutStatus">
<?php
echo $id['Status'];
?>
</div>
<div id= "OutDate">
<?php
echo $id['Date'];
?>
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Search</li>
<li>New</li>
<li>More</li>
</ul>
</div><!-- Ende navbar -->
</div>
</body>
</body>
</html>
First of all, don't use the mysql_* methods! Use PDO or mysqli_* instead.
Below, I'm pasting your example query, using PDO:
$dsn = 'mysql:host=localhost;dbname='.$dbname;//$dbName is the name of your database
$user = 'root';
$pass = '123';//use your login information here
$db = new PDO($dsn, $user,$pass);
$query = "SELECT * FROM ToDo1 WHERE id = :id LIMIT 1";
$ps = $db->prepare($query);
$ps->bindParam(':id', $id)
$ps->execute();
$row = $ps->fetch(PDO::FETCH_ASSOC);
Now, to get your button, you don't need to use jquery:
<?php
$path = $row['ID'];
$description = $row['ShortDescription'];
echo "<form action='your/site/$path'><button type='submit' value='$description'/>$description</form>"
?>
Another option is use the onclick:
<?php
$path = $row['ID'];
$description = $row['ShortDescription'];
echo "<input type=\"button\" onclick=\"location.href='your/site/$path'\" value=\"$description\" />";
?>
The \ before " is a escape, so PHP will print the character " and not interpret it as the end of your string.
Advice: Try to avoid mix HTML and PHP, in general this is a bad practice.

Putting the WHERE statement in SQL STATEMENT

<div class = "col-md-9 text-left">
<?php
$host = 'localhost';
$dbname = 'project';
$username = 'root';
$password = '1234';
$charset = 'utf8';
try
{
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql = "SELECT subject,description,time,date FROM status";
$q = $pdo->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$usid = ($row['userID']);
$sql1 = 'SELECT status.subject, status.description, status.time , status.date , status.stno , status.userID , tbl_users.userID , tbl_users.Fname , tbl_users.Lname
FROM status , tbl_users
WHERE status.userID=tbl_users.userID ORDER BY status.time DESC';
$q1 = $pdo->prepare($sql1);
$q1->execute([$usid]);
$q1->setFetchMode(PDO::FETCH_ASSOC);
}
catch (PDOException $e)
{
die("Could not connect to the database $dbname :" . $e->getMessage());
}
?>
<?php while ($row = $q->fetch()): ?>
<?php while ($row1 = $q1->fetch()): ?>
<div class="col-md-9">
<div class="box box-widget">
<div class="box-header with-border">
<div class="user-block">
<img class="img-circle" src="<?php echo $row10['des']; ?><?php echo $row9['userPic']; ?>" alt="User Image">
<span class="username"><?php echo htmlspecialchars($row1['Fname']); ?> <?php echo htmlspecialchars($row1['Lname']); ?></span>
<span class="description">Shared publicly - <?php echo htmlspecialchars($row['time']) ?> <?php echo htmlspecialchars($row['date']) ?></span>
</div>
<!-- /.user-block -->
<div class="box-tools">
<button type="button" class="btn btn-box-tool" data-toggle="tooltip" title="Mark as read">
<i class="fa fa-circle-o"></i>
</button>
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
<button type="button" class="btn btn-box-tool" data-widget="remove">
<i class="fa fa-times"></i>
</button>
</div>
<!-- /.box-tools -->
</div>
<!-- /.box-header -->
<div class="box-body">
<p><b><?php echo htmlspecialchars($row1['subject']) ?></b></p>
<p><i><?php echo htmlspecialchars($row1['description']) ?></i></p>
<?php
// Check connection
$servername = "localhost";
$username = "root";
$password = "1234";
$dbname = "project";
htmlspecialchars($a = $row1['stno']);
$d1 = $row7['userID'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM likes WHERE rec = $a";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$GLOBALS['a'] = $row['do'];
}
}
$z4 = $GLOBALS['a'];
if ($d1==$z4)
{
include ("unlikee.php");
}
else
{
include ("likee.php");
}
$conn->close();
?>
<span class="pull-right text-muted"><?php
$con=mysqli_connect("localhost","root","1234","project");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
htmlspecialchars($a = $row1['stno']);
$sql="SELECT * FROM likes WHERE rec = $a";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("%d\n",$rowcount);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
</h5>
<span class="description-text"><?php
$con=mysqli_connect("localhost","root","1234","project");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
htmlspecialchars($a = $row1['stno']);
$sql="SELECT * FROM likes WHERE rec = $a";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
if ($rowcount==1)
echo 'Like';
else
echo 'Likes';
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?> - 3 comments</span>
</div>
<!-- /.box-body -->
<!-- /.box-footer -->
<div class="box-footer">
<form action="#" method="post">
<img class="img-responsive img-circle img-sm" src="../dist/img/user4-128x128.jpg" alt="Alt Text">
<!-- .img-push is used to add margin to elements next to floating images -->
</form>
</div>
<!-- /.box-footer -->
</div>
<!-- /.box -->
</div>
<?php endwhile; ?> <?php endwhile; ?>
</div>
I want to retrieve the Data of only one USER but I don't know how to give a condition for it in SQL Statement. Where and how I can put WHERE userID = $user_Session?
$sql = "SELECT subject,description,time,date FROM status";
In the two code statements above where should I put the first?
$sql1 = 'SELECT status.subject, status.description, status.time , status.date , status.stno , status.userID , tbl_users.userID , tbl_users.Fname , tbl_users.Lname
FROM status , tbl_users
WHERE status.userID=tbl_users.userID ORDER BY status.time DESC';
$sql1 =
'SELECT
status.subject, status.description, status.time , status.date , status.stno , status.userID , tbl_users.userID , tbl_users.Fname , tbl_users.Lname
FROM
status , tbl_users
WHERE
status.userID=tbl_users.userID
AND [correct_table_name].userID = $user_Session # here with AND instead WHERE
ORDER BY
status.time DESC';
Here is the code I added a parameter UID
try
{
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql = "SELECT subject,description,time,date FROM status";
$q = $pdo->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$usid = ($row['userID']);
$sql1 = 'SELECT status.subject, status.description, status.time , status.date , status.stno , status.userID , tbl_users.userID , tbl_users.Fname , tbl_users.Lname
FROM status , tbl_users
WHERE status.userID=tbl_users.userID and tbl_users.userID = :UID ORDER BY status.time DESC';
$q1 = $pdo->prepare($sql1);
$q1->bindParam(':UID', $usid, PDO::PARAM_INT); //call with param
$q1->execute();
$q1->setFetchMode(PDO::FETCH_ASSOC);
}

Dynamic Dropdown menu - PHP

First of all, I am new to mysqli and prepare statements so please let me know if you see any error. I have this static drop down menu :
HTML code:
<ul class="menu sgray fade" id="menu">
<li>Bike
<!-- start mega menu -->
<div class="cols3">
<div class="col1">
<ol>
<li>bikes</li>
<li>wheels</li>
<li>helmets</li>
<li>components</li>
</ol>
</div>
<div class="col1">
<ol>
<li>pedals</li>
<li>GPS</li>
<li>pumps</li>
<li>bike storage</li>
</ol>
</div>
<div class="col1">
<ol>
<li>power meters</li>
<li>hydratation system</li>
<li>shoes</li>
<li>saddles</li>
</ol>
</div>
</div>
<!-- end mega menu -->
</li>
I want to make a dynamic dropdown menu. I managed to show the $categoryName and the $SubCategoryName with this function:
function showMenuCategory(){
$db = db_connect();
$query = "SELECT * FROM Category";
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->bind_result($id,$categoryName,$description,$pic,$active);
while($stmt->fetch()) {
echo'<li>'.$categoryName.'
<!-- start mega menu -->
<div class="cols3">
<div class="col1">
<ol>';
$dba = db_connect();
$Subquery = "SELECT * FROM Subcategory WHERE CategoryId = '".$id."'";
$Substmt = $dba->prepare($Subquery);
$Substmt->execute();
$Substmt->bind_result($Subid,$CatId,$SubCategoryName,$SubDescription);
while($Substmt->fetch()) {
echo'
<li>'.$SubCategoryName.'</li>';
}
echo'
</ol>
</div>
<!-- end mega menu -->
</li>';
}
}
The only problem is that it returns all the subcategories on the the same <div class="col1">:
what I would like to obtain is count the subcategories and if the result is more than 4 return the other items in the second and third column.
UPDATE***: thanks to the answer below now the menu looks like this:
thanks!
How about try this?
To explain further
What is happening is that for every subcategory fetched, I increment a counter. If that counter hits 4, it ends the <UL> and <DIV> and creates a new one which will represent the new column.
function showMenuCategory(){
$db = db_connect();
$query = "SELECT * FROM Category";
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->bind_result($id,$categoryName,$description,$pic,$active);
while($stmt->fetch()) {
echo'<li>'.$categoryName.'
<!-- start mega menu -->
<div class="cols3">
<div class="col1">
<ol>';
$dba = db_connect();
$Subquery = "SELECT * FROM Subcategory WHERE CategoryId = '".$id."'";
$Substmt = $dba->prepare($Subquery);
$Substmt->execute();
$Substmt->bind_result($Subid,$CatId,$SubCategoryName,$SubDescription);
$count = 0;
while($Substmt->fetch()) {
echo'
<li>'.$SubCategoryName.'</li>';
$count+=1;
if ($count == 4) {
$count = 0;
echo '</ol></div><div class="col1"><ol>';
}
}
echo'
</ol>
</div>
<!-- end mega menu -->
</li>';
}
}
EDIT: Misunderstood the purpose of col1. They all should be col1 and should work now. If not, leave me a comment!
Try this:
function showMenuCategory(){
$db = db_connect();
$query = "SELECT * FROM Category";
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->bind_result($id,$categoryName,$description,$pic,$active);
echo '<div class="cols3">';
while($stmt->fetch()) {
echo'<li>'.$categoryName.'
<!-- start mega menu -->
<div class="col1">
<ol>';
$dba = db_connect();
$Subquery = "SELECT * FROM Subcategory WHERE CategoryId = '".$id."'";
$Substmt = $dba->prepare($Subquery);
$Substmt->execute();
$Substmt->bind_result($Subid,$CatId,$SubCategoryName,$SubDescription);
while($Substmt->fetch()) {
echo'<li>'.$SubCategoryName.'</li>';
}
echo'</ol>';
}
echo '</div><!-- end mega menu --></li>';
}

Categories