I need to extract records from a database like this:
id
name
request1
request2
request3
request4
request5
time
request fields can be 0 or 1
and I have my SQL query SELECT * FROM table ORDER BY id ASC but I'm getting only one record for row, but I need to print the records like this:
id1 - name1 - request1
id1 - name1 - request2
id2 - name2 - request4
id2 - name2 - request5
this means having an extract for every single "request = 1"
How can I afford this?
require("datisql.php");
dbconnect();
mysql_query("SET CHARACTER SET 'utf8'");
$result2 = mysql_query("SELECT * FROM richieste ORDER BY id DESC");
while($row = mysql_fetch_array($result2)) {
$id="{$row['id']}";
$nominativo="{$row['nominativo']}";
$data="{$row['timestamp']}";
echo"<div>...........";
}
Here an abstract of the requests table: click me
My answer is based on the assumption that all of the requests columns are in one row. If I am wrong, I will change that. The way I would handle taking a recordset that looks like that would be to loop through each row and throw each row into a for loop like this:
// Add each of the request types to an array
$requestTypes = array('Interior','Exterior');
// Loop through the resultset
while( $row = mysql_fetch_array( $result2 ) ){
foreach($requestTypes as $type){
$id= $row['id'];
$nominativo = $row['nominativo'];
$requestedType = $row[$type];
$data = $row['timestamp'];
}
}
Related
I am fetching multiple rows from my data base like,
$query = "SELECT * FROM student_info where district = '".$admdistrict."' AND user_status = 'approved' ORDER BY id DESC";
$result = mysql_query($query) or die(mysql_error());
$delete = mysql_fetch_array($resultt);
$std_delete_array = explode(',', $delete['id']);
the value of id in database is like 4,5,6 in different rows but it is giving only first value 4.
Another array I am fetching is,
$query="SELECT * FROM events where id='$district'";
$showdata=mysql_query($query) or die(mysql_error());
$user=mysql_fetch_array($showdata);
$std_fulllist_array = explode(',', $user['std_list']);
the value in database is 4,5,6,8. But in single coloumn, so it is giving proper output. now I want to subtract $std_delete_array from $std_fulllist_array.
I am using following code,
$values = array_diff($std_fulllist_array, $std_delete_array);
which is only subtracting first value of $std_delete array.
strucutre of table student_info is
id ! name ! District
4 a panipat
5 b panipat
6 c panipat
strucutre of table events is
id ! district ! std_list
1 panipat 4,5,6
2 karnal 4,7,8
3 chandigarh 5,6,7
You are saying the value of id in database is like 4,5,6 in different rows
that means your table is look like
id district
-- ---------
4 abc
5 def
6 geh
8 ijk
so your first query is fetching multiple records.
EDIT
So your query would be
$ret_ = array();
$query = "SELECT * FROM student_info where district = '".$admdistrict."' AND user_status = 'approved' ORDER BY id DESC";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysql_fetch_array($result)) {
echo $row['id'];
$ret_[] = $row;
}
}
print_r($ret_);
I have two different tables of the following structure:
grouprel
id | userId | pupID | groupId
pupils
id | userId | fname | lname
pupId in groulrel is equal to id in pupils.
I want to fetch pupils from a different group and then order them by fname, lname.
Now I have two queries like this:
$q = "SELECT * FROM grouprel WHERE userid = ". $userid ." AND groupId = ". $_GET['id'] ."";
$r = mysqli_query($mysqli, $q);
while ($rows = mysqli_fetch_object($r)) {
$query = "SELECT id, fname, lname FROM pupils WHERE userid = ". $userid ." AND id = ". $rows->pupId ." AND status = 0 ORDER BY fname, lname";
$result = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_object($result)) {
echo stuff...
}
}
This works, but it doesn't order the names alphabetically like I want to.
How could I fix this?
This is iterating over the first query:
while ($rows = mysqli_fetch_object($r)) {
And this iterates over each instance of the second query:
while($row = mysqli_fetch_object($result)) {
So if the first query returns 1,2,3, and each iteration of the second query returns A,B, then your output would be:
1 A
1 B
2 A
2 B
3 A
3 B
The second query is ordering by the ORDER BY clause you gave it. But you are ordering the entire output by the first query.
Ultimately, why do you need these separate queries at all? Executing a database query in a loop is almost always the wrong idea. It looks like all you need is one query with a simple JOIN. Guessing on your logic, something like this:
SELECT
pupils.id, pupils.fname, pupils.lname
FROM
pupils
INNER JOIN grouprel ON pupils.id = grouprel.pupId
WHERE
pupils.userid = ?
AND grouprel.groupId = ?
AND pupils.status = 0
ORDER BY
fname, lname
It may take a little tweaking to match exactly what you're looking for, but you can achieve your goal with a single query instead of multiple separate queries. Then the results of that query will be ordered the way you told MySQL to order them, instead of the way you told PHP to order them.
I have a table in database and in this table i have added 3 columns that is i, name,parent_id.please see below.
ID | name | parent_id
1 name1 0
2 name2 1
3 name3 1
Now i want to fetch this id from database. I have created a method in PHP and fetch data one by one from database. Please see below
function getData($id)
{
$array = array();
$db = JFactory::getDBO();
$sql = "SELECT * from table_name when id = ".$id;
$db>setQuery($sql);
$fetchAllDatas = $db->getObjectList();
foreach ($fetchAllDatas as $fetchAllData)
{
if($fetchAllData->parent_id > 0)
{
$array[$fetchAllData->parent_id] = $fetchAllData->name;
$this->getData($fetchAllData->parent_id);
}
else
{
$array[$fetchAllData->parent_id] = $fetchAllData->name;
}
}
return $array;
}
Now if i call this method with id 3 like
$this->getData(3); // has a parent
It will return like that
Array(
[0]=>name1
)
But i want like below
Array(
[1]=>name3,
[0]=>name1
)
I know i have redefine array if we have parent but how i manage it.
i have used array_push php function but its not work with my condition.
foreach ($fetchAllDatas as $fetchAllData)
{
$array[$fetchAllData->parent_id] = $fetchAllData->name;
if($fetchAllData->parent_id > 0)
array_push($array,$this->getData($fetchAllData->parent_id));
}
return $array;
1)Because you do $array[$fetchAllData->parent_id] = $fetchAllData->name; in the if and in the else, you do this in both cases so put out of if..else.
2) Try to push the result of your second call in the original array to get what you want.
you have unique ID in your table, so if you call your query it will always return only one result. Maybe you wanted to write query this way:
$sql = "SELECT * from table_name when parent_id = ".$id;
if you want to get the result with given ID and his parent, you should add this after calling $this->fetchSharedFolder(...);
$array = array_merge($array, $this->getData($fetchAllData->parent_id));
OK so I have a table like this
Col1 Col2
10 30
20 40
50 60
I am querying the data like so
Query = ("SELECT * FROM TableName");
while ( $row= Mysql_fetch_array($query)) {
// code will go here
Code needs to get the prev row and the current row for every row in the table like:
This row['col1'] - prev row['col1'] = $wahatever
echo $whatever
}
I dont know whow to reference the prev row in php so as it looks through the while statment I need to say col1 - prev col1 and col2 - prev col2
Can Anyonw tell me how to do this. Its actually for working out complex mapping distcances which I can do, just cant work out how to call the prev rows data in the loop.
Any help would be greatfully apprceiated
Thanks for all your help but I dont think I asled the question properly.
What I am looking for is for a way to get each row and then minus col1 from col1 on the prev row and run through a loop untill the end.
You can try this completly in SQL solution
SELECT col1, col2,
col1 - #prev1,
col2 - #prev2,
#prev1 := col1, #prev2 := col2
FROM TableName, (select #prev1 := 0, #prev2 := 0) r
SQLFiddle demo
$prevRow = null;
while ( $row= Mysql_fetch_array($query)) {
if($prevRow != null){
//comparison here
}
$prevRow = $row;
}
Or, you could store your values first in an array like
$myArr = array(); $i=0;
while ( $row= Mysql_fetch_array($query)) {
// code will go here
$myArr[$i] = $row['col1'];
$myArr[$i] = $row['col2'];
$i++;
}
Then you would know that $i-1 is the previous row from db.
foreach($myArr as $i => $row) {
if( isset($myArr[$i-1]) {
$prevRow = $row;
}
// blah blah blah
}
You can use mysql_data_seek for changing pointer to current row and then fetch it, but I recommend to store previous value in each step
if you will compare 2 different rows most probably they will not be equal if they have id which is primary and auto incrementing but if you will just compare the specific data's in the row best way is to store them or you can query all column but not including the id
query the id-1 of the current query just make sure to make the id primary and auto increment for example
<?php
$que = "SELECT * FROM table ...'";
res = mysql_query($que, $con);
if(mysql_num_rows($res)>0){
while($row = mysql_fetch_array($res)){
$counter=1;//apply this so it will not compare the first row in the data to the previous
//one because there is nothing to compare
if($counter > 1){//determine if it is the 2nd row therfore do the comparison
$currentrow=$row['id']; //this is the id of the current row which is row 2
$previousrowid=$row['id']-1; //this is the id of the row 1 which you will need to query
//the datas on it to compare it
$que2 = mysql_query("SELECT value FROM table where id= '$previousrowid' ");//query of the previous row
$r = mysql_fetch_array($que2);
$previousdata=$r['data'];
$currentdata=$row['data'];
$counter++;
if($previousdata != $currentdata)
{
echo "They Are Not Equal";
}else{
echo "They Are Equal!";
}
}//ending of the counter
}}//ending of loop
?>
hopes this help
$count =0;
$result1 = mysql_query("SELECT fwid FROM sbsw WHERE fword = '".$searchText."'");
while ($result2= mysql_fetch_array($result1))
{
$result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2[$count]."'");
$result4= mysql_fetch_array($result3);
print $result4[$count].'<br>';
$count++;
}
mysql_free_result($result1);
mysql_free_result($result3);
Let's have a look at how mysql_fetch_array works - for example if you have table structure like
id | name | surname | role
1 John Smith user
2 Peter Qeep user
3 Mark Ziii admin
When you execute a query SELECT * FROM table and then loop $result = mysql_fetch_array($query), $result will always be an array(4) containing
[0] => id,
[1] => name,
[2] => surname,
[3] => role
Therefore, when you execute the query $result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2[$count]."'");, in the first iteration, $count will be 0 which is the key for the result returned by the previous query, however in any further iteration it will increase and that will lead to an undefined key. This means that you have to stop using the variable $count and just use $result2[0] instead.
Also, way better approach to this would be using MySQL JOIN, in your example it would be SELECT w.fsyn FROM sbsw s JOIN wrsyn w ON s.fwid = w.fwid WHERE s.fword = "'.$searchText.'";
Please, use reasonable variable names and indent properly. You're getting one column from each row as you're only printing out once for each iteration over your rows.
Basically: For each row, print the value of a column.
The $count-variable decided which column, but it obviously didn't make sense at it counts the row you're at.
Something like this should do it: (not tested)
$result1 = mysql_query("SELECT fwid FROM sbsw WHERE fword = '".$searchText."'");
while ($result2= mysql_fetch_array($result1))
{
$result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2['fwid']."'");
$result4= mysql_fetch_row($result3);
for($x = 0; $x < count($result4); $x++){
print $result4[$x].'<br>';
}
}
mysql_free_result($result1);
mysql_free_result($result3);
Oh and I changed fetch_array to fetch_row in the inner loop to ease iteration.