while (double?) foreach or join? - php

I have an Excel sheet which is converted to csv and then code imports that into mysql.
In Excel I have in first row A's and B's
I get output, It works but I cannot get into displaying data right.
How I'm trying to display is A B then break and again A B and so on. It is ordered by contact_id but I only get AAAAAA's and 1 B if I try double while.
This is the code with which I have tried to achieve this. Tried double while and I have googled and I have noticed double while is not working, Couldn't get it to work with mysql JOIN either and have never worked with foreach function.
$data = dbquery("SELECT contact_id, contact_first, contact_last, contact_email FROM contact_info WHERE contact_first='A)' ORDER BY contact_id ASC");
$data2 = dbquery("SELECT contact_id, contact_first, contact_last, contact_email FROM contact_info WHERE contact_first='B)' ORDER BY contact_id ASC");
while ($userdata = dbarray($data)) {
echo "<li><ul class='ulcla'>";
echo "<h1>".$userdata['contact_first']."</h1>";
echo "<li>".$userdata['contact_last']."</li>";
echo "</ul><br>";
while ($userdata = dbarray($data2)) {
echo "".$userdata['contact_id']." - ".$userdata2['contact_first']." - ".$userdata2['contact_last']." - ".$userdata2['contact_email']."";
echo "<br>";
}
echo "</ol></div>";
}
How could I loop data like that?

Change while ($userdata = dbarray($data2)) { to while ($userdata2 = dbarray($data2)) {for innner while loop
$data = dbquery("SELECT contact_id, contact_first, contact_last, contact_email FROM contact_info WHERE contact_first='B)' ORDER BY contact_id ASC");
$data2 = dbquery("SELECT contact_id, contact_first, contact_last, contact_email FROM contact_info WHERE contact_first='B)' ORDER BY contact_id ASC");
while ($userdata = dbarray($data)) {
echo "<li><ul class='ulcla'>";
echo "<h1>".$userdata['contact_first']."</h1>";
echo "<li>".$userdata['contact_last']."</li>";
echo "</ul><br>";
while ($userdata2 = dbarray($data2)) {
echo "".$userdata2['contact_id']." - ".$userdata2['contact_first']." - ".$userdata2['contact_last']." - ".$userdata2['contact_email']."";
echo "<br>";
}
echo "</ol></div>";
}

If there are the same amount of each A and B then you can create two arrays from the output and use a simple for loop to go through the keys. So it could echo $userdata[$x] and $userdata2[$x] where $x is the loop iterator.
Try to avoid using multiple loops, especially nested loops.

while ($userdata = dbarray($data)) {
//your stuff
while ($other_userdata = dbarray($data2)) {
//your other stuff
}
}

Related

Group the output of PDO query

I have a PDO query in which I am doing inner join on two tables and extracting the columns required by me.
Now these two columns are - status, script.
Status can be - passed, failed, incomplete and
script - scripts/testSuite/layer3Features/ManualStaticRouting/manualStaticRoutes.tcl , scripts/testSuite/hostAgentFeatures/dhcp/DHCP IPv6/RelayBBasicFunc/ipv6DhcpRelayEnableDhcpv6RelayGlobally.tcl
the output of --
while($row = $getFamily->fetch(PDO::FETCH_ASSOC))
{
foreach($row as $key)
{
print_r($row);
}
is -
http://pastebin.com/WqcibEyp
the full query is -
$testType = 'TCL';
$getFamily = $conn->prepare('SELECT testcases2.script, results3.status FROM testcases2 INNER JOIN results3 ON testcases2.testcaseID = results3.testcaseID
WHERE testType = :testType');
$getFamily->execute(array(':testType' => $testType));
while($row = $getFamily->fetch(PDO::FETCH_ASSOC))
{
foreach($row as $key)
{
print_r($row);
$family[] = $key;
}
}
Now here what I want to do is, read the second location of each script (considering scripts at 0) and group all the values which have same stuff in the third location, with status together.
How this can be done.
Please guide.
You need to group your script and status like this,
while($row = $getFamily->fetch(PDO::FETCH_ASSOC))
{
$status[] = $row['status'];
$scripts[] = $row['script'];
}
print_r($scripts);
print_r($status);

PHP MySQLi while loop logic

I have switched over to the mysqli_ extension for PHP, and I have ran into a bit of an issue.
I have 2 databases. 1 database I am only allowed read privileges, the other I have all privileges. My end goal is to read what I need from database 1, and put it in a table in database 2.
I use a join on database 1 to get all the information I need. I then loop through the results with a while loop. I have a unique id (domainid) in both databases. Where I am encountering the issue is inside the while loop once I have the domainid from the read-only database, I need to check if it exists inside my all-privileges database. I am just unsure of how to accomplish this?
Here is the code:
require 'db/connect.php';
require 'db/connect2.php';
if($result = $db->query("
SELECT tblhosting.domain as domain, tblhosting.id as domainid, tblclients.email as email
FROM tblhosting
LEFT JOIN tblclients ON
tblclients.id = tblhosting.userid
")){
if ($count = $result->num_rows) {
while($row = $result->fetch_object()){
$domainid = $row->domainid;
$domain = $row->domain;
$email = $row->email;
$result2 = $db2->prepare("SELECT domainid FROM information WHERE domainid = ?");
$result2->bind_param('i', $row->domainid);
$result2->execute();
$result2->bind_result($domainid2);
//$result2->fetch();
while($row2 = $result2->fetch_object()){
$domainid2 = $row2->domainid;
if ($domainid == $domainid2) {
echo "Information exists in both Databases", '<br>';
}
else{
echo "New Information Added to Database 2", '<br>';
}
}
}
}
}
This is what I have tried, but was unsuccessful.
EDIT
Second attempt putting the results into an array then looping through them. The array is correct when I print them out. The issue is with the 2nd execute(); command.
$result = $db->query("
SELECT tblhosting.domain as domain, tblhosting.id as domainid, tblclients.email as email
FROM tblhosting
LEFT JOIN tblclients ON
tblclients.id = tblhosting.userid
");
$domainid_arr = array();
while($row = $result->fetch_object()){
$domainid_arr[] = array(
'domainid' => $row->domainid,
'domain' => $row->domain
);
}
foreach ($domainid_arr as $d) {
echo $d['domainid'], $d['domain'], '<br>';
$result2 = $db2->prepare("SELECT domainid FROM information WHERE domainid = ?");
$result2->bind_param('i', $d['domainid']);
$result2->execute();
$result2->bind_result($domainid2);
while($row2 = $result2->fetch_object()){
$domainid2 = $row2->domainid;
if ($d['domainid'] == $domainid2) {
echo "Information exists in both Databases", '<br>';
}
else{
echo "New Information Added to Database 2", '<br>';
}
}
}

Grouping row elements into one column using SQL

My current table is fetching content from the database like this but I would like to combine the rows so that all the Room Preference's are displayed in one row rather than over several. How can I go about doing this? As a result the table below would have only two rows.
The Room Preference information is being inferred from ts_roompref.
Here is my code so far:
$sql = "SELECT
*
FROM ts_request
INNER JOIN ts_day
ON ts_request.day_id = ts_day.id
INNER JOIN ts_period
ON ts_request.period_id = ts_period.id
INNER JOIN ts_allocation
ON ts_request.id = ts_allocation.request_id
INNER JOIN ts_roompref
ON ts_request.id = ts_roompref.request_id
WHERE ts_request.round=:round
AND ts_request.dept_id=:dept
ORDER BY ts_request.module_id ASC";
}
$stm = $pdo->prepare( $sql );
$stm->execute( array( ':round' => 'P', ':dept' => $loggedin_id ) );
$rows = $stm->fetchAll();
foreach ($rows as $row)
{
echo '<tr align="center">';
echo '<td>'.$row['module_id'].'</td>';
echo '<td>'.$row['day'].'</td>';
echo '<td>'.$row['period'].'</td>';
echo '<td>';
if ($row['room_id']=="0")
{
echo "Any";
}
else
{
echo $row['room_id'];
}
echo '</td>';
echo '<td>'.$row['status'].'</td>';
echo '</tr>';
Well, I guess your trying to do it in SQL, but if you wanted to do it in your PHP you could loop over the rows watching for changes to Module Code. Pseudo code something like...
$newrows = array()
$tmpCode = ""
foreach $rows as $row
if $tmpCode != $row['module_code'] {
$tmpCode = $row['module_code']
$newrows[] = $row
} else {
$newrows[count($newrows) - 1]['room_preference'] .= $row['room_preference']
}
}
...rough, but you get the idea.
If you want to do it in SQL, can't you do a GROUP_CONCAT on room_preference and GROUP BY the other 4 fields?

Returning each unique user from a MySQL table and also the count of the number of rows for each user

I am using the following MySQL query to generate a table for users in a database. The query is designed to just return one row for each user, even though there are multiple rows for each user. This works fine, however I also need to calculate the number of unique entries for each user, to enter into the table where it states HERE. Do I need to use another query to return the count for all entries, and if so how do I integrate this with the code I already have?
$query="SELECT from_user, COUNT(*) AS num FROM tracks GROUP BY from_user ORDER BY COUNT(*) DESC";
$result=mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$user = $row['from_user'];
echo "<tr>";
echo "<td>".$user."</td>";
echo "<td>uploads (**HERE**)</td>";
echo "<td>favourites (count)</td>";
echo "</tr>";
}
?>
</table>
Because you've already created the custom field 'num', you can use that to get the count!
Add the following line after user = ...
$count = $row['num'];
Then you can
echo "<td>uploads ($count)</td>";
It miss your table stucture to know your field name, but, if i well understand your question you can use count + distinct in mysql.
You can check this answer too.
SELECT DISTINCT(from_user) AS user,
COUNT(from_user) AS num
FROM tracks
GROUP BY from_user
ORDER BY num DESC";
For the second problem you can doing a second query, or do a join tracks .
I think, in your case it's easier to you to do se second query inside the loop to get all detail from 'user' result.
$query1="SELECT DISTINCT(from_user), COUNT(*) AS num
FROM tracks
GROUP BY from_user
ORDER BY COUNT(*) DESC";
$query2="SELECT * FROM tracks";
$result1=mysql_query($query1) or die(mysql_error());
$result2=mysql_query($query2) or die(mysql_error());
$user_array = array();
while ($row = mysql_fetch_array($result1)) {
$user = $row['from_user'];
$num = $row['num'];
$uploads_array = array();
while ($sub_row = mysql_fetch_array($result2)) {
if( $sub_row['from_user'] == $user ) {
//for example only due to the unknown structure of your table
$uploads_array[] = array(
"file_name" => $sub_row['file_name'],
"file_url" => $sub_row['file_url']
);
}
}
$user_array[] = array(
"name" => $user,
"num_entry" => $num,
"actions" => $uploads_array
);
}
// now the table with all data is stuctured and you can parse it
foreach($user_array as $result) {
$upload_html_link_arr = array();
$user = $result['name'];
$num_entry = $result['num_entry'];
$all_actions_from_user_array = $result['actions'];
foreach($all_actions_from_user_array as $upload) {
$upload_html_link_arr[] = sprintf('%s', $upload["file_url"],$upload["file_name"]);
}
$upload_html_link = implode(', ',$upload_html_link_arr);
$full_row = sprintf("<tr><td>%s</td><td>uploads : %s</td><td>favourites (%d)</td></tr>", $user, $upload_html_link, $num_entry);
// now just echo the full row or store it to a table for the final echo.
echo $full_row;
}
I hope this help, mike

Join two MySQL tables and group result with php

I have the following code to populate cities in a table.
$cities_query = "SELECT city_name FROM city_selection";
$cities_result = mysql_query($cities_query);
echo "<table>";
while ($row = mysql_fetch_assoc($cities_result))
{
echo "<tr>";
echo "<td>".$row['city_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
Now I need to group every city by a region so I created the table called city_region_selection and added a Foreign key from the new column "region_id" in the city_selection table to region_id in the new table.
I'm now struggling to present this data in a nice html table using PHP.
Is it even possible to populate first a table row with region_name and then some subrows containing cities from that region? Please see this image for details:
You just have to do a little preprocessing:
/* SQL
SELECT
city_name,
region_name
FROM
city_selection
NATURAL JOIN city_region_selection
SQL */
$regions = array();
while ($result->fetch()) {
if (!isset($regions[$result->region_name])) {
$regions[$result->region_name] = array();
}
$regions[$result->region_name][] = $result->city_name;
}
Alternate Method with SQL focus
/* SQL
SELECT
region_name,
GROUP_CONCAT(city_name SEPARATOR ',') cities
FROM
city_selection
NATURAL JOIN city_region_selection
GROUP BY
region_name
*/
$regions = array();
while ($result->fetch()) {
$regions[$result->region_name] = explode(',', $result->city_name);
}
Help
Note that the while syntax is just abridged. You would probably replace it with
while ($row = mysql_fetch_assoc($cities_result)) {
$regions[$row['region_name']] = explode(',', $row['city_name']);
}
... for example
Once regions is built, simply do this:
foreach ($regions as $region => $cities) {
echo "<tr><td>$region</td></tr>";
foreach ($cities as $city) {
echo "<tr><td class="tabbed">$city</td></tr>";
}
}

Categories