Displaying values from mysqli with loop - php

I need to be able to display the course_desc on line 30, beside the course_name.
<?php
$result = $db->query("select distinct c.dbid, c.course_name, c.course_image, m.module_id, m.module_name, m.module_name_id, m.module_image, m.hasFiles, m.files from courses c join modules_to_courses mc on (c.dbid = mc.courses_id) join modules m on (mc.modules_id = m.module_id)");
$course_name = $db->query("SELECT distinct course_name, course_desc FROM courses");
while ($temp = $course_name->fetch_assoc()) {
$courses[] = $temp['course_name'];
}
$final = array();
// Retrieve results
while ($row = $result->fetch_assoc()) {
// Add to final array via counter if valid course is found
if (in_array($row['course_name'], $courses)) {
$final[$row['course_name']][] = $row;
}
}
// Display if final array is not empty
if (!empty($final)) {
// Loop through each potential course name
foreach ($courses as $name) {
// Output if the course has values within the final array
if (array_key_exists($name, $final)) {
echo '<div>'."\n";
echo ' '. $name . "\n";
echo '<!-- list of modules -->'."\n";
// Loop through internal values
foreach ($final[$name] as $value) {
$module_name = $value['module_name'];
echo ' '. $module_name ."\n";
}
echo ' </div>'."\n";
}
}
}
?>

You already having your course description in $final so you can access it using,
$final[$name]['course_desc']
I have created a paste based on your with changes. Also note that it's need to change your $final array.

distinct course_name, course_desc means you are trying to fetch the values regarding to distinct course_name and distinct course_desc together. You may wanna use group by instead. If I understood correctly, your statement will not bring you distinct course names and their related course desc. (if that is what you want)

Related

fetch and check cart data with php mysql

I had cart data in session like product_id, product_name, product_price..... so there is multiple data in session with array it's not fixed..sometime single data and sometime morethan one..... but when customer check out.... I need to check each product with customers entered pincode …..and products have multiple or single pincode in table....so we can get them by session product_id ..... then want to check if those pin match with client/user pincode then store in new session and those products which are not match yet....also move in another new session..... or just want to display product like allowed or not allowed product for this pin
is there any way to make it simple ? i think it's work with foreach inside condtions and all..but still confused.....sorry for bad english !
i had just wrote little code but confused what to next ?
if (!empty($_SESSION["shopping_cart"])){
foreach ($_SESSION["shopping_cart"] as $keys => $value){
$pro_session_id = $_SESSION["shopping_cart"][$keys]['product_id'];
$select_price_data = mysql_query("select * from product_pincode where product_ID = '$pro_session_id'");
}
}
if (!empty($_SESSION["shopping_cart"])) {
foreach ($_SESSION["shopping_cart"] as $keys => $value) {
$pro_session_id = $_SESSION["shopping_cart"][$keys]['product_id'];
// echo $pro_session_id;
// echo "<br>";
// $select_pin_data = mysql_query("select * from product_pincode where product_ID = '$pro_session_id'");
$select_pin_query = "SELECT * FROM product_pincode WHERE product_ID = '$pro_session_id'";
$selected = mysql_query($select_pin_query, $con) or die(mysql_error($con));
$pin_val = array();
while ($get_pin_data = mysql_fetch_assoc($selected)) {
$pin_val[] = $get_pin_data;
}
foreach ($pin_val as $get_pin_data) {
if ($get_pin_data['pincode_number'] == $_SESSION["order_placement_details"][0]['user_pincode']) {
echo "Complete " . $get_pin_data['pincode_number'];
echo "<br>";
} else {
echo "unallowed" . $get_pin_data['pincode_number'];
echo "<br>";
}
}
}

Excluding row in database with != in PDO query

I'm trying to exclude certain rows with a PDO query but it is not returning the right value and I'm not seeing my error maybe some of you can help me.
This is the first query that works.
$objGetRecievedChat = $objDatabaseMessages->prepare('SELECT * FROM messages WHERE recieverid = :recieverid GROUP BY chatid');
Now I want to exclude the chatid's that I get from this query.
foreach ($getRecievedChatFtch as $chatid) {
echo $chatid['chatid'] . '<BR>';
}
When I echo the above I get the next result:
20920
81586
Wich is correct I want to exclude those two values so I execute the next query:
$objGetSendChat = $objDatabaseMessages->prepare('SELECT * FROM messages WHERE ownerid = :ownerid AND chatid != :chatid GROUP BY chatid');
foreach ($getSendChat as $key ) {
echo $key['chatid'] . '<BR>';
}
But when I echo the above I get the next values
44495
20920
44495
this value 44495 is correct although I only need it once (that is why I GROUP BY chatid) But the value 20920 is one of the values I need to exclude.
Does anyone know what I'm doing wrong?
Thanks in advance!
Whole code:
//Voor de berichten die je hebt ontvangen.
$objGetRecievedChat = $objDatabaseMessages->prepare('SELECT * FROM messages WHERE recieverid = :recieverid GROUP BY chatid');
$objGetRecievedChat->bindParam('recieverid', $member_id);
$objGetRecievedChat->execute();
$getRecievedChatFtch = $objGetRecievedChat->fetchAll(PDO::FETCH_ASSOC);
//Dit is voor verzonden berichten.
foreach ($getRecievedChatFtch as $chatid) {
echo $chatid['chatid'] . '<BR>';
$objGetSendChat = $objDatabaseMessages->prepare('SELECT * FROM messages WHERE ownerid = :ownerid AND chatid NOT IN(:chatid) GROUP BY chatid');
$objGetSendChat->bindParam('ownerid', $member_id);
$objGetSendChat->bindParam('chatid', $chatid['chatid']);
$objGetSendChat->execute();
$getSendChat = $objGetSendChat->fetchAll(PDO::FETCH_ASSOC);
foreach ($getSendChat as $key) {
echo $key['chatid'] . '<BR>';
}
}
Change query to catid NOT IN (xxxx,xxxx).
You're making it wrong: in your foreach loop, you retrieve ALL rows BUT the current one. You must put the query out of the foreach and use a WHERE IN
//Voor de berichten die je hebt ontvangen.
$objGetRecievedChat = $objDatabaseMessages->prepare('SELECT * FROM messages WHERE recieverid = :recieverid GROUP BY chatid');
$objGetRecievedChat->bindParam('recieverid', $member_id);
$objGetRecievedChat->execute();
$getRecievedChatFtch = $objGetRecievedChat->fetchAll(PDO::FETCH_ASSOC);
//Dit is voor verzonden berichten.
$chatids = array();
foreach ($getRecievedChatFtch as $chatid) {
echo $chatid['chatid'] . '<BR>';
$chatids = $chatid['chatid'];
}
$placeholders = implode(',', array_fill('?', count($chatids)));
$objGetSendChat = $objDatabaseMessages->prepare('SELECT * FROM messages WHERE ownerid = ? AND chatid NOT IN(' . $placeholders . ') GROUP BY chatid');
$objGetSendChat->execute(array_merge(array($ownerid, $chatids)));
$getSendChat = $objGetSendChat->fetchAll(PDO::FETCH_ASSOC);
foreach ($getSendChat as $key) {
echo $key['chatid'] . '<BR>';
}
More or less (because I dislike using WHERE IN with prepared statement. You usually can avoid them with JOIN.
$objGetSendChat = ...
While you use $getSendChat in the foreach.
So I feel we're missing some code here, that contains the error.
Plus, you do a GROUP BY chatid and you get 44495 twice in the result, so the result cannot be the query's one.

Include files in PHP

Thank you for reading this and for your help in advance.
I got a simple Book-Catalogue /procedure code/, every visitor can see the book catalogue and click through out the books and check their authors BUT I've got an idea to add a feature that allows the users to write a comment to each book ONLY if they're logged. So I added a session variable $_SESSION['isLogged']. But there is a lot of code blocks that duplicates. What I need is an advice, what to do with this duplicated blocks of code. What the good practice says? And my code below is from one of the 6 files that I got. In everyfile I got this repeating of code.
So here's my code:
if (!isset($_SESSION['isLogged'])) {
echo '<div class="user-navigation">
<a href="register.php" class="user-nav" >Register now</a>
Log in
</div>
<div class="navigation1">
Add book
Add author
</div>';
$booksAndAuthors = mysqli_query($connection, 'SELECT DISTINCT * FROM books LEFT JOIN books_authors ON books.book_id=books_authors.book_id LEFT JOIN authors ON authors.author_id=books_authors.author_id');
$result = array();
while ($resultArr = mysqli_fetch_assoc($booksAndAuthors)) {
$result[$resultArr['book_id']] ['book_name'] = $resultArr['book_title']; // Reodering array
$result[$resultArr['book_id']] ['author'][$resultArr['author_id']] = $resultArr['author_name']; // Reordering array
}
echo '<table class="table"><tr><th>Book name</th><th>Author</th></tr>'; // Open table html table tags
foreach ($result as $k=>$b) { // Foreach the result array to get the book_name
echo '<tr><td>' . $b['book_name'] . '</td><td>';
$data = array(); // Create an empty array in order to fill the data inside
foreach ($b['author'] as $k => $a) { // Foreach the nested array with the authors to get the author_name displayed
$_GET['author_name'] = $a;
$data[] = '' . $a . ''; // Link is chosen by the author_id
}
echo implode(', ', $data); // Add a comma after every record
echo '</td></tr>'; // Close table cell and row
}
exit;
echo '</table>'; // Close html table tag
}
else {
echo '<div class="user-navigation">
My Profile
Log out
</div>
<div class="navigation2">
Add book
Add author
</div>';
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$booksAndAuthors = mysqli_query($connection, 'SELECT DISTINCT * FROM books LEFT JOIN books_authors ON books.book_id=books_authors.book_id LEFT JOIN authors ON authors.author_id=books_authors.author_id');
$result = array();
while ($resultArr = mysqli_fetch_assoc($booksAndAuthors)) {
$result[$resultArr['book_id']] ['book_name'] = $resultArr['book_title']; // Reodering array
$result[$resultArr['book_id']] ['author'][$resultArr['author_id']] = $resultArr['author_name']; // Reordering array
}
echo '<table class="table"><tr><th>Book name</th><th>Author</th></tr>'; // Open table html table tags
foreach ($result as $k=>$b) { // Foreach the result array to get the book_name
echo '<tr><td>' . $b['book_name'] . '</td><td>';
$data = array(); // Create an empty array in order to fill the data inside
foreach ($b['author'] as $k => $a) { // Foreach the nested array with the authors to get the author_name displayed
$_GET['author_name'] = $a;
$data[] = '' . $a . ''; // Link is chosen by the author_id
}
echo implode(', ', $data); // Add a comma after every record
echo '</td></tr>'; // Close table cell and row
}
echo '</table>'; // Close html table tag
}
*If my question is not properly asked or you have some notices.Please let me know!
* (=
Put this code in a file then include that file at the bottom of all of the pages.
For example put the code in isLogged.php
Then on each page where the code is duplicated replace it with:
include "isLogged.php";
include is what you're looking for.
You should create a file that contains your repeated code. functions.php for example.
Then call it with one of these methods.
include "functions.php"
http://php.net/manual/en/function.include.php
include_once("functions.php")
http://php.net/manual/en/function.include-once.php
require_once("functions.php")
http://php.net/manual/en/function.require-once.php
create a function of repeated block and call when it required or create a file with the set of repeated code and use any of include,include_once,require_once to add the file.for more detail see php manual for these functions.

PHP Getting SUM of Array Values While Comparing

I have an array of Information States And Totals. I want to see how to get the Total of all the Totals for each state.
I know I have to use a loop but I am not sure which - what would I do?
This is what I have so far. It's making the array from a database.
$WorkFind = mysql_query(
"SELECT Customers.State, WorkOrders.Total
FROM WorkOrders
INNER JOIN Customers
ON WorkOrders.CID=Customers.ID
WHERE WorkOrders.Type <> 'Warranty'
AND (WorkOrders.Status <> 'Closed'
OR WorkOrders.Status <> 'Cancelled')
AND WorkOrders.TransferID='0'
ORDER BY Customers.State ASC");
while ($Work = mysql_fetch_array($WorkFind)) {
}
The while loop has made the array but I'm unsure what to put into it.
I'm using PHP 5.3 and MYSQL 5.2
Try this:
$WorkFind = mysql_query("SELECT Customers.State AS State, WorkOrders.Total AS Total -- ...");
$total = array();
while ($Work = mysql_fetch_array($WorkFind)) {
$state = $Work['State'];
if (!isset($total[$state])) {
$total[$state] = 0;
}
$total[$state] += $Work['Total'];
}
// format as simple table
echo '<table><tr><th>State</th><th>Total</th></tr>';
foreach ($total as $state_name => $state_total) {
echo '<tr><td>' . $state_name . '</td><td>' . $state_total . '</td></tr>';
}
echo '</table>';

How to break down a php array with levels?

I have a MySQL table with stock information including what main industry sector and sub sector a stock belongs to (for example the Coca-Cola stock belongs to the industry sector "Consumer Goods" and to the sub sector "Beverages - Soft Drinks".
$SQL = "SELECT name, industrysector, subsector FROM Stocks WHERE economic_indicator_type = 'Stock' GROUP BY industrysector, subsector, name";
$result = mysql_query($SQL) or die ("Error in query: $SQL. " . mysql_error());
while ($row = mysql_fetch_row($result)) {
$stocks[$i]['name'] = $row[0];
$stocks[$i]['industrysector'] = $row[1];
$stocks[$i]['subsector'] = $row[2];
$i++;
}
$stocksTotals = array();
foreach($stocks as $amount) {
$stocksTotals[$amount['industrysector']] = $stocksTotals[$amount['industrysector']].", ".$amount['name'];
}
foreach($stocksTotals as $name => $amount) { echo $name.": ".substr($amount,1)."<br>"; }
My problem is that I don't get the code to handle the third level. I want to first output all of the industry sectors (Basic material for example), then all subsectors (Basic Resources for example) for each industry sector, then all names of the stocks corresponding to each subsector.
Currently I only get industry sector and then the stock name, because I fail to understand how to handle this in the array handling code.
Any advise would be highly appreciated! I have put a image here (http://imageshack.us/photo/my-images/853/mysqltophp.gif/) for better reference.
Thanks!
the foreach loop needs to be like this:
//considering you want the value as "$amount['industrysector'], $amount['name']"
foreach($stocks as $amount) {
// $stocksTotals[$amount['industrysector']] = $amount['industrysector'] .", ".$amount['name'];
echo $amount['industrysector'].": "."$amount['industrysector'], $amount['name']"."<br>";
}
you dont need another foreach loop.
Edit: you would need to change the way you fetch your rows too,
while ($row = mysql_fetch_assoc($result)) {
$stocks[$i]['name'] = $row['name'];
$stocks[$i]['industrysector'] = $row['industrysector'];
$stocks[$i]['subsector'] = $row['industrysector'];
$i++;
}
foreach($stocks as $amount) {
$output = "$amount['industrysector'] : $amount['industrysector'], $amount['subsector']";
if( $amount['name'] !== '' )
$output .= "<br>" . $amount['name'];
";
}

Categories