MySQL PHP use query result more that once in HTML - php

I have an query that shows data from db. I use while loop to display data. Problem is that I can call (echo) result only once.
Here is my code:
$ime_ = "SELECT * FROM `users` WHERE '" . ($_COOKIE['username']) . "' = user_username";
$ime_result = $mysqli->query($ime_);
and later in my html I use this result as:
<?php
if ($ime_result->num_rows > 0)
while($row = $ime_result->fetch_assoc()) {
echo "<h2>" . $row["Ime"] . "</h2>";
}
?>
This work ok, but I want to use this result to display many times in my html. And when copy while loop again later in html no result is given.

Store the string with data from while() into a variable, than apply echo to that variable as many times as you like..
$re_out ='';
if($ime_result->num_rows > 0){
while($row = $ime_result->fetch_assoc()) {
$re_out .="<h2>". $row["Ime"] ."</h2>";
}
}
echo $re_out;
//etc..
echo $re_out;

<?php
if ($ime_result->num_rows > 0)
$ime_result->data_seek(0); // seek to row no. 1
while($row = $ime_result->fetch_assoc()) {
echo "<h2>" . $row["Ime"] . "</h2>";
}
?>
Haven't run script. Try if it works.

Related

Fill options with function using mysql in php

I'm trying to fill in the different options on a form calling objects from a database using a different php file. Here is my code:
PHP Code (functions.php):
<?php /* Gets values from sql and inserts into html options values */
function selectOptions($column, $table){
// fetch records
$sql = "SELECT" . $column. "FROM" . $table. "ORDER BY Id";
$result = $conn->query($sql);
//check there are more than 0 rows
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option>' .$row['$column']. '</option>';
}
}
else {
echo '<option>No results!</option>'; } } ?>
HTML code:
<?php
require "php/dbconnect.php";
require "php/functions.php";
?>
<select class="form-control">
<option>SUBJECT</option>
<?php
selectOptions("Subjects", "general_subjects");
?>
</select>
I use this function multiple times for different forms, so I figured having it in its own file would be the best approach but it does not work. When I use the function without variables inside the index.php file, it seems to work. I don't know what I am doing wrong
EDIT: Image of what it should be doing Image of index.php
Add spaces to your sql query. Also you need to access the $column variable properly. You shouldn't wrap it around single quotes as it is a variable. You also have a variable scope issue as $conn does not exist
function selectOptions($conn, $column, $table) {
// fetch records
$sql = "SELECT `" . $column . "` FROM `" . $table . "` ORDER BY Id"; #add spaces
$result = $conn->query($sql);
//check there are more than 0 rows
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option>' . $row[$column] . '</option>'; #remove single quotes
}
} else {
echo '<option>No results!</option>';
}
}
When you call the above function, add the echo keyword
<?php
echo selectOptions($conn, "Subjects", "general_subjects"); #echo the function
?>
Would you try editing your function.php sql part like this
$sql = "SELECT " . $column. " FROM " . $table. " ORDER BY Id";
i think the spaces is the reason that it's not returning data

Nested while doesn't work in PHP

I have problem with my code.
I use nested while in my code and the nested while doesn't work, only the outer while is work
I don't know where is the bug of my code.
This is the piece of my code :
$database = new mysqli('127.0.0.1', 'user', 'user', 'mini_email');
$query = 'SELECT * FROM mails';
$query2 = 'SELECT * FROM users';
$result_set = $database->query($query);
$result2 = $database->query($query2);
while ($row2 = $result2->fetch_assoc()) {
if ($row2['username'] == $_SESSION['user']) {
$id_email = $row2['id'];
}
}
if (isset($_SESSION['is_logged_in'])) {
echo('<center><font size="10">Mailing List</font></center><br><br>');
echo('<center><table border="3" bgcolor="#f0cdfa">');
echo('<tr>');
echo ('<td>No</td>');
echo ('<td>ID</td>');
echo ('<td>From</td>');
echo('<td>Subject</td>');
echo ('<td>Message</td>');
echo ('<td>Action</td>');
echo ('</tr>');
$i = 1;
while ($row = $result_set->fetch_assoc()) {
if ($row['to_user_id'] == $id_email) {
echo('<tr>');
echo ('<td>' . $i . '</td>');
echo ('<td>' . $row['id'] . '</td>');
while($row2 = $result2->fetch_assoc()){
if($row2['id']== $row['from_user_id']){
echo ('<td>' . $row2['username'] . '</td>');
}
}
echo ('<td>' . $row['subject'] . '</td>');
echo ('<td>' . $row['message'] . '</td>');
echo ('<td>View</td>');
echo ('</tr>');
$i++;
}
}
Your initial
while ($row2 = $result2->fetch_assoc()) {
is looping through all the records to the end of the set,
so looping a second time won't retrieve any further records because you're already at the end of the resultset
Resultset pointers aren't automatically reset when you initiate a new loop, but you can reset them manually using
$result2->data_seek(0);
before each subsequent loop
But iterating the point made in the comments by #Sirko you'd be better using a JOIN to make a single query
If I may help, I think you shouldn't even perform the queries when your if statement with the session returns false.
In the first lines or your script you should define a function with all this code, and write it like this :
function YourFunction()
{
if (isset($_SESSION['is_logged_in'])) {
return false;
}
// Database connection and queries
// your business
}
This will be more clean.
Next, your query doesn't seem to be correct. You get all the mails of your website, and then in a loop you check if the mail user id is the user id you have in session. Imagine the lack of performance if you have 35 000 mails in your database.
Improve your query with a WHERE statement : http://www.w3schools.com/sql/sql_where.asp
then, are you sure that $_SESSION['user'] contains an id ? I think your second if statement never returns true because of that.

Passing a value through URL

Here is what i want to achieve ; sending ID's through URL's and printing it.
index.html
ID 1
ID 2
receive.php
<?php
$id_q = $_GET['id'];
print "The parameters passed through URL are $id_q";
?>
This above code works perfectly, I'm not able to do this with a list of ID's printed with a php command.
The below code is used to print all the PID's in the DB.How do i make every PID printed clickable ?
When I add html tags inside PHP code it throws up an error.
print.php
$result = mysqli_query($con,"SELECT * FROM List");
while($row = mysqli_fetch_array($result))
{
echo $row['PID'];
}
edit-query.php
$pid_q=$_GET[pid];
echo $pid_q;
while($row = mysqli_fetch_array($result))
{
echo "<a href='receive.php?id=".$row['PID']."'>".$row['PID']."</a>";
}
If you want to add your own text to a variable or echo, quote it and separate the variable with a "."
echo ''.$row['PID'].'';
you should do that like this
How about...
echo '' . $row['PID'] . '';
I believe this is what you mean?
while($row = mysqli_fetch_array($result))
{
echo 'Print ID: ' . $row['PID'] . '';
}
while($row = mysqli_fetch_array($result))
{
echo "<p id=".$row['PID']." class='clickable'>" . $row['PID'] . "</p>";
}
$(document).ready(function(){
$("#clickable").click(function(){
$(this)...something...
});
});
This is a little something you can do using JQuery if you wanted each PID to do something other than refer to another location. It will listen on any with the clickable class.

How to loop the $row = mysql_fetch_array($rs);

I have a table
Now.i have a function in my JS
function add()
{
<?php
include('conn.php');
$rs = mysql_query("select * from position");
$row = mysql_fetch_array($rs);
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo "add2()";
?>}
function add2(){
AddAddress("<?php echo $ss;?>","<?php echo $sss;?>/<?php echo $ssss;?><br /><?php echo $sssss;?>/<?php echo $ssssss;?>");
}
How to get the every date from my table?
Something like this?
function add() {
<?php
include('conn.php');
$rs = mysql_query("select * from position");
while ( $row = mysql_fetch_array($rs) ) {
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo 'AddAddress("' . $ss . '","' . $sss . '/' . $ssss . '<br />' . $sssss . '/' . $ssssss . '");';
}
?>
}
Didn't text the echo 'AddAddress....' line so I hop eI got all the single and double quotes in the right place??
Performing POST requests using Ajax here is an example of sending data from js to php.
also stop naming your vars s,ss,sss,ssss you will have no idea what they mean when you read your code tomorrow..
and try not to use mysql_* functions they have been deprecated switch to mysqli or pdo
I got what would you like to do. In your PHP file:
function add(){
<?php
include('conn.php');
$rs = mysql_query("select * from position");
echo "var data = [] ; "
while($row = mysql_fetch_assoc($rs)){
echo "
data.push({
name: '{$row['Name']}',
nowb: '{$row['nowb']}',
totalb: '{$row['totalb']}',
nowc: '{$row['nowc']}',
totalc: '{$row['totalc']}'
}); \n\r " ;
}
?>
add2(data);
}
function add2(data){
for (var i in data){
var row = data[i] ;
AddAddress(row.name, row.nowb, row.totalb, row.nowc, row.totalc);
}
}
If I understand the question correctly you want to know how to loop through an array in php.
$row = mysql_fetch_array($rs);
foreach($row as $value){
//Do something
}
Read up on it in the docs
http://php.net/manual/en/control-structures.foreach.php

PHP not be able to echo data [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP not be able to echo data
I'm trying to get data from database, and echo them on the page using their unique id.. below is my code
<?php
session_start();
require_once('config.php');
//create query statement
$query = 'SELECT * FROM player_info';
//make the query from db
$myData = mysql_query($query, $conn)
OR exit('Unable to select data from table');
while($row = mysql_fetch_array($myData, MYSQL_ASSOC)){
$playerID = $row['id'];
$player_bio = $row['player_bio'];
$achievements = $row['player_achts'];
}
?>
and here is how i code for echo the data
<?php
if ($playerID == 1)
{
echo '<p class="playerAchievesL">' . $achievements . '</p><p class="playerInfoL">' . $player_bio . '</p>';
}
?>
I don't get any error return from php, but the data does not display anything... help please ... thank you so much
If I understand correctly, you need to place the echo inside the while() loop:
while($row = mysql_fetch_array($myData, MYSQL_ASSOC)){
$playerID = $row['id'];
$player_bio = $row['player_bio'];
$achievements = $row['player_achts'];
echo '<p class="playerAchievesL">' . $achievements . '</p><p class="playerInfoL">' . $player_bio . '</p>';
}
You fetch all players from the table, and for each player, overwrite $playerID, $player_bio and $achievements. After the while loop, $playerID contains the identifier of the last fetched player.
If you have more than one player, this most likely is not $playerID with 1.
problem is in here. you're overwriting the values on every iteration
while($row = mysql_fetch_array($myData, MYSQL_ASSOC)){
$playerID = $row['id'];
$player_bio = $row['player_bio'];
$achievements = $row['player_achts'];
}
Just echo them directly in the loop:
while($row = mysql_fetch_array($myData, MYSQL_ASSOC)){
echo $row['id'];
echo $row['player_bio'];
echo $row['player_achts'];
}
Your while loop may be overwriting $pkayerID, so if the last playerID isn't 1 the it won't echo anything.
Try putting the echo line after the $achievemets line to see if this is the case.

Categories