How to echo rows values in php? - php

I am trying to echo values of each row.
I tried this... while ($row = mysqli_fetch_assoc) {...}
but it prints the last value of row each time in a specific part of the loop.
Also, I created an array an I assigned the values in the while loop but it didn't work.
Can you please help me?
$query= mysqli_query($con, "SELECT * FROM db WHERE user='$user' AND deleted='no' ORDER BY id DESC LIMIT 6");
while ($row = mysqli_fetch_assoc($query)) {
$link="index.php?id=". $row['id']; //wrong value
if ($row["user"] == 'User 1') {
$id=$row['id'];
$tags=$row['tags'];
$token = strtok($tags, ",");
echo "<div class='thisdiv'>
<a href='../games/avery/index.php?id=$id'><img src='../images/games/Preview.png ' ></a><br><p class='font-size-bold'>Tags</p>"; //correct $id

SQL Inject is allowed with your code, use statament for exclude this possible:
$query= $con->prepare("SELECT * FROM db WHERE user=? AND deleted=? ORDER BY id DESC LIMIT 6");
$no='no';
$query->bind_param('ss',$user,$no);
$query->execute();
$result=$query->get_result();
while ($row = $result->fetch_assoc()) {
if ($row["user"] == 'User 1') {
$id=$row['id'];
$tags=$row['tags'];
$token = strtok($tags, ",");
echo "<div class='thisdiv'><a href='../games/avery/index.php?id=$id'><img src='../images/games/Preview.png ' ></a><br><p class='font-size-bold'>Tags</p>"; //correct $id
}
}

Your code is quite limited but will try to break it down for you.
So first things first your query is working. And you get the 6 last results from your table since you order in DESC and LIMIT to 6
You while loop also loops around your fetched results. So your issue is more logical.
The 1st iteration of your while will set value to variable $link like:
$link="index.php?id=". $row['id'];
This will always be executed on every iteration (6 times) and actually your variable will be overwritten, so at the last iteration $link is going to have the id of the last element.
In your code after that you have a check:
if ($row["user"] == 'User 1') {
$id=$row['id'];
$tags=$row['tags'];
$token = strtok($tags, ",");
echo "<a href='../games/avery/index.php?id=$id'><img src='../images/games/Preview.png ' ></a><br><p class='font-size-bold'>Tags</p>";
} // mind the closing bracket, you echo your validated value
That's where i think you are getting it wrong. This echo should be inside your if check but also your variable link should be in there.

Related

How to store a row into an array in PHP and echo out a certain value of the array?

I'm trying to query data from a row in a table, store the data into an array, and then echo out a certain value from the array. Here's the PHP:
$receiveuserdata = mysqli_query($connection, "SELECT * FROM s_users LIMIT 0,1");
$userdata = array();
$index = 0;
while ($row = mysqli_fetch_assoc($receiveuserdata)) {
$userdata[$index] = $row;
$index++;
};
I've tried using other posts related to this issue for help, but most are outdated. Here's my attempt to echo a value from the array:
<h3>Username: <?php echo $userdata[0]; ?></h3>
Am I using $receiveuserdata incorrectly?
To retrieve Single row
You are used to LIMIT 0,1 - so it will retrieve only one row
<?php
$receiveuserdata = mysqli_query($connection, "SELECT * FROM s_users LIMIT 0,1");
if (mysqli_num_rows($receiveuserdata) > 0)
{
$row = mysqli_fetch_assoc($receiveuserdata);
$username = $row['username'];
echo '<h3>Username: '.$username.'</h3>';
}
?>
To retrive multiple rows
<?php
$receiveuserdata = mysqli_query($connection, "SELECT * FROM s_users");
if (mysqli_num_rows($receiveuserdata) > 0)
{
while ($row = mysqli_fetch_assoc($receiveuserdata)) {
$username = $row['username'];
echo '<h3>Username: '.$username.'</h3>';
}
}
?>
$row contains the entire MySQL table row. Which means that $userdata[0] also contains a row (as an associative array). Using echo does not work with arrays. Instead you can use var_dump if you want to see what the row is or access the value you need directly: $userdata[0]['username'] (if you have a column name username)

Compare rows in PHP

Hi I would like to compare two tables from two different databases.
Select from the first database
$sql= mysqli_query ("SELECT * FROM emasa.staff_detail");
$row = mysqli_fetch_array($sql);
Select from the second database
$sql2 = mysqli_query ("SELECT * FROM employee");
$row2 = mysqli_fetch_array($sql2);
Then I compare the two table
if ($row['icnum'] == $row2['emp_ic'])
{
echo "Data already exist in both database.";
}
else
{
while ($row = mysqli_fetch_assoc($sql))
{
echo "<td align='center' height='30'>" . $row ['name'] . "</td>";
echo "<td align='center'>" .$row['icnum'] . "</td>";
}
}
But my problem is it only compares the first row in the database.
My output should only display the staff name that is not available in the other database. However, this is my output.
Based on the output it only compares the first row. So how do I change my code so that it compares the whole row. Please help me, thank you!
You're not looping through the results of the query. You're simply getting back the first row and going with that.
Ex:
$sql= mysqli_query ("SELECT * FROM emasa.staff_detail");
This is returning a result set which you then need to use
$row = mysqli_fetch_array($sql);
to get the actual values. The problem comes when
$row = mysqli_fetch_array($sql);
by itself only gives you one row.
Solution 1
You must use code like this:
while($row = mysqli_fetch_array($sql))
{
//Do some comparison
}
Since you're going to have to loop through two different result sets, you're going to have to do a loop within a loop, build an array of results and then loop through the results afterwards to output your HTML.
Ex:
while($row = mysqli_fetch_array($sql))
{
while($row2 = mysqli_fetch_array($sql2))
{
if ($row['icnum'] == $row2['emp_ic'])
{
//add to array of equal data
}
else
{
//add to array of not equal data
}
}
}
foreach($array as $not_equal_or_equal_data)
{
//output your desired HTML
}
Solution 2
Depending on what you actually care about, you could do a sql statement like this
$sql = "
SELECT
*
FROM
emasa.staff_detail AS sd
JOIN db2.employee AS e
ON sd.icnum = e.emp_ic";
This would return all the rows where those two columns were equal

Printing a MySQL query in PHP

function MattsScript()
{
$query = 'SELECT * FROM `ACCOUNTING` WHERE `ACCTSTATUSTYPE` = "start" AND `Process_status` IS NULL LIMIT 0,100';
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
while ($row = mysql_fetch_assoc($result))
{
echo $row['USERNAME'] . "<br />";
echo $row['ACCTSTATUSTYPE'];
}
}
I am trying to echo the results of a query. What I think is happening here is I am saving a query to a variable, the first 100 results (LIMIT 0,100) then using a loop to echo each row to the page.
However nothing is happening, no error and nothing written to the page.
Is there something I am missing?
if you are expecting only one result remove the while loop if not leave the while loop and remove the line $row = mysql_fetch_assoc($result); before the while loop. Also make sure you are querying your database correctly.
Example: $result = mysql_query($query) or die(mysql_error());

Query Result: What is $row[0]

I know this may sound like a stupid question from a programming-newbie, but I just want to make sure I understand correctly.
After a query, what does $row[0] stand for/ result in?
Is my understanding correct that $row[0] shows ALL results?
HERE ARE EXAMPLES:
$query = "SELECT count(commentid) from comments where jokeid = $jokeid";
$result = mysql_query($query);
$row=mysql_fetch_array($result);
if ($row[0] == 0)
{
echo "No comments posted yet. \n";
} else
{
echo $row[0] . "\n";
echo " comments posted. \n";
AND THIS ONE
$query = "Select count(prodid) from products where catid = $catid";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if ($row[0] == 0)
{
echo "<h2><br>Sorry, there are no products in this category</h2>\n";
}
else
{
$totrecords = $row[0];
Thanks in advance.
$row[0] will simply echo the first column in your database.
0 is the first because all arrays in PHP (and in most programming languages) are zero-based - they simply start with zero.
$row[0] will be the value of the first column in your results. If you use mysql_fetch_assoc($result) you will have an array in the form:
array(column_name => column_value);
e.g.
$row = mysql_fetch_asssoc($result);
$value_column_1 = $row['column_1'];
You can also use mysql_fetch_object($result) to get an object with column names as the parameters.
$row = mysql_fetch_object($result);
$value = $row->column_name
mysql_fetch_array() takes the next (in your examples first) row out of the resultset and stores the data in an array $row.
$row[0] now represents the first value of that row.
So in total in your examples the variable holds the first value of the first row of your resultset.

MYSQL - Select specific value from a fetched array

I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.
I have got a very simple database and I am getting all rows by this:
while($row = mysql_fetch_array($result)){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:
$name2= $row['name'][2];
Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?
What I am trying to is following:
-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.
If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:
$row = array();
while( $row[] = mysql_fetch_array( $result ) );
Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].
$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
if($row['id'] == 2){
/*You can filtere here*/
}
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
if($counter == 2){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
}
This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.
Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:
$count = 0;
while($row = mysql_fetch_array($result)){
if(++$count == 2)
{
//do stuff
}
}
Yes, ideally you have to write another sql query to filter your results. If you had :
SELECT * FROM Employes
then you can filter it with :
SELECT * FROM Employes WHERE Name="Paul";
if you want every names that start with a P, you can achieve this with :
SELECT * FROM Employes WHERE Name LIKE "P%";
The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.
If you want to be able to use 2 consecutive results in one loop, you can store the results of the first loop, and then loop through.
$initial = true;
$storedId = '';
while($row = mysql_fetch_array($result)) {
$storedId = $row['id'];
if($initial) {
$initial = false;
continue;
}
echo $storedId . $row['name'];
}
This only works for consecutive things though.Please excuse the syntax errors, i haven't programmed in PHP for a very long time...
If you always want the second row, no matter how many rows you have in the database you should modify your query thus:
SELECT * FROM theTable LIMIT 1, 1;
See: http://dev.mysql.com/doc/refman/5.5/en/select.html
I used the code from the answer and slightly modified it. Thought I would share.
$result = mysql_query( "SELECT name FROM category;", db_connect() );
$myrow = array();
while ($myrow[] = mysql_fetch_array( $result, MYSQLI_ASSOC )) {}
$num = mysql_num_rows($result);
Example usage
echo "You're viewing " . $myrow[$view_cat]['name'] . "from a total of " . $num;

Categories