mysql_fetch_array and array keys - php

This code works:
$row = array(5,6,89,97,101);
$found = array();
$post = 89;
$count_row = count($row);
for($i = 0; $i < $count_row; $i++){
if($row[$i]==$post){
$found[] = $row[$i-2];
$found[] = $row[$i-1];
$found[] = $row[$i];
$found[] = $row[$i+1];
$found[] = $row[$i+2];
var_dump($found);
}
}
And this does not, probably doing something wrong in the mysql_fetch_array;
$found = array();
$q = "SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id='$term_tax_id'";
$rs = mysql_query($q) or die(mysql_error());
$row = mysql_fetch_array($rs, MYSQL_NUM);
$count_row = count($row);
for($i = 0; $i < $count_row; $i++){
print_r($row);
if($row[$i]==$post){
$found[] = $row[$i-2];
$found[] = $row[$i-1];
$found[] = $row[$i];
$found[] = $row[$i+1];
$found[] = $row[$i+2];
var_dump($found);
}
}
Nothing is shown if post is more than 1.
Anyone know a way to solve this problem?

mysql_fetch_array() fetches one single row, which, in your case, contains exactly one column.
You should either query all rows from the result set at once (which I don't know how that works), or you should do this:
$q = "SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id='$term_tax_id'";
$rs = mysql_query($q) or die(mysql_error());
$data = array();
while ($row = mysql_fetch_array($rs, MYSQL_NUM)) {
$data[] = $row[0];
}
for($i = 2; $i < count($data) - 2; $i++){ // adjusted boundaries
if($data[$i]==$post){
$found[] = $data[$i-2];
$found[] = $data[$i-1];
$found[] = $data[$i];
$found[] = $data[$i+1];
$found[] = $data[$i+2];
var_dump($found);
}
}
}
I as well have adjusted the boundaries: if you are interested in the range $i-2 to $i+2, you only should run from 2 to end-2.

The select statement should be rewritten so as to return only the values you're looking for. One way to do this is with a UNION of two selects, one returning lesser object IDs and one returning greater. You should also make use of WordPress's wpdb class. For one thing, a site admin may change the table prefix from "wp_" to something else; $wpdb->term_relationships will give the correct name for the table.
$statement = $wpdb->prepare(
" (SELECT object_id
FROM $wpdb->term_relationships
WHERE term_taxonomy_id= %d
AND object_id <= %d
ORDER BY object_id DESC
LIMIT 3)
UNION
(SELECT object_id
FROM $wpdb->term_relationships
WHERE term_taxonomy_id= %d
AND object_id > %d
ORDER BY object_id ASC
LIMIT 2)
ORDER BY object_id", $term_tax_id, $post, $term_tax_id, $post);
$found = $wpdb->get_results($statement);
This also has the advantage of working when there are less than two terms relationships before or after the center (the object with id $post).

Related

Why does not the fetch statement have any value after the fetch_all statement?

I want to output the number of myTable and output field1 of myTable in the loop.
However, if I run the following code, only 10 'test : ' will be printed.
If I remove [$rows = $statement->fetchAll(PDO::FETCH_ASSOC);] and change the $count of for() to 10, it works fine, but that is not what I intended.
<?php
$db = new PDO("mysql:host=localhost;dbname=mydb;charset=utf8;", myid, mypw);
$statement = $db->query('select field1 from myTable limit 10');
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
$count = count($rows);
echo "count : $count<br><br>";
for($i = 0; $i < $count; $i++)
{
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo 'test : '.$row['field1'].'<br>';
}
?>
I would like to avoid the following methods to count the number of myTable. Because query statements that look similar are added unnecessarily.
$count = $db->query('SELECT count(*) FROM qudtls_mutter')->fetchColumn();
As the result, from
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
will be associative array, that you will need to count.
You can simply use $statement->rowCount():int that will return count from last query.
Then you can use it mixed with FOR
for ($i=0; $i<$statement->rowCount(); $i++) {
}
For other use, you can go with WHILE
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
}
For use foreach, simply:
foreach ($statment as $row) {
}
$db = new PDO("mysql:host=localhost;dbname=mydb;charset=utf8;", myid, mypw);
$statement = $db->query('select field1 from myTable limit 10');
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
The above will, as it says, fetch All of the ten rows. There will be now no more rows to fetch in your result set. This is to be expected.
Change this:
for ($i = 0; $i < $count; $i++) {
$row = $statement->fetch(PDO::FETCH_ASSOC);
to this:
foreach ($rows as $i => $row) {
to have it work. After the fetchAll you already have all the rows, you do not need to fetch them again, and it will not work if you try to.
If you want to output the whole table, do not fetchAll, but fetch until there is nothing left. Remove the fetchAll, and:
$i = 0;
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$i++;
// This will execute for all rows. It will exit as soon as fetch() returns null at the end of the query.

Fetching data from relational database in codeigniter

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

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.

PHP array for loop

I want to show the array value $result[] from the for loop calculation. However, it shows me nothing on the page. Is there is anything wrong in the below code?
$sql= "SELECT * FROM items where itemID =3 ";
$result1= mysql_query($sql) or die (mysql_error());
while ($row= mysql_fetch_array($result1)){
$quantity[] = $row ['quantity'];
$month[] = $row ['month'];
}
$alpha = 0.3;
for($i = 1; $i > 12; $i++){
$result[$i] = ($quantity[$i] - $result[$i-1]) * $alpha + $result[$i-1];
}
foreach ($result as $key => $value ){
echo "$value";
}
Your for loop has an error. You have
for($i = 1; $i > 12; $i++)
but it should be
for($i = 1; $i < 12; $i++)
This is not directly the answer to your question, but there are few things that hasn't been mentioned that concern the way you query and process your data:
Your SELECT statement doesn't have specific order specified. Since order of records is not preserved you can get records out of correct order and get invalid calculations. Use ORDER BY (e.g. ORDER BY month) or make use of month values and extract exactly previous month's value from array(s) (if it is what you're doing in your code).
Your current code relies on the fact that the resultset from DB will contain (at least) 12 records. If for some reason it will produce less records your for loop will brake.
It's uncertain from the information in the question but it looks like you might need a year in your query unless the table contains records only for one year.
Now, you can calculate the whole thing on DB side with a query like this
SELECT i.month,
COALESCE((i.quantity - p.quantity) * 0.3 + p.quantity, 0) value
FROM items i LEFT JOIN items p
ON i.itemID = p.itemID
AND i.`year` = p.`year`
AND i.month = p.month + 1
WHERE i.itemID = 3
AND i.`year` = 2013
ORDER BY month
SQLFiddle
That's assuming (and I'm not sure about that) you actually need to read previous month's quantity values for your calculations and month column is of integer type
There is an obvious flaw in the logic. You try to get the $i index form $quantity. However, you can't be sure $quantity will have this index.
Supposing that itemId is not the primary key, I would do something like this:
$sql = "SELECT * FROM `items` WHERE `itemID` = 3";
$result1= mysql_query($sql) or die (mysql_error());
while ($row= mysql_fetch_assoc($result1)){
$quantity[] = $row ['quantity'];
}
$alpha = 0.3;
$i = 1
foreach ($quantity as $elem) {
if ($i >= 12)
break;
$result[$i] = ($elem - $result[$i-1]) * $alpha + $result[$i-1];
$i++
}
foreach ($result as $value ){
echo $value;
}

storing percentages into an array

I'm trying to store a number of percentages that I've worked out into an array so that I can call it later on to create a pie chart but don't have a clue how to do it. Here is my PHP code so far for working out the percentages: Thanks for any help in advance!
//execute the SQL query and return records
$result = mysql_query("SELECT book_id, COUNT(*) FROM loan GROUP BY book_id ASC ORDER BY count(*) DESC LIMIT 10");
$book_count = mysql_num_rows($result);
$step = 1;
while($row = mysql_fetch_array($result))
{
$total = $total + $row['COUNT(*)'];
$i[$step] = $row['COUNT(*)'];
$step++;
}
for($index = 1; $index <= 10; $index++)
{
$percentage[$index] = (($i[$index]/$total)*100);
#$degrees = (($percentage/100)*360);
}
This should do what you're asking, just substitute the variables for real ones:
array_push($array, $value);
// This will add "$value" on to the end of $array, i.e the last element
It can also be done much simpler:
$array[] = $value;
Updated code:
//execute the SQL query and return records
$result = mysql_query("SELECT book_id, COUNT(*) FROM loan GROUP BY book_id ASC ORDER BY count(*) DESC LIMIT 10");
$book_count = mysql_num_rows($result);
$step = 1;
while($row = mysql_fetch_array($result))
{
$total = $total + $row['COUNT(*)'];
$i[$step] = $row['COUNT(*)'];
$step++;
}
$percentage_array = array();
for($index = 1; $index <= 10; $index++)
{
array_push($percentage_array, (($i[$index]/$total)*100));
#$degrees = (($percentage/100)*360);
}

Categories