Retrieve rows from table to str_replace - php

I'm having trouble taking data from a table and using it to replace strings in html text. I need to retrieve the last 4 rows from the table, then using str_replace, automatically create hrefs. So one column is url, one is title, one is description, etc. Then I'll create 4 separate hrefs from each row. What I have so far will work for only the last result. How do I make it work for all 4?
$query = "SELECT * FROM LINKS ORDER BY id DESC LIMIT 4";
if(!$result = mysql_query($query)){
// query failed, handle the error here...
$errors[] = "A fatal error occurred and this page is non-functional at this time!";
trigger_error("Query failed: $query<br /> Due to: " . mysql_error()); // application error
} else {
// query worked
if(!mysql_num_rows($result)){
// no matching rows
$main_content .= "No rows were found!\n";
} else {
// query matched at least one row, use the results from the query here...
$row = mysql_fetch_assoc($result);
$title1 .= $row['title'];
$link1 .= $row['url'];
}
}
//string replace arrays
$placeholders = array('LINK1','LINK2', 'LINK3','LINK4');
$replacevals = array($link1, $link2, $link3, $link4);
//replace the areas of the template with the posted values
$page = str_replace($placeholders,$replacevals,$template);
I'd like to be able to output $title2, $link2, $title3, etc.

Easiest way to do so would be to do something like this:
...
// query worked
if(!mysql_num_rows($result)){
// no matching rows
$main_content .= "No rows were found!\n";
}
else {
$urls_array = Array();
// query matched at least one row, use the results from the query here...
while ($row = mysql_fetch_assoc($result))
{
$urls_array[] = "<a href='" . $row['url'] . "'>" . $row['title'] . "</a>";
}
}
Then you end up with an array of html links set to the $urls_array variable.

Use a loop with mysql_fetch_assoc(). Traditionally, a while loop.
Here's an example derived from the PHP docs:
while ($row = mysql_fetch_assoc($result)) {
echo $row['title'];
}
That should get you started. Welcome to StackOverflow.

Related

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

How do I compare array value to the next value in array

I am wanting to compare the next value in the array with my current value. If you look at my code I think you will see what I am trying to do but to explain I need only one picture to show if $row[2] is the same on the next loop thru.
My error start at // ERROR HERE in if Statement in the code below.
I am sure there is a simple solution to this but I don't know the proper name and could not find it in my searches.
-Disclaimer I am still an newbie at this please forgive me.
$connection = mysqli_connect($host, $user, $pass, $db);
if (mysqli_connect_errno($connection)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// create query
$query = "SELECT * FROM 1098";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_row($result)) {
echo "<center>";
// ERROR HERE in if Statement
$nextrow = 1 + $row;
if ( $row[2] <> $nextrow[2]){
if ( $row[6] == "kit"){
$img ='<img style="width: 700px; height: 800px;" alt="Picture Not Found" src=" ';
$file = substr($row[2], -3);
$filepath='files/'.$row[6].'/'.$file.'_files/image001.png">';
echo $img.$filepath;
}
else
{
$img ='<img style="width: 700px; height: 280px;" alt="Picture Not Found" src=" ';
$filepath='files/'.$row[6].'/'.$row[2].'_files/image001.png">';
echo $img.$filepath ;
}
}
echo "</center>";
}
}
$nextrow = 1 + $row doesn't make sense. That would be attempting to add an integer to a database record, i.e. 1 + array('foo', 'bar', 'baz').
If you simply want to compare the current record with the previous record (on all loops after the first one) how about something like this:
while($row = mysqli_fetch_row($result)) {
print '<center>';
// If there is no previous record set (first record) or if the 2nd value is different.
if (!isset($prev_record) || $prev_record[2] != $row[2]) {
// ...
}
print '</center>';
// Assign the current row to a variable so that it's available on the next run.
$prev_record = $row;
}
Edit – here's an example of how you can get all records into a single array and then play with them:
$records = array();
while($row = mysqli_fetch_row($result)) {
$records[] = $row;
}
foreach ($records as $i => $record) {
$record; // current record
$records[$i-1]; // last record
$records[$i+1]; // next record
}
I would recommend splitting your data up into multiple tables, though, and using a cleaner approach.
$nextrow = 1 + $row;
Given $row is a row, this is not doing what you think it is.
If you want the nextrow from the query you have to fetch it.
If you can reverse your logic to use previous row , you could preserve that and compare it to the current row.
You could read them all into an array first, but on a big result set that would be expensive....
You could do two fetches, one to current row, one to next row,
And then add a lot of logic to deal with the first and last, and making current = next and fetching the next next :(
Or you could rework the query so it returned the data you need in one row.
You definitely can't do what you are trying to do though. There is no next row until you fetch. $row is an array of columns, there is no rows as in an array of rows.

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;

MYSQL SELECT statement with variable based on PHP for loop

Currently, $selection outputs the following: MIN(Bale_ID), MIN(Incoming_Moisture) which is exactly what it should be outputting (they're names from another table). However, when I put $selection into the mysql_query $data1, it seems to just be reading the last value (MIN(Incoming_Moisture)) and only displays the results for that. How do I get the query to read the entire array of elements in $selection? Thank you!!
while ($row1 = mysql_fetch_array($fieldnames1)) {
$fields = $row1['fields1'];
$explode = explode(',',$fields);
if ($row1) {
for ($i=0; $i<$minrows; $i++) {
if ($i<$minrows-1){
$comma = ", ";
}
else {
$comma = "";
}
//$selection = "MIN(".$explode[$i].")".$comma;
//echo $selection;
$data1 = mysql_query("SELECT MIN(".$explode[$i].")".$comma." from data WHERE (fchmitimestamp LIKE CONCAT(#year,'%',#month,'%',#day,'_________'))");
$all1 = mysql_num_fields($data1); //return # of columns; for some reason is returning "1" right now.
while ($row2 = mysql_fetch_array($data1)) {
for ($col=0; $col<$all1; $col++) {
echo $all1;
echo "<td>Min: " . $row2[$col] . "</td>";
}
echo "</tr>";
}
}
}
}
echo "</table>";
Look at the order of operations in your code:
loop {
... fetch data ...
... assign results to $data1 ...
}
Nowhere in your loop do you output or save the results you've got in $data1, so each iteration of the loop overwrites the results of the previous iteration - in other words, only the LAST iteration's results will be stored.
you are running the query once per for loop cycle (1 field at a time) and since first ones yields in SQL error because of the trailin comma, these will not be echoed except the last one.
-- notice the error in first query
SELECT MIN(Bale_ID), from data WHERE (fchmitimestamp LIKE CONCAT(#year,'%',#month,'%',#day,'_________'))
SELECT MIN(Incoming_Moisture) from data WHERE (fchmitimestamp LIKE CONCAT(#year,'%',#month,'%',#day,'_________'))
use var_dump($selection) instead of echo $selection to see yourself

How do I loop through a PHP array containing data returned from MySQL?

Ok I have a table with a few fields. One of the fields is username. There are many times where the username is the same, for example:
username: bob
password: bob
report: 1
username: bob
password: bob
report: 2
I did a SQL statement to select * where username='bob'; but when I do the following PHP function, it will only return the last result:
$thisrow = mysql_fetch_row($result);
I need to get every field from every row. How should I go about doing this?
$mainsection="auth"; //The name of the table
$query1="select * from auth where username='$user'";
$result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1); //do the query
$thisrow=mysql_fetch_row($result);
echo "Study: " . $thisrow[1] . " - " . $thisrow[5];
Sorry for such a dumb question. I can't seem to get the while loops of more than one field working for the life of me.
mysql_fetch_row fetches each row one at a time. In order to retrieve multiple rows, you would use a while loop like this:
while ($row = mysql_fetch_row($result))
{
// code
}
Use a loop, and use mysql_fetch_array() instead of row:
while($row = mysql_fetch_array($result)) {
echo "Study: " . $row[1] . " - " . $row[5];
// but now with mysql_fetch_array() you can do this instead of the above
// line (substitute userID and username with actual database column names)...
echo "Study: " . $row["userID"] . " - " . $row["username"];
}
I suggest you to read this:
http://www.w3schools.com/php/php_mysql_select.asp
It will give you an overview idea of how to properly connect to mysql, gather data etc
For your question, you should use a loop:
while ($row = mysql_fetch_row($result)){//code}
As said by htw
You can also obtain a count of all rows in a table like this:
$count = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS count FROM table"));
$count = $count["count"];
You can also append a normal WHERE clause to the select above and only count rows which match a certain condition (if needed). Then you can use your count for loops:
$data = mysql_query("SELECT * WHERE username='bob'");
for ($i = 0; $i
Also, mysql_fetch_array() is usually a lot easier to use as it stores data in an associative array, so you can access data with the name of the row, rather than it's numeric index.
Edit:
There's some kind of bug or something going on where my second code block isn't showing everything once it's posted. It shows fine on the preview.
I like to separate the DB logic from the display. I generally put my results into an array that I can call within the HTML code. Purely personal preference; but here's how'd I'd approach the problem: (I'd take the $sql out of the error message in production)
<?php
$sql="
SELECT *
FROM auth
WHERE username='$user';
";
$result = mysql_query($sql)
or die("Failed Query : ".mysql_error() . $sql); //do the query
while ($ROW = mysql_fetch_array($result,MYSQL_ASSOC)) {
$USERS[] = $ROW;
}
?>
HTML CODE
<? foreach ($USERS as $USER) { ?>
Study: <?=$USER['dbFieldName'];?> - <?=$USER['dbFieldName2'];?>
<? } //foreach $USER ?>
$qry=mysql_query(select * where username='bob');
if(mysql_num_rows($qry))
{
while($row=mysql_fetch_array($qry,MSQL_NUM))
{
echo $row[0]." ".$row[1]." ".$row[2]."<br>";
}
}

Categories