How to select data from each row of database using php - php

I am working to create a Blog page, I want to retrieve data from database using php. I have created 2 pages:
Blogs Page
Preview Page
Blog page is used to retrieve all data from the database and display only Title and Concept of the blog. After the concept there is a button to view whole blog. I am uploading example of UI, like how should it look.
Blog Example
After clicking on button, it should Navigate to preview page where whole content of blog should be dynamically changed as according to Title selected in Blog Page.
Now, I've created 2 blogs on backend but it is taking all the values from database of the latest one that I created recently, even when I am clicking on the button of the blog which I created 2 days ago.
Code for Blog Page that I written is:
<?php
session_start();
$dbHost = "localhost";
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'Database';
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($db->connect_error){
die("Connection failed: " . $db->connect_error);
}
$sql = $db->prepare('Select * from blogs;');
$sql->execute();
$result = $sql->get_result();
?>
<!DOCTYPE html>
<html>
<head>
<title>Blogs</title>
<?php include '_header.html'; ?>
<link rel="stylesheet" href="css/about.css">
<link rel="stylesheet" href="css/blog.css">
</head>
<body>
<?php include '_navbar.html'; ?>
<div class="bg2">
<h1>Our Opinion</h1>
</div>
<div class="col-sm-12">
<div class="container">
<div class="col-sm-12">
<div class="row">
<div class="col-sm-12">
<?php
if($result)
{
while($row = $result->fetch_assoc())
{
echo "<h3><a href = 'preview.php' style = 'color:black'>".$row['Title']."</a></h3>";
$_SESSION['Title'] = $row['Title'];
echo "<p>".$row['concept']."</p><hr>";
}
}
?>
</div><hr>
</div>
</div>
</div>
</div>
<div style="padding:50px"></div>
<?php include '_footer1.html'; ?>
<?php include '_footer.html'; ?>
</body>
</html>
And code for Preview Page is:
<?php
session_start();
$title = $_SESSION['Title'];
$dbHost = "localhost";
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'database';
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($db->connect_error){
die("Connection failed: " . $db->connect_error);
}
$sql = $db->prepare("SELECT * FROM blogs where Title = ?");
$sql ->bind_param("s",$title);
$sql->execute();
$result = $sql ->get_result();
?>
<!DOCTYPE html>
<html>
<head>
<title>Preview</title>
<?php include '_header.html'; ?>
<link rel="stylesheet" href="css/treatment.css">
</head>
<body>
<?php include '_navbar.html'; ?>
<div class="col-sm-12">
<div class="container-fluid">
<div style="text-align:center">
<img src = "img/Ayurvedjya 02.png" alt = "Ayurvedajya Logo" width = "15%">
</div>
<?php
if($result)
{
while($row = $result->fetch_assoc())
{
echo "<h3>".$row['Title']."</h3><hr>";
?>
<div class="col-sm-12">
<div class="row">
<div class="col-sm-9">
<?php echo "<p><b>".$row['Content']."</b></p>";?>
</div>
<div class="col-sm-3">
<?php
echo '<img src="img/'.$row['image'].'" width= 100%/>';
?>
</div>
</div>
</div>
<?php }}else {echo "No Data";}?>
</div>
</div>
<div style="padding:50px"></div>
<?php include '_footer1.html'; ?>
<?php include '_footer.html'; ?>
</body>
</html>
Can anyone please confirm where I am going wrong and How can I fix this?

you're putting the data of each row into the session, overwriting that value each time it loops, and then redirecting afterwards (your header values get overwritten on each loop too, only the last one is issued to the browser). The title you're putting into the session is unrelated to what was actually clicked on. Your form needs to send the ID of the clicked blog and then use that, not the data fetched from the database.
Also for this scenario there's really no reason to post the form to the same script and then redirect (as per your original code). A simple hyperlink with a query parameter will do the job very nicely:
Blog page:
echo "<h3><a href = 'preview.php?id=".$row["ID"]."' style = 'color:black'>".$row['Title']."</a></h3>";
Preview page:
<?php
session_start();
$id = $_GET["id"]; //get the ID from the URL
//... etc, then
$sql = $db->prepare("SELECT * FROM blogs where ID = ?");
$sql ->bind_param("i",$id);
Note that I'm assuming here that your blogs have an integer ID column as the primary key in the database - this would be normal practice, and it's more robust to use that as the query parameter than the title (because titles can change, or not be unique, or have characters in them which don't work well in a URL, etc. so I strongly suggest you use the ID to identify the blog instead of the title).

Related

Unknown issue with $_SERVER["REQUEST_METHOD"] returning false when it should be true

Hey there stackoverflow users, i have come upon a very confusing problem that I cant seem to move past. I am creating a forum type web page and am currently working on the comments section. I have a form that uses the post method to send your comment as well as a hidden input to store the threads ID. I will post the entire php file below just to make sure nothing is left out.
<?php
session_start();
parse_str($_SERVER['QUERY_STRING'], $link);
$threadID = $link['ID'];
require("config.php");
$connection = mysqli_connect($host, $user, $password, $database);
$error = mysqli_connect_error();
if($error != null) {
$output = "<p>Unable to connect to database!</p>";
exit($output);
} else {
//Get Thread Data
$query = "SELECT username, title, content FROM threads, users WHERE threads.ID = $threadID AND users.ID = threads.makerID;";
$results = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($results);
//Get Comment Data
$query = "SELECT username, comment FROM comments, users WHERE threadID = $threadID AND users.ID = comments.makerID;";
$results = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($results);
}
?>
<!DOCTYPE html>
<html>
<head lang="en">
<title>BodyweightMate</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/styling.css"/>
</head>
<body>
<!--Top masthead-->
<header class="masthead" id="top">
<h1 class="masthead-title"> Welcome To BodyweightMate </h1>
</header>
<!--Navigation bar-->
<nav class="navbar">
<table class="navbar-table">
<tr>
<!--Logo-->
<td>
<a class="navbar-brand" href="main.php">
<img src="../images/logo.jpg" alt="BodyweightMate" height="30" width="30">
</a>
</td>
<!--Login/Profile-->
<?php if(isset($_SESSION['login_user'])) {
echo"<td><a class=\"navbar-profile\" href=\"profile.php\"> Profile </a></td>";
echo"<td><a class=\"navbar-logout\" href=\"logout.php\"> Logout </a></td>";
} else {
echo"<td><a class=\"navbar-login\" href=\"login.php\"> Login </a></td>";
}?>
</tr>
</table>
</nav>
<!--Main portion-->
<section class="content-section">
<article>
<h3><?php echo $row['username']. ": " .$row['title']; ?></h3>
<p><?php echo $row['content']; ?></p>
<br>
<h3>Comments</h3>
<p>Some annoying user: Gr8 B8 M8</p>
<p>Annoying users friend: I R8 8/8</p>
</article>
<div>
<!--If logged in, ability to comment-->
<?php if(isset($_SESSION['login_user'])): ?>
<form role="comment-form" method="POST" action="processcomment.php" id="mainForm">
<input type="hidden" value="$threadID" name="threadID">
<div class="form-group">
<label for="comment">Comment </label> <br>
<textarea class="comment-text" name="comment" rows="2" maxlength="255"></textarea>
</div> <br>
<input type="Submit" class="btn-newcomment" value="Submit Comment" name="submit">
</form>
<?php endif ?>
</div>
</section>
<!--Right portion-->
<aside class="content-aside">
<div>
<!--If logged in, be able to create a thread-->
<?php
if(isset($_SESSION['login_user'])) {
echo"<form method=\"post\" action=\"makethread.php\">";
echo"<input type=\"submit\" class=\"btn-newthread\" value=\"Create New Thread\" name=\"submit\">";
echo"</form>";
}
?>
</div>
<!--Info-->
<div>
<p> GOING TO NEED A SEARCH FUNCTION HERE
This is the cool little aside section. It will always be there to provide you with some very nice little details, helpful links, maybe a list of moderators? who knows! The uses are endless when you have a beautiful little aside like this one! Here are a few very useful bodyweight fitness links to get us started :D </p>
</div>
<br>
<div>
<ul class="content-aside-links">
<li>
Reddit's Bodyweightfitness Forum
</li>
<li>
Reddit's Bodyweightfitness RR
</li>
<li>
Antranik's Bodyweightfitness Routine
</li>
</ul>
</div>
<div></div>
</aside>
<!--Footer -->
<footer class="footer">
<div>
<p> Use of this site constitutes acceptance of our User Agreement © 2017 BodyweightMate inc. All rights reserved. </p>
</div>
</footer>
</body>
</html>
The error is occurring under the main portion where i check if a user is logged in, and if they are add a short form consisting of a message, a text area, and a submit button. This form sends the information to the following php file.
<?php
session_start();
if(!isset($_SESSION['login_user'])) { header("location: main.php"); }
?>
<!DOCTYPE html>
<html>
<body>
<?php
require("config.php");
$connection = mysqli_connect($host, $user, $password, $database);
$error = mysqli_connect_error();
if($error != null) {
$output = "<p>Unable to connect to database!</p>";
exit($output);
} else {
//Validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$comment = $_POST['comment'];
$threadID = $_POST['threadID'];
$user = $_SESSION['login_user'];
} else {
//Redirect back to register
echo"<p>Form must use post or input was bypassed.</p>";
echo" Return to home page. ";
mysqli_close($connection);
exit();
}
There is no issue with connecting to the database, and I don't believe the remainder of the code is necessary to help me with this error since that one if statement of checking if the form is using post is failing and the else statement is always called. Why is this? i have rewritten the form multiple times ensuring that its properly structured and using post yet it fails every time!

How to fetch from MySQL database “Hindi” (Indian local language) हिन्दी text in websites [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 6 years ago.
How to fetch from MySQL database “Hindi” (Indian local language) हिन्दी text in websites
pictureofdatabase
when i fetch data from database it show
???????????????????????????????????????
????????????????????????
??????????????????????????????????????
??????????????????????????????????????
Referring to this question I have changed my database charset to "utf8_unicode_ci", but Still not working. I have written following code to fetch the data
connection.php page
<?php
$DB_HOST = 'localhost';
$DB_USER = 'xxxxxxxx_usr';
$DB_PASS = 'xxxxxxxxxxxxxxxxx';
$DB_NAME = 'xxxxxxxs_dta';
try{
$DB_con = new PDO("mysql:host={$DB_HOST};dbname={$DB_NAME}",$DB_USER,$DB_PASS);
$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}
index.php page
<?php include("../header.php"); ?><style>
.wrapper{position:relative;}
.right,.left{width:50%; position:absolute;}
.right{right:0;}
.left{left:0;}
</style> <?php
require_once 'connect.php';?>
<link href='/Lang/style.css' rel='stylesheet' type='text/css'>
<?php
$iddd =$_GET['id'];
$d = $browser_t; ?>
<div class="content">
<div class="dta">
<?php
mysqi_set_charset( $DB_con, 'utf8');
$stmt = $DB_con->prepare('SELECT id, title, post, viewers, author, external FROM getpost WHERE id =:vid');
$stmt->execute(array(':vid'=>$iddd));
$stmt->execute();
if($stmt->rowCount() > 0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
?>
<div class="list_item"><h2><?php echo $row['title']; ?> Tutorials</h2></div>
<div class="nykfont"> </div>
<?php echo $row['post']; ?>
<div class="content">
<div class="dta">
<div class="nykfont">
<div class="lis_ite"><?php echo $row['external']; ?></div>
<div class="listt_itemm">Author<h5><?php echo $row['author']; ?></h5></div></div>
<?php
}
}
else
?>
</div></div>
<hr>
<?php include("../footer.php"); ?>
This solved my same problem.
ALTER TABLE tablename
CHANGE COLUMN columnname VARCHAR(45) CHARACTER SET 'utf8' ;
hope solve yours too.

PHP Script is connecting to database but will not return a table value despite being connected.

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.2/material.indigo-pink.min.css">
<script src="https://storage.googleapis.com/code.getmdl.io/1.0.2/material.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<body>
<!-- Always shows a header, even in smaller screens. -->
<div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
<header class="mdl-layout__header">
<div class="mdl-layout__header-row">
<!-- Title -->
<span class="mdl-layout-title">Forum</span>
<!-- Add spacer, to align navigation to the right -->
<div class="mdl-layout-spacer"></div>
<!-- Navigation. We hide it in small screens. -->
<nav class="mdl-navigation mdl-layout--large-screen-only">
<a class="mdl-navigation__link" href="">Default Subforum2</a>
</nav>
</div>
</header>
<div class="mdl-layout__drawer">
<span class="mdl-layout-title">Forum</span>
<nav class="mdl-navigation">
<a class="mdl-navigation__link" href="">Browse Subforums</a>
<a class="mdl-navigation__link" href="">Search For Post</a>
</nav>
</div>
<main class="mdl-layout__content">
<div class="page-content">
<!-- Your content goes here -->
<?php
include("dbforforum.php");
$subForum = "";
$results = $mysqli->query("SELECT * FROM `SubForumList`");
echo $results;
for ($i = 0; $i < $results->num_rows; $i++)
{
$results->data_seek($i);
$row = $results->fetch_assoc();
$subForum = $row['Name'];
echo $subForum;
echo $subForum;
}
?>
</div>
</main>
</div>
</body>
</html>
I'm trying to echo HTML within PHP the row 'subForum' of my SQL table $row['subForum'] every time this loop goes through, however, for some reason it is not connecting.
Even in dbforforum.php, my database config file, it is showing that it connected successfully:
<?php
$mysqli = new mysqli("localhost", "root", "", "Forum");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
I am very, very confused by this. Any help is appreciated.
Note: I recently switched to Mac from Windows (not my choice), and have therefore gone from WAMP to MAMP. Not sure if this has to do with anything.
It should be this
In your database config
$mysqli = new mysqli("localhost", "root", "", "Forum"); //the variable here is mysqli
if ($conn->connect_error) { //the error here is $conn because it isn't the variable above so change the variable to $mysqli
die("Connection failed: " . $conn->connect_error); //and here too to $mysqli
}
echo "Connected successfully";
Changes:
$mysqli = new mysqli('localhost', 'root', '', 'databasename'); //connect db
if($mysqli->connect_errno){
die("Error! ".$mysqli->connect_errno);
}
if($result = $mysqli->query("SELECT * FROM SubForumlist")){
echo $result->num_rows //num_rows == your data you want to echo
}

WHERE not working when it should be?

before I start I have looked over the answers related but I cannot figure this out
Hello, I am trying to fetch the values with just the data from formtype = 'Question1'
the value is in the database under column formtype as Question1, it is a radio option value which is one of 3 values that I use to redirect information over to one page, so I have to do this on each page to get that specific information. My question is, why is it not selecting the values that contain Question1? it doesn't grab anything at all, but if I get rid of WHERE it grabs all the information just fine(which i only wanna grab the one containing Question1). Why is this? it isnt showing any errors with SELECT so I don't know what I did wrong.
I am connected to the database
<?php $db_name = 'submissions';
$db_user = 'root';
$db_pass = '';
$db_host = 'localhost';
mysql_connect("localhost", $db_user, $db_pass) or die(mysql_error());
mysql_select_db("submissions") or die(mysql_error());
$query1 = mysql_query("SELECT actual_quote,poster,formtype FROM data WHERE formtype = 'Question1'");
$info = mysql_fetch_array($query1);
while($info = mysql_fetch_array($query1)){
echo '
<div class="wrapper">
<div class="submissions">
<div class="logo-logo"><h2>Questions.</h2>
<div class="checkboxes">'.$info['formtype'].'
</div>
</div>
<div class="top-submit">
&#8220'. $info["actual_quote"] . '”
</div>
<div class="poster">- '. $info["poster"].'
<div class = "like">
Like
<p id = "like" style = "color:green;">0</p>
</div>
<div class = "dislike">
Dislike
<p id = "dis" style = "color:red;">0</p>
</div>
</div>
<!-- use select to get the items to stay on the page-->
</div>
</div>
</div>
';
}
?>
Any suggestions?
Fix these lines:
$link = mysql_connect("localhost", $db_user, $db_pass) or die(mysql_error());
mysql_select_db("submissions",$link) or die(mysql_error());
$query1 = mysql_query("SELECT actual_quote,poster,formtype FROM data WHERE formtype = 'Question1'",$link);
//delete this-> $info = mysql_fetch_array($query1); ?
while($info = mysql_fetch_array($query1)){

PHP use a variable from a different file

I have a login page which records the username that the user enters and adds it to a variable of $uname. However when the page after the login page loads, I cannot echo the $uname. For example, when i type
Welcome <?php echo $uname; ?>
it does not insert the username.
below is a copy of my login-validation code. but I am not sure if the $_SESSION variable is working correctly, or how to reference it in my profile.php file.
<?php
session_start();
$_SESSION['uname'] = $uname;
// Grab User submitted information
$uname = $_POST["uname"];
$pass = $_POST["pass"];
// Connect to the database
$con = mysql_connect("mysql.*********.co.uk","******","************");
// Make sure we connected succesfully
if(! $con)
{
die('Connection Failed'.mysql_error());
}
// Select the database to use
mysql_select_db("onedirectionaffection_members",$con);
$result = mysql_query("SELECT uname, pass FROM users WHERE uname = $uname");
$row = mysql_fetch_array($result);
if($row["uname"]==$uname && $row["pass"]==$pass)
header("Location: ../../profile/profile.php");
else
echo"Sorry, your credentials are not valid, Please try again.";
?>
If anyone could help I would be hugely thankful. Also, I am an absolute beginner at all of this so if you need anymore details I'll try my best to answer.
profile.php
<?php
session_start();
echo $_SESSION['uname'];
?>
<html>
<head>
<title>1D Affection</title>
<link rel="stylesheet" Type="text/css" href="../css/stylesheet.css" />
<link rel="stylesheet" Type="text/css" href="../css/font.css" />
<link rel="stylesheet" Type="text/css" href="../css/profile.css" />
</head>
<body bgcolor="white">
<div id="wrapperhead">
<div id="headcont">
<div class="logo">
<img src="../images/1DA logo ripped.png" height="150px">
</div>
<div class="subheading">
<img src="../images/1d subheading.png" height="150px">
</div>
</div>
</div> <!--END OF HEADER-->
<div id="nav">
<div class="navigation">
<ul>
<li><a class="nav" href="../index.html">Home</a></li>
<li><a class="nav" href="#">News</a></li>
<li><a class="nav" href="#">Fan-fiction</a></li>
<li><a class="nav" href="#">Gallery</a></li>
<li><a class="nav" href="#">Testimonials</a></li>
<li><a class="nav" href="http://www.onedirectionstore.com/" target="_blank">Store</a></li>
</ul>
</div> <!-- END OF MENU-->
<!-- END OF NAVIGATION-->
</div>
<div id="wrappercontent">
<div class="content">
<div class="maincont">
<div class="profcust">
<div class="profpic">
</div>
<div class="profinfo">
</div>
</div>
<div class="username">
Welcome <?php session_start(); echo $uname; ?>
</div>
<div class="story">
</div>
</div>
<div class="sidenav">
Coming Soon
</div>
</div><!--end of content-->
</div>
</body>
</html>
Seems like you haven't added session_start(); on top of your profile.php page.
Try like this
//profile.php
<?php
session_start();
echo $_SESSION['uname'];
This is probably a good part of the issue.
$_SESSION['uname'] = $uname;
$uname = $_POST["uname"];
Your setting your session's uname to blank on every load of that page. Put $_SESSION['uname'] = $uname; at the end of the code when it's validated.
1) You need to add a value to $uname first, then assign its value to $_SESSION element, so it's better be like this:
$uname = $_POST['uname'];
$_SESSION['uname'] = $uname;
or even like this:
$_SESSION['uname'] = $_POST['uname'];
2) As already mentioned, At profile.php you should also have session_start();
3) Make a clean exit like this:
header("Location: ../../profile/profile.php");
exit();
My bet is that it should be working fine after.
Some how, this is now working. From what I can figure out, the solution was to call in the $_SESSION variable, and then wrap that inside another variable. so
<?php
session_start();
$uname = $_SESSION['uname'];
?>
Thanks for all the help :D
session_start(); needs to be inside all pages using sessions.
I tested the following:
<?php
session_start(); // page_2.php
echo "Welcome " . $_SESSION['uname'];
?>
In conjunction with my test page: page_a.php
<?php
session_start();
$uname = "FRED";
$_SESSION['uname'] = $uname;
?>
CLICK
Echo'ed Welcome FRED on page 2.
I also noticed you have another instance of session_start(); in your page profile.php, remove it because you will be starting a new session while overwriting your first.
<div class="username">
Welcome <?php session_start(); echo $uname; ?>
</div>
Therefore you should be using:
$uname = $_SESSION['uname'];
in conjunction with:
<div class="username">
<?php echo "Welcome " . $_SESSION['uname']; ?>
</div>
As berkes stated in this comment you have a security issue:
$uname = $_POST["uname"];
$pass = $_POST["pass"];
Change it to:
$uname = mysql_real_escape_string($_POST['uname']);
$pass = mysql_real_escape_string($_POST['pass']);
MySQL_ functions are deprecated, therefore using MySQLi_ with prepared statements is highly suggested or PDO.
Do read the following articles:
How can I prevent SQL injection in PHP?
On owasp.org

Categories