Fetching data from relational database in codeigniter - php

I have got 2 tables; table1 and table2. Both of them are related to eachother with a common groupid I am able to query the second table successfully using the following code:
$query = $this->db->query("SELECT * FROM `table2` WHERE `memberid`='$id'");
$data['relation'] = $query->result_array();
Now using groupid result I want to query the first table i.e. table1
I have tried the following methods, without any success:
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
}
$data1['group'] = $query1->result_array();
$fine = array_merge($data, $data1);
print_r(count($fine)); // the count result is 1 ideally should be 2
The above code only returns the last row of the table1 however I am looking for all the results.
When I run the above code inside the "for" loop, it shows me a count of 33:
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
$data1['group'] = $query1->result_array();
$fine = array_merge($data, $data1);
print_r(count($fine)); // the count result is 33 ideally should be 2
}
I know how to achieve this in core php however not too sure how to do it in CI. I am new to CI, any help will be greatly appreciated.
Thanks,
Utpal

$ok = array();
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
print_r ($id);
echo "<br>";
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
$data1['group'][$ii]= $query1->result_array();
}
//print_r($data1['group']);
$fine = array_merge($data, $data1);
print_r($fine);
You need to create a array ($data1) outside this for loop and define $query->result_array(); inside forloop as shown above

Related

PHP loop stops unexpectly

I have a table (table3) in MYSQL with 99 text fields (field1, filed2, ...,field99). I wanted to count the non-empty values of each field so I wrote a simple php script with a for loop as below:
for($i = 1; $i <= 99; $i++)
{
$sqlstm = "SELECT COUNT(field$i) FROM table3 WHERE field$i IS NOT NULL AND field$i <> '';";
$r = #mysqli_query($dbc, $sqlstm);
if($r)
{
while($row = #mysqli_fetch_array($r))
{
echo "<p>$row[0]</p>\n";
}
}
else
{
echo "field $i error: " . mysqli_error($dbc);
}
}
But the loop stopped after showing four values (field1 to filed4) and no error message. I do have all 99 fields with data in table3 and I could run the query manually for any field. Could this due to browser timeout?
Can someone help me? Thanks.
$sqlstm = "SELECT COUNT(field$i) FROM table3
you are selecting the columns here, your table has 99 rows but apperantly only 4 columns
what you could better do is
$sqlstm = "SELECT * FROM table3 WHERE (column name) IS NOT NULL";
$count = 0
for($sqlstm as $one) {
$count = $count + 1;
}
echo($count);
or something along those lines

How do I fix this php to include full list from array?

$q = mysql_query("SELECT * FROM users WHERE ID=".$_SESSION['user_id']."");
while($row = mysql_fetch_array($q)) {
$array = (explode(":",$row['recent_views']));
for ($i = 1; $i < count($array); ++$i) {
$userids = $array[$i].',';
$q2 = mysql_query("SELECT * FROM item WHERE approved = 1 AND id IN(".$userids."0)");
echo $userids;
//NOTE: my echo is spitting out "18622,44968,44968," but when using $userids in mysql query it doesn't include the full list of numbers
}
}
I put }'s after mysql query to try to include variable in the for loop, if i close brackets before query $userids only prints last number from array.
Close the parenthesis before your query and use concatenation instead of re-assigning $userids on each iteration:
$q = mysql_query("SELECT * FROM users WHERE ID=".$_SESSION['user_id']."");
while($row = mysql_fetch_array($q)) {
$array = (explode(":",$row['recent_views']));
for ($i = 1; $i < count($array); ++$i) {
$userids .= $array[$i].',';
// ^ missing the period here
}
}
$q2 = mysql_query("SELECT * FROM item LEFT JOIN subcategory
ON item.subcategory_id=subcategory.subcategory_id LEFT JOIN genre ON item.genre_id=genre.genre_id WHERE approved = 1 AND broken = 0 AND id IN(".$userids."0)");
echo $userids;
You could also just get rid of the for-loop and use implode():
while($row = mysql_fetch_array($q)) {
$array = (explode(":",$row['recent_views']));
$userids .= implode(',', $array) + ',';
}
While this may fix the issue, know that this isn't very efficient nor maintainable. It would make more sense to use SQL JOIN syntax to combine a user's recent views with the sub-categories all in one query.

Multiple Mysqli Select Statement, echo separated results

I have looked online for a solution to my problem for many hours to no avail.
I have multiple selct statements, receiving data from different mysql tables.
I want to echo completely separated results. Currently, results are printed as if they are one,
so I cannot work on the answers separately.
Suppose the output from table is:
100
200
300
400
I want to echo out:
result1 = 100;
result2 = 200;
etc
So I can work on the final results in another program. If a result is null, it should not produce an error,
but just post 0.
Example, if output from mysql table is:
100
null
null
100
I want the output to clearly show
result1 = 100;
result2 = 0;
result3 = 0;
result4 = 100;
etc.
$check_sco = 100;
$sql = "SELECT TABLE_1 FROM RIDER_1 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_2 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_3 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_4 WHERE score1=$check_sco";
if (mysqli_multi_query($con,$sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($con)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);//how to echo separated result that can be manipulated indepedently?
}
mysqli_free_result($result);
}
} while (mysqli_next_result($con));
}
Thank you.
Why not just run them in sequence?
$check_sco = 100;
$riders = array();
for($i=1; $i<=4; $i++) {
$sql = "SELECT TABLE_1 FROM RIDER_" . $i . " WHERE score1=" . $check_sco;
$result = mysqli_query($con, $sql);
$row = $result->fetch_assoc();
$riders[] = ($row['TABLE_1']) ? $row['TABLE_1'] : 0;
}
Then you'll have an array with the results you want
You need to use IFNULL which if TABLE_1 is not null it will return TABLE_1 otherwise it will give you 0
SELECT IFNULL(TABLE_1, 0) FROM RIDER_1 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_2 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_3 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_4 WHERE score1=$check_sco

SQL QUERY returning all results using OR in WHERE statement

Hoping I am just missing something simple here:
$sql = "Select * FROM user_info, user_login WHERE user_login.status = '0' OR user_login.status = '2' AND user_info.uid = user_login.uid";
$db = new connection();
$results = $db->query($sql);
$user = array();
while($info = mysql_fetch_array($results))
{
$user[] = $info;
}
$total = count($user);
//TEST the amount of rows returned.
echo $total;
for ($i = 0; $i < $total; $i++)
{
//echo data;
}
just trying to pull all data that has the user_login.status field set to "0" or "2" but it shows everything thing and it shows the items marked as 2 twice.
Does anyone see my issue?
Your precedence is getting whacked because of missing parentheses:
SELECT DISTINCT *
FROM user_info, user_login
WHERE (user_login.status = '0' OR user_login.status = '2')
AND user_info.uid = user_login.uid
Without seeing the data I can't give you more than a SELECT DISTINCT with regards to the duplicate records.
Select * FROM user_info, user_login WHERE (user_login.status = '0' OR user_login.status = '2') AND user_info.uid = user_login.uid
Order of precedence :)

how can i controll while loop into another while loop

Suppose I have a while loop like:
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
}
then if first query return 5 results i.e 1-5 and second query returns 3 results than if i want to echo out second query it gives me like this..........
111112222233333
than how can i fix to 123 so that the second while loop should execute according to number of times allowed by me........!! how can i do that.........!!
I'm not sure I 100% understand your question - it's a little unclear.
It's possible you could solve this in the query with a GROUP BY clause
$sql_2 = mysql_query("SELECT id FROM secondtable WHERE id != $id GROUP BY id");
But that would only work if you need just secondtable.id and not any of the other columns.
When you say "number of time allowed by me" do you mean some sort of arbitrary value? If so, then you need to use a different loop mechanism, such as Greg B's solution.
Do you want to explicitly limit the number of iterations of the inner loop?
Have you considered using a for loop?
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
for($i=0; $i<3; $i++){
$ro = mysql_fetch_array($sql_2);
$id2 = $ro["id2"];
echo $id2;
}
}
Your first while loop is iterating over all 5 results, one at a time.
Your second while loop is iterating over each of the 5 results, producing it's own set of results (i.e. 3 results for each of the 5 iterations, totaling 15 results).
I believe what you are trying to do is exclude all IDs found in your first loop from your second query. You could do that as follows:
$sql = mysql_query("SELECT * FROM tablename");
$exclude = array();
while($row = mysql_fetch_array($sql)) {
array_push($exclude, $row['id']);
}
// simplify query if no results found
$where = '';
if (!empty($exclude)) {
$where = sprintf(' WHERE id NOT IN (%s)', implode(',', $exclude));
}
$sql = sprintf('SELECT * FROM secondtable%s', $where);
while($row = mysql_fetch_array($sql_2)) {
$id2 = $row["id2"];
echo $id2;
}
$sql = mysql_query("SELECT * FROM tablename");
$tmp = array();
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
if(!in_array($id, $tmp)) {
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
$tmp[] = $id;
}
}
Saving all queried $id's in an array to check on the next iteration if it has already been queried. I also think that GROUPing the first query result would be a better way.
I agree with Leonardo Herrera that it's really not clear what you're trying to ask here. It would help if you could rewrite your question. It sounds a bit like you're trying to query one table and not include id's found in another table. You might try something like:
SELECT * FROM secondtable t2
WHERE NOT EXISTS (SELECT 1 FROM tablename t1 WHERE t1.id = t2.id);

Categories