Retrieve part of a MySQL column with PHP - php

For instance, if I have the following table:
+----+---+----------+
| id | a | position |
+----+---+----------+
| 0 | 0 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 4 |
| 3 | 1 | 9 |
| 4 | 1 | 6 |
| 5 | 1 | 1 |
+----+---+----------+
and I want to get an array that contains the first 100 values from position where a is 1 in ascending order, what would I do?
Im guessing something like this:
$col = mysql_fetch_array( mysql_query('
SELECT `position`
FROM `table`
WHERE `a`="1"
ORDER BY `position` ASC
LIMIT 100
'));
I'd expect to get the following array:
+-------+-------+
| index | value |
+-------+-------+
| 0 | 1 |
| 1 | 4 |
| 2 | 6 |
| 3 | 9 |
+-------+-------+
but it doesn't work.
¿What should I do to make it work?
Thanks

mysql_fetch_array() gets a single row at a time from the result of your query. To access all of the rows you need a loop. Something like...
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
printf("index: %s value: %s", $row[0], $row[1]);
}
I would take a closer look at: http://php.net/manual/en/function.mysql-fetch-array.php

Okay, couple of things:
Running the mysql_query inside the fetch_array is weird. Mysql_fetch_array works on a query result to put the individual lines of the result(as fetched) into an array. So when you're running it as you've got it, if it runs at all, it's only going to give you the first row, not the first hundred rows.
Second, the quoting looks pretty weird. Depending on the data type in "a", the double quotes might cause. (Haven't used MySQL in a bit, could be wrong.)
If I was going to do it, I'd do it like this:
$result = mysql_query("SELECT index, position FROM table WHERE a = 1 ORDER BY position ASC LIMIT 100");
while($col = mysql_fetch_array($result)){
*do something*
}
*Thanks to JYelton for the Query reformat.

Your query is okay.
The problem is that mysql_fetch_array retrieves only one row. You should loop all the rows and add each value to your $col array.
$result = mysql_query('...');
while($row = mysql_fetch_array($result, MYSQL_NUM))
{
$col[] = $row[0];
}
Now $col contains following:
Array
(
[0] => "1"
[1] => "4"
[2] => "6"
[3] => "9"
)

Related

SQL query returns one row too few

SOLUTION: Make sure you don't 'use up' any $responses->fetch_assoc()s before the while loop.
I performed mysqli_fetch_array($responses);.
In php I have this sql query (simplified for your convenience, but the problem remains)
$sql = "SELECT id, content FROM responses ORDER BY RAND()";
$responses = $conn->query($sql);
where the responses table looks like this:
+----+----------+--------+------+
| id | content | userId | part |
+----+----------+--------+------+
| 4 | peewee | 31 | 1 |
| 5 | tallinn | 31 | 1 |
| 6 | dewey | 31 | 1 |
| 7 | stanford | 31 | 1 |
+----+----------+--------+------+
That doesn't format properly so all you need to know is that the id and content rows are different for each entry while the rest is the same for each.
The problem is, when I do a while loop on $responses like so:
while ($row = $responses->fetch_assoc()) {
$responseId = $row["id"];
$content = $row["content"];
echo " id: ".$responseId;
echo " content: ".$content;
}
I always get 1 record fewer than there are. In this case, since there are 4 rows, I would only see 3 echoed. However, it is not always the same 3, nor are they in the same order. If I remove the ORDER BY RAND() clause, then it is always the first record which is left out.
Thanks in advance
Cheers

Querying MySQL results into multi-dimensional associative PHP array

I'm probably overlooking a fairly simple way of doing this; perhaps someone has an idea of how to make this easy with limited looping and without an excessively long query. Let's say I have a MySQL table with data like this: (There's 12 months, and could be maybe 10 different possible grades). I'll query out just the results for a given user_id and year.
+----+---------+------+-------+-------+-------+
| id | user_id | year | month | grade | value |
+----+---------+------+-------+-------+-------+
| 1 | 1 | 2021 | Jan | A | 95 |
+----+---------+------+-------+-------+-------+
| 2 | 2 | 2021 | Jan | D | 75 |
+----+---------+------+-------+-------+-------+
| 3 | 2 | 2021 | Feb | F | 45 |
+----+---------+------+-------+-------+-------+
I want to be able to query the data and put it into a multi-dimensional associative PHP array.
Essentially, so I can access the data like this:
echo $month_value['Jan']['D']; // Should give me 75
echo $month_value['Feb']['F']; // Should give me 45
Figured out a simple method that works for me:
$sql_retrieve = $con->prepare("SELECT month, grade, value
FROM table
WHERE user_id = ? AND year = ?;");
$bind_process = $sql_retrieve->bind_param('ii',$user_id,$year);
$sql_retrieve->execute();
$result = $sql_retrieve->get_result();
$month_values = []; // initialize array
if($result->num_rows > 0 ){ // If there are results
while($row=$result->fetch_assoc()){
$month_values[$row["month"]][$row["grade"]] = $row["value"]; // add to array
} // end while
} // end of if num_rows > 0
print_r($month_values); // Example
echo 'Value: '.$month_values['Jan']['D'];
This then provides the MySQL results into a multi-dimensional associative PHP array, so they can be referenced as such.

do the math for each data in database sql post result to database in php

I'd like to fetch data from my 2 sql database and do some math and post the result in database
let's say my table1 is like this
+---+---+----------------------------+
| A | B | C |
+---+---+----------------------------+
| 2 | 9 | result from A*B*D*E in php |
| 1 | 8 | result from A*B*D*E in php |
| 4 | 7 | result from A*B*D*E in php |
| 3 | 6 | result from A*B*D*E in php |
| 6 | 5 | result from A*B*D*E in php |
| 6 | 5 | result from A*B*D*E in php |
| 5 | 4 | result from A*B*D*E in php |
+---+---+----------------------------+
and my table2 is like this
+---+----+
| D | E |
+---+----+
| 1 | 9 |
| 2 | 7 |
| 3 | 8 |
| 4 | 6 |
| 5 | 5 |
| 6 | 3 |
| 7 | 2 |
+---+----+
so far what i've done
// database connection
include_once("config.php");
// Query
$query = mysqli_query($conn, "SELECT * FROM table1");
$query2 = mysqli_query($conn, "SELECT * FROM table2");
//Source1
while($user_data1 = mysqli_fetch_array($query))
{
$A[] = $user_data1['A'];
$B[] = $user_data1['B'];
}
//Source2
while($user_data2 = mysqli_fetch_array($query2))
{
$D[] = $user_data2['D'];
$E[] = $user_data2['E'];
}
foreach (array_combine($A, $B) as $ValueA=> $ValueB)
{
foreach (array_combine($D, $E) as $ValueD=> $ValueE)
{
$result1 = $ValueA*$ValueB*ValueD*ValueE;
$val = 0.123;
$result2[] = $result1*$val;
}
$final result = min($result2);
echo round($final result, 2);
unset($result2);
}
I haven't inserted the database yet
still echoing for debug if the math is correct
somehow this code found some bug
for example using my database the final result only echo/showing 6 math result
because in table1 row 5 and 6 has same data
btw of course in my table1 and 2 has primary key
To change C in this case, you don't even need PHP. To UPDATE a value in MySQL with multiple tables just add them with a , when selecting the tables, like this:
UPDATE table1,table2 SET C = table1.A * table1.B * table2.D * table2.E WHERE C IS NULL;
Executing this code once will update all rows so that C = A*B*D*E as wanted where C is not yet set or NULL. If you want to update all rows you can just remove the WHERE condition
Note: Sometimes (at least for me) SQL will give a warning when having no WHERE condition in the SQL query. To bypass this just add WHERE 1=1 at the end.
Just for my understanding: you want to calculate a value for your calculation you need some data from table 1 that is clear, but also from table2 But which one? I guess you want to use the data from the same row ( so row 1 from table1 and row 1 from table2, row 2 from table 1 and row 2 from table2 ) right? Now you have an problem because when you make a select * from table You do not know in which order they give back from your database. Most time it may be the same order as you have input them, but there is no garantie. You have sayed you have an primary key on each table, how have you defined them? I guess you may have a id column, so you can join your table on that id?

Cannot understand how to do this loop structure

Can someone help me on the way with a SELECT (or more if needed) and some php loops. I've been trying to come up with a solution for 2 days now.
There's this 12 column grid I use which is movable and resizable. I store the data of it, such as x-axis, y-axix, width, height.
Here is an example of the database table elements:
| id | page_id | element_type | element_x | element_y | width | height | element_content
----------------------------------------------------------------------------------------
| 45 | 1 | title | 0 | 0 | 12 | 1 | Content
| 70 | 1 | button | 6 | 2 | 6 | 1 | Content
| 23 | 1 | form | 4 | 1 | 4 | 1 | Content
| 55 | 1 | rich-textfield 0 | 1 | 4 | 1 | Content
| 101| 1 | gallery | 8 | 1 | 4 | 1 | Content
As you can see the height doesn't matter because it's always 1.
This example structure would show this in my resizable grid:
So far I got this to SELECT the grid items:
$id = 1;
$selectElements = $conn->prepare("SELECT * FROM `elements` WHERE `page_id` = :id");
$selectElements->bindParam(':id', $id, PDO::PARAM_STR);
$selectElements->execute();
What I have in mind is something like
foreach element_y
<div class="row">
// loop to loop thru all element_x's per element_y
</div>
endforeach
Note that every element_y number needs to be outputted just one time each. so instead of:
0 - 1 - 1 - 1 - 2 it should be 0 - 1 - 2
Is it possible to make what I have in mind or am I thinking the complete wrong way? :) Highly appreciated!
P.S. If the question is not clear enough tell me, I will change my question!
I'd suggest something along the lines of the following:
Make sure your SQL orders by element_y and element_x:
SELECT * FROM `elements`
WHERE `page_id` = :id
ORDER BY `element_y` ASC, `element_x` ASC
That way, you'll be sure to have the correct order already.
Then, transform your array into a slightly different structure with something like this:
$elements_grouped = [];
foreach ($elements as $key => $element) {
$elements_grouped[$element['element_y']][$key] = $element;
}
That will put your elements in an array with element_y keys holding their respective elements.
Then, you can loop over that, and in in a second loop loop over the elements (using your pseudocode):
foreach elements_grouped as row
<div class="row">
foreach row as element
// output element
endforeach
</div>
endforeach
You should use multi dimensional array ( key and value) to handle all data first
$handleData = array();
foreach($result as $item){
$handleData[$item['element_y'] => array(
$item['element_x'] => array(
'element_type' => $item['element_type'],
'width' => $item['width '],
'element_content' => $item['element_content']
)
)
}
After that, you just need to printout $handleData

counting multiple values in a row, going trugh columns twice in a row

I have a table that look like this:
Name | date1 | date2 | date3 | etc..
per1 | status1 | | status2 | etc
per4 | status2 | status3 | | etc
The number of the dates columns is not fixed. Their values can either be a status or they can be empty.
I want to access the data of the dates columns for each row separately and process the data.
The output I want to achieve:
Name | field1 | status1 | status2 | etc..
per1 | value | #ofstat1 | #ofstat2 | etc
So for I got, accessing the table at the beginning of the question:
$confirmed ="Confirmed";
$accepted ="Accepted";
while ($row = mysql_fetch_array($result)) {
$confirmed_cnt =0;
$accepted_cnt =0;
foreach ($row as $value) {
if (strcmp($value, $confirmed)) $confirmed_cnt++;
else if (strcmp($value, $accepted)) $accepted_cnt++;
}
print("<tr>");
print("<td>$row["Name"]</td>"); // name
print("<td>$confirmed</td>"); // confirmed
print("<td>$accepted</td>"); // accepted
print("</tr>");
}
As far as I know this should work, but for some reason it goes trough each column 2 times in a row.
Try mysql_fetch_assoc() or mysql_fetch_row() instead.
mysql_fetch_array() returns every column two times: as [1] and as ['fieldName']
Also, you have another error, replace your following line:
print("<td>$row["Name"]</td>"); // name
for this one:
print("<td>$row['Name']</td>"); // name

Categories