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;
Related
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
$search = htmlspecialchars($_GET["s"]);
if(isset($_GET['s'])) {
// id index exists
$wordarray = explode(" ",$search);
$stringsearch = implode('%',$wordarray);
echo $stringsearch;
echo ",";
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
if (!empty($result)) {
echo sizeof($result);
echo ",";
Database has 3 rows with titles test,pest,nest with corresponding id's 1,2,3. when i request domain.com/?s=est
it echos something like this
est,2,
Now when i checked $result[0] and $result[1], $result[0] echoed 1 and $result[1] didn't echo anything. When I use foreach function, it is taking only value of $result[0]
and $result should be array of all the three indexes.
I cannot find any mistake,
when i type the same command in sql console it works, somebody help me, thanks in advance.
The problem is, if you're expecting multiple rows, then don't do this:
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
This only fetches the first row, you need to loop it to advance the next pointer and get the next following row set:
$result = $conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%' ");
while($row = $result->fetch_array()) {
echo $row[0] . '<br/>';
// or $row['ID'];
}
Sidenote: Consider using prepared statements instead, since mysqli already supports this.
I'm probably missing something easy, but I seem to be blocked here... I have a MySQL database with two tables and each table has several rows. So the goal is to query the database and display the results in a table, so I start like so:
$query = "SELECT name, email, phone FROM users";
Then I have this PHP code:
$result = mysql_query($query);
Then, I use this to get array:
$row = mysql_fetch_array($result);
At this point, I thought I could simply loop through the $row array and display results in a table. I already have a function to do the looping and displaying of the table, but unfortunately the array seems to be incomplete before it even gets to the function.
To troubleshoot this I use this:
for ($i = 0; $i < count($row); $i++) {
echo $row[$i] . " ";
}
At this point, I only get the first row in the database, and there are 3 others that aren't displaying. Any assistance is much appreciated.
You need to use the following because if you call mysql_fetch_array outside of the loop, you're only returning an array of all the elements in the first row. By setting row to a new row returned by mysql_fetch_array each time the loop goes through, you will iterate through each row instead of whats actually inside the row.
while($row = mysql_fetch_array($result))
{
// This will loop through each row, now use your loop here
}
But the good way is to iterate through each row, as you have only three columns
while($row = mysql_fetch_assoc($result))
{
echo $row['name']." ";
echo $row['email']." ";
}
One common way to loop through results is something like this:
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
// do stuff with $row
}
Check out the examples and comments on PHP.net. You can find everything you need to know there.
I need to have a single row of data "printed out" through php.
So, take this example from w3schools:
http://www.w3schools.com/PHP/php_mysql_select.asp
There is a cicle that goes through all the rows ( in this case, 2) and prints them out. The end result is:
Peter Griffin
Glenn Quagmire
What I want is to be able to select row 1 or 2 (or more) and just have that row of data selected. Then I could say something like (I know this doesent work, just an example):
echo $row["Name",2];
And get:
Glenn Quagmire
I believe I have to get a special parameter in mysql_fetch_array, but I cant find it anywhere, and I bet its something really simple. Please help me out, full examples/tutorials/guides links are preferred.
you have 2 options. First is edit your SQL query like exmaple below this will return just 2nd row from database.
$result = mysql_query("SELECT * FROM Persons" WHERE id = 2);
Or during the foreach loop fetch all result into another array.
$result = mysql_query("SELECT * FROM Persons");
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row['FirstName'] . " " . $row['LastName'];
}
As far as i know mysql doesnt have a function to return the entire query as an array.
So you can switch to using PDO (recommended):
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetchAll();
echo $result[1]['name'];
or if you must use the mysql_functions just create an array with the loop:
while($row = mysql_fetch_array($result)) {
$result[] = $row;
}
echo $result[1]['name'];
fetchall the results into an array and print the row you want.
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>";
}
}