My php While loop run the query, but the results must be print inside html. In this moment I unknow the way to make this:
My php while loop
<?php
include "connect.php";
$username=$_SESSION['Username'];
$result = mysqli_query($dbconn,"
SELECT *
FROM books
WHERE username = '$Username'
");
while($rows = mysqli_fetch_array($result));
?>
After this code there is a Html code where I want print the variables:
Edit
In this moment the variable is empty
How to fix this?
[Resolved] Update
I have resolve my problem. This is the correct php script. Work fine:
<?php
include "connect.php";
$username=$_SESSION['Username'];
$result = mysqli_query($dbconn,"
SELECT *
FROM books
WHERE username = '$Username'
");
global $book_id, $book_name
while($row = mysqli_fetch_array($result)) {
$book_id = row['book_id'];
$book_name = row['book_name'];
?>
Outside while loop. Print variable inside Html:
<?php echo $row['book_id']; ?> <br>
<?php echo $row['book_name']; ?>
Close while loop and connection:
<?php
}
mysqli_close($dbconn);
?>
with prepared statements :
<?php
session_start();
$username = $_SESSION['Username'];
error_reporting(E_ALL);
ini_set('display_errors', 1);
include"config.inc.php";
/* connect to DB */
$mysqli = mysqli_connect("$host", "$user", "$mdp", "$db");
if (mysqli_connect_errno()) { echo "Error connecting : " . mysqli_connect_error($mysqli); }
$query = " SELECT * FROM books WHERE username=? ";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $username);
$results = $stmt->execute();
$stmt->bind_result($book_id, $book_name);
$stmt->store_result();
if ($stmt->num_rows > 0) {
while($stmt->fetch()){
?>
<p><?php echo"$book_name"; ?> > Edit</p>
<?php
}
}
else
{ echo"[ no data ]"; }
?>
(Rewriting)
The real issue is:
while ($rows = ...) ;
This loops until $rows is NULL. So there is nothing to display afterwards.
Since you are fetching the entire array in a single function call, there is no need for the loop!
$rows = ...;
But then you need to reference the first(?) row to get the desired data:
$row = $rows[0];
So, another approach is to just fetch one row, then close the fetch process.
In your html you have to do this
Edit
As there might be multiple books for each user, you have to print the link inside the while loop, or store it in a string:
<?php
include "connect.php";
$username = $_SESSION['Username'];
$result = mysqli_query($dbconn,"
SELECT * FROM books
WHERE username = '$Username'
");
$links = ""; // all links are stored in this string
while($rows = mysqli_fetch_array($result)) {
// I assume that the columns are called `id` and `name`
$links .= 'Edit '. $rows["name"] .'';
}
?>
In the html code simply write
<?php echo $links ?>
Note that you should use prepared statements instead. You should also take a look at the object oriented way to use mysqli using the mysqli class.
Related
I'm creating a news website, and want to create a dynamic PHP page that will have the header and footer, and get the content itself (title and text) from the database by calling the article's id via the URL(like 'article.php?id=1'), so that there is no need for creating a new file for each article. However, I don't know what function should I use to make that work. Currently, the code is like this:
<?php
include "header.php";
$query = "SELECT title_article, subtitle_article, content_article FROM tb_article WHERE id_tb_article = 1";
$conn = mysqli_connect('127.0.0.1:3307', 'root', '', 'article') or die("error");
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<div class='titlediv'><h1 class='title'>" . $row["title_article"]. "</h1></div><div class='titlediv'><h3 class='title'>". $row["subtitle_article"]. "</h3></div><div class='textdiv'><p class='text'>" . $row["content_article"]. "</p></div><br>";
}
} else {
echo "Article not found";
}
include "footer.php";
?>
To get the id value from query string in URL, you can use the PHP's superglobal $_GET['id'].
To select a dynamic value from SQL using this value you must use prepared statements with parameter binding.
Your code with all the fixes would look more or less like this:
<?php
include "header.php";
$query = "SELECT title_article, subtitle_article, content_article FROM tb_article WHERE id_tb_article = 1";
// Enable mysqli error reporting and NEVER die()
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli('127.0.0.1:3307', 'root', '', 'article');
$conn->set_charset('utf8mb4'); // You should always specify the correct charset, which most of the time should be utf8mb4
// prepare -> bind -> execute -> get result
$stmt = $conn->prepare('SELECT title_article, subtitle_article, content_article
FROM tb_article
WHERE id_tb_article = ? ');
$stmt->bind_param('i', $_GET['id']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows) {
// output data of each row
foreach ($result as $row) {
echo "<div class='titlediv'><h1 class='title'>" . htmlspecialchars($row["title_article"]). "</h1></div>";
echo "<div class='titlediv'><h3 class='title'>". htmlspecialchars($row["subtitle_article"]). "</h3></div>";
echo "<div class='textdiv'><p class='text'>" . htmlspecialchars($row["content_article"]). "</p></div><br>";
}
} else {
echo "Article not found";
}
include "footer.php";
Whenever output values into HTML context always do it via htmlspecialchars
You can use a GET method and the url look like 'article.php?id=2'.
<?php
include "header.php";
//use GET to get the id
$id = $_GET["id"];
// use .$id to concat to the query
$query = "SELECT title_article, subtitle_article, content_article FROM tb_article WHERE id_tb_article = ".$id;
$conn = mysqli_connect('127.0.0.1:3307', 'root', '', 'article') or die("error");
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<div class='titlediv'><h1 class='title'>" . $row["title_article"]. "</h1></div><div class='titlediv'><h3 class='title'>". $row["subtitle_article"]. "</h3></div><div class='textdiv'><p class='text'>" . $row["content_article"]. "</p></div><br>";
}
} else {
echo "Article not found";
}
include "footer.php";
?>
You want to look at the global variables $_GET and $_POST. In your example ('article.php?id=1') you will find the value of 'id' in $_GET['id'].
URL: article.php?id=42
echo $_GET['id']; // Outputs 42
Remember that anyone can change that value in the URL and even injecting malicious queries into your query. Its better to at least cast your id to an integer first and use always mysqli_real_escape_string() for URL given variables in the query.
URL: article.php?id=42;DROP TABLE tb_article
echo $_GET['id']; // Outputs "42;DROP TABLE tb_article", would delete your table when used directly
// Convert to an integer value
$id = intval($_GET['id']); // Returns 42
$query = "... FROM tb_article WHERE id_tb_article = ".mysqli_real_escape_string($id);
I'm trying to get data from mysql and show them using while loop. But problem is inside while loop there is always one less data i'm getting.
Suppose there is two row in my db , but using this code i'm getting only one row. First row always missing. Cant figure out why ! Sharing some of the code.
tried var_dump() , it shows there is right number rows in db
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id");
echo mysql_error();
$data = mysql_fetch_array($ddaa);
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
You are fetching one row before using while loop which you are not using anywhere, thats why you are loosing one row.
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id") or die(mysql_error());
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
Try to remove this line:
$data = mysql_fetch_array($ddaa);
The server and database credentials are missing in your code try this one
$server = 'server_name';
$user = 'server_username';
$pass = 'server_password';
$db = 'database_name';
$connection = new mysqli($server, $user, $pass, $db);
$aa = "SELECT * FROM coupons ORDER BY id";
$dd = mysqli_query($connection,$aa); // $connection is the variable which contains server and database credentials;
while ($data = mysqli_fetch_assoc($dd)) {
echo $data['id'];
}
It Will Work For Me. Try This...
<?php
$con=mysql_connect('localhost','root','') or die("could not connect".mysql_error());
mysql_select_db('dbname');
$query = mysql_query("SELECT * FROM Student");
$num_rows = mysql_num_rows($query);
while($row = mysql_fetch_array($query))
{
echo $row['firstname'];
}
echo "<h3>Record Selected successfully\n</h3>";
mysql_close($con);
?>
I am building a site, and essentially what this PHP algorithm will do is look at a product (row in MySQL database) one at a time, and do a process accordingly.
I put a lot of research into this but couldn't find anything, any help would be greatly appreciated!
My Code (currently returning nothing for echo variables):
<?php
include_once 'dbconnect.php';
$query = "SELECT * FROM track";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$pro_code = mysql_result(mysql_fetch_array(mysql_query('SELECT product_code FROM track')));
$currency = mysql_fetch_array(mysql_query('SELECT currency FROM track'));
$cc = mysql_fetch_array(mysql_query('SELECT cctld FROM track'));
$initial_price = mysql_fetch_array(mysql_query('SELECT initial_price FROM track'));
$url = 'test';
}
echo $pro_code;
echo $currency;
echo $initial_price;
?>
First of all, try the advice about PDO and stuff from Jay Blanchard some day.
Secondly I've tried to answer your question anyway and I've tried to interpret your complete intention. I put comments in the code:
<?php
include_once 'dbconnect.php';
$query = "SELECT * FROM track";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
//You need to read the row variable as an array
$pro_code = $row['product_code'];
$currency = $row['currency'];
$cc = $row['cctld'];
$initial_price = $row['initial_price'];
//$url is not used.. I asume a test to get the external source ;-)
$url = 'test';
if ($url == $cc) {
//if you want to print every row, you must echo inside the while loop
echo $pro_code;
echo $currency;
echo $initial_price;
} elseif ($url == 'test') {
//do something else here
} else {
//do something for all the other cases here
}//end if
}//end while
?>
Why do you query the same table multiple times, your code should be written like this:
include_once 'dbconnect.php';
$query = "SELECT product_code, currency, cctld, initial_price FROM track";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
echo $row['product_code'];
echo $row['currency'];
echo $row['cctld'];
echo $row['initial_price'];
}
and please upgrade to mysqli or PDO
i'm a newbie to php still.
I'm using phpmyadmin as my database. I have a table called 'lessonno' and a column named 'lesson' in it. I tried using this code to retrieve out the number inside 'lesson'. But it's not printing out anything. Can someone help?
<?php
$server = 'localhost';
$username = '';
$password = '';
$database = 'project';
mysql_connect($server,$username,$password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
$sql = "SELECT 'lesson' FROM 'lessonno'";
$lesson = $_POST['lesson'];
$result = mysql_query($sql);
?>
<?php
for($i = 1; $i <= $lesson; $i++) {
echo "<div>
<span>Lesson ".$i."</span>
</div>
<br>";
}
?>
You can use something like this:
$sql = "SELECT lesson FROM lessonno";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo $row['lesson'];
}
If you would like to only print out a specific lesson with an certan ID, you can use something along the lines:
$id = $_GET['lessonid']; // If you would have something like index.php?lessonid=36 and you'd like it to only fetch the data for the lesson with the id of 36.
$sql = "SELECT lesson FROM lessonno WHERE id='$id'";
(by looking at the $_POST['lesson'] part, I suppose that's something you might be trying to do as it's in the for loop as well)
Also, I suggest you use mysqli.
And, this:
echo "<div>
<span>Lesson ".$i."</span>
</div>
<br>";
Will just echo the $i as both lesson= and the span with Lesson, which won't grab any information from the actual database but just go with the current number it's at, from the for loop you have.
i have made some changes in your code try this
<?php
$server = 'localhost';
$username = 'root';
$password = '';
$database = 'project';
$conn = mysql_connect($server,$username,$password) or die(mysql_error());
mysql_select_db($database, $conn) or die(mysql_error());
$sql = "SELECT `lesson` FROM `lessonno`";
$lesson = $_POST['lesson'];
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
$lesson_no = $row['lesson'];
echo "<div>
<span>Lesson ".$lesson_no."</span>
</div>
<br>";
}
?>
Note : mysql_* is deprecated. use mysqli_* OR PDO
For getting Values from DB you need to use something like this
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
For further reference please visit http://in2.php.net/manual/en/function.mysql-fetch-assoc.php
For counting the number of data in your database, just insert this code
$sql = "SELECT 'lesson' FROM 'lessonno'";
$lesson = $_POST['lesson'];
$result = mysql_query($sql);
$count=mysql_num_rows($result);//this will count the number of rows in your table.
echo "<div>
<span>Lesson ".$count."</span>
</div>
<br>";
I have seen the opencart function which can be used outside with html like
<?php
foreach ($categories as $category){
echo $category['image'];
}
?>
i would like to make a function like that in php which i can grab data from database and use it outside. may be it's an array so foreach statement is working on it.
like i have name and age in my database i would like to use it like this
<?php
foreach($peoples as $people){
echo $people['name'];
echo $people['age'];
}
?>
Thanks in advance
As Aman Chhabra mentioned, you must first fetch the result from database and then you can use foreach loop to iterate over it.
One thing I would like to mention is DON'T use mysql_query() as use of it is discouraged as per the new guidelines of php development (Check: http://ca1.php.net/manual/en/function.mysql-query.php). To have a compatible code with advanced php use mysqli_query() instead.
Following is the code example utilizing mysqli class. This is procedural way but you can use it in OOP style as well.
//Connect to database
$host = "localhost"; //Change according to yours
$username = "root"; //Change according to yours
$password = ""; //Change according to yours
$database = "test"; //Change according to yours
$con = mysqli_connect($host,$username,$password,$database); //Create the connection
if(!$con)
{
echo "Not connected";
}
else
{
echo "Connected<br />";
}
//Prepare the query to fetch the database records
$query = "select * from TableName"; //Replace the table name with yours
$sql = mysqli_query($con,$query); //Execute the query
while($result = mysqli_fetch_assoc($sql)) //Loop through, till there are records corresponding to the query
{
$rows[] = $result; //Store all the records in an array
}
//Now iterate over each property using foreach loop
foreach($rows as $row)
{
echo "Name - ".$row['name']." Age - ".$row['age']."<br />";
}
Opencart modifies it to the array of results and the use it using foreach
You need to do it like this
$result = mysql_query($con,"SELECT * FROM Persons");
while($row = mysql_fetch_array($result))
{
$data[] = $result;
}
And then later you can use it like this
foreach($data as $row)
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}