PHP code won't pull database information - php

My current program, for some reason, won't register my database values even though my previous code(looks identical but from different database tables) works just fine.
So far I have no errors when it runs. The only thing that prints for each page is the table's title. Also the clients page works just fine. So the product(tv, cell, computer) and transaction page are my current issue.
My current index.php file (main program) is as follows:
<?php
//url /index.php?action=clients
include('header.php'); // create top box
include('sidemenu.php'); // create side menu
//database connection
include('pdo_connect.php');
//Read data type
$type = "";
if (isset($_REQUEST['action']))
$type = $_REQUEST['action'];
//echo 'Action: {$type}';
switch($type) {
case 'products' : //display a list of clients
//define sql
$sql = "SELECT product_type, product_title, product_description, unit_price FROM products
WHERE product_type = :product_type";
$values = array(':product_type'=>$_GET['product_type']);
$products = getAll($sql);
//display result
displayProductList($products);
break;
case 'clients' : //displaya list of movies
$sql = "SELECT first_name, last_name, email FROM p_clients";
$clients = getAll($sql);
displayClientList($clients);
break;
case 'transactions' :
$sql = "SELECT products.product_title, products.product_description, products.unit_price, p_clients.first_name,
p_clients.last_name, sales.quantity FROM p_clients INNER JOIN sales, products ON p_clients.client_id = sales.client_id
AND products.product_id = sales.product_id";
$transactions = getAll($sql);
displayTransactionList($transactions);
break;
default:
defaultView();
break;
}
include('footer.php');
function defaultView() {
?>
<!-- add page content -->
<div id='content'>
<h2>Welcome to our movie store</h2>
</div>
<div id = 'image'></div>
<div id = 'box'>
<p id = 'text-box'>
We appreciate your interest in our products and services. Please reference
the the links provided to see our current specials for each of our clients.
</p>
</div>
<?php
}
function displayProductList($products) {
echo "<div id='content'>
<h2>List of Products</h2>";
echo "<table id = clients>";
echo "<tr><td id = 'title'>Product Name</td><td id= 'title'>Description</td><td id = 'title'>Cost</td></tr>";
//display each record
for ($i = 0; $i < count($products); $i++){
echo "<tr><td>{$products[$i]['product_title']} </td><td> {$products[$i]['product_description']} </td><td>
{$products[$i]['unit_price']} </td></tr>" ;
}
echo "</table>";
echo "</div>";
}
function displayClientList($clients) {
echo "<div id='content'>
<h2>List of Clients</h2>";
echo "<table id = 'long'>";
// echo "<table>";
echo "<tr><td id = 'title'>First Name</td><td id= 'title'>Last Name</td><td id = 'title'>Email</td></tr>";
//display each record
for ($i = 0; $i < count($clients); $i++){
echo "<tr><td>{$clients[$i]['first_name']}</td><td> {$clients[$i]['last_name']}
</td><td> {$clients[$i]['email']} </td></tr>";
}
echo "</table>";
echo "</div>";
}
function displayTransactionList($transactions) {
echo "<div id='content'>
<h2>List of Client Transactions</h2>";
echo "<table id = 'long'>";
// echo "<table>";
echo "<tr><td id = 'title'>First Name</td><td id= 'title'>Last Name</td><td id = 'title'>Product Title</td>
<td id = 'title'>Product Description</td><td id = 'title'>Cost</td><td id = 'title'>Quantity</td></tr>";
//display each record
for ($i = 0; $i < count($transactions); $i++){
echo "<tr><td>{$transactions[$i]['first_name']}</td><td> {$transactions[$i]['last_name']}
</td><td> {$transactions[$i]['product_title']} </td><td> {$transactions[$i]['product_description']} </td><td>
{$transactions[$i]['unit_price']} </td><td> {$transactions[$i]['quantity']} </td></tr>";
}
echo "</table>";
echo "</div>";
}
function getAll($sql, $values =null){
global $db;
$statm = $db->prepare($sql);
//Method 4
//assign a value to named parameters using an array
//$values= array(':genre'=>'drama');
$statm->execute($values);
//Fetch all records
$result = $statm->fetchAll();
return $result;
}
The sidemenu.php file calls each one from links:
<div id = 'sidebar'>
<h4>Links</h4>
<ul id = "nav" class= "text-left">
<li><a href='index.php'>Home</a></li>
<li><a href='index.php?action=products&product_type=tv'>TV Products</a></li>
<li><a href='index.php?action=products&product_type=cell'>Cell Phone Products</a></li>
<li><a href='index.php?action=products&product_type=computer'>Computer Products</a></li>
<li><a href='index.php?action=clients'>List of Customers</a></li>
<li><a href='index.php?action=transactions'>List of Transactions</a></li>
<!--<li><a href='index.php?action=moviesFS&genre=sci-fi&date_out=2009-12-15'>List of Favorite Sci-Fi Movies</a></li>-->
</ul>
</div>
As you can see, if I type my sql into my database it works just fine:

Try changing
$products = getAll($sql);
to
$products = getAll($sql,$values);
inside case 'products' :

Related

Selecting one row from database then other rows for tabs active issue

I am setting a page that contains a tablist imported from database, the problem is that I want the 1st tab to be class='active' but when I add the class inside the while loop it take the class for all panels
Is there a way to select the 1st row only and give it the active class then select the other rows without it?
my code will describe it
<?php
$str_trans = "";
$str_poem = "";
$ebody_import_query = mysqli_query($con, "SELECT * FROM ebody WHERE epoem_ie='$ie' ORDER BY rand()");
if(mysqli_num_rows($ebody_import_query) > 0) {
while ($row = mysqli_fetch_array($ebody_import_query)) {
$id = $row['id'];
$translator = $row['translator'];
$title = $row['title'];
$body = $row['body'];
$str_trans .= "
<li role='presentation'><a style='padding: 5px; font-size: 14px;' href='#$translator' aria-controls='$translator' role='tab' data-toggle='tab'>$translator</a></li>
";
$str_poem .= "
<div role='tabpanel' class='tab-pane' id='$translator'>
<div>
<u><b class='poemname'>$title</b></u>$body<br>
<a style='margin-bottom: 10px;' href='translator.php?translator=$translator '><u><b>(جميع ترجمات $translator_name)</b></u></a>
<hr></div>
</div>
";
}
}
?>
<div class='status_post' >
<div class='profile_main_column column ' style='margin-top: 10px; '>
<ul class='nav nav-tabs' style='margin-bottom: 10px; ' role='tablist' id='profileTabs'>
<?php echo $str_trans; ?>
</ul>
<div class='tab-content'>
<?php echo $str_poem; ?>
</div>
Using a counter when you fetch the result of the query.
$counter = 0;
if($counter === 0)
echo "<div class='active'></div>"
else
echo "<div></div>"
And at the end of your cicle you increment the counter, so that the active class is assigned only the first time.

Select multiple rows from multiple tables and print all withe php while loop

i have 3 table T1, T2, T3,
so, in T1 i want to select 1st row and select from T2 the rows related to the row selected in T1, and select from T3 rows related to T2 how have relation with row selected in T1 and print all this in one continer withe php while loop function
see the images for more descriptions
Base on what I understand with your question. This could be the answer
<?php
$db = new PDO("mysql:host=localhost", "username", "password");
$q1 = $db->prepare("SELECT * FROM T1");
$q1->execute();
$f1 = $q1->fetchAll(PDO::FETCH_ASSOC);
foreach ($f1 as $f1_items) {
echo "<tr><td>".$f1['id_cat']."</td></tr>";
$q2 = $db->prepare("SELECT * FROM T2 WHERE id_cat = ".$f1['id_cat'].";");
$q2->execute();
$f2 = $q2->fetchAll(PDO::FETCH_ASSOC);
foreach ($f2 as $f2_items) {
echo "<tr><td>\t".$f2['id_tr']."</td></tr>";
$q3 = $db->prepare("SELECT * FROM T3 WHERE id_tr = ".$f2['id_cus'].";");
$q3->execute();
$f3 = $q3->fetchAll(PDO::FETCH_ASSOC);
foreach ($f3 as $f3_items) {
echo "<tr><td>\t\t".$f2['id_cus']."</td></tr>";
}
}
}
?>
Solved and this is the code i am happy :)
$ReqFindRows = "SELECT * FROM commandes WHERE commande_status = 0 AND date(commande_le) = CURDATE()";
$STMTFindRows = $connect->stmt_init();
if(!$STMTFindRows->prepare($ReqFindRows)){
echo "No Results";
}
else {
$STMTFindRows->execute();
$ResultsFindRows = $STMTFindRows->get_result();
$x = 0;
while($ArrayCat = $ResultsFindRows->fetch_assoc()){
switch($ArrayCat['commande_importance']){
case 0 :
$importance = 'Normal';
$bgclas = "bg-blue";
break;
case 1 :
$importance = 'Urgent';
$bgclas = "bg-yellow";
break;
case 2 :
$importance = 'Immediat';
$bgclas = "bg-red";
break;
};
$prods = array();
$GetProductsInCommandeQuery = "SELECT * FROM commandes_produits WHERE commande_id = ?";
$GetProductsInCommandeSTMT = $connect->stmt_init();
if(!$GetProductsInCommandeSTMT->prepare($GetProductsInCommandeQuery)){
echo $connect->error;
}
else {
$id_toserch = $ArrayCat["commande_id"];
$GetProductsInCommandeSTMT->bind_param("s", $id_toserch );
$GetProductsInCommandeSTMT->execute();
$GetProductsInCommandeResults = $GetProductsInCommandeSTMT->get_result();
$Prodss = "";
while($GetProductsInCommandeArray = $GetProductsInCommandeResults->fetch_array()){
$prods = $GetProductsInCommandeArray["recette_id"];
$GetSupQuery = "SELECT * FROM commandes_supp WHERE tr_number = ? AND commande_id = ?";
$GetSupSTMT = $connect->stmt_init();
if(!$GetSupSTMT->prepare($GetSupQuery)){
echo $connect->error;
}
else {
$trNumber = $GetProductsInCommandeArray["tr_number"];
$GetSupSTMT->bind_param("ss", $trNumber, $id_toserch );
$GetSupSTMT->execute();
$GetSupResults = $GetSupSTMT->get_result();
$Supp = "";
while($GetSupArray = $GetSupResults->fetch_array()){
$Suppss = $GetSupArray["supp_id"];
$Supp .= '<p style="color:#F00">'.$Suppss.' </p>';
}
}
$Prodss .=
'<tr>
<td>
'.$prods.'
'.$Supp.'
</td>
<td>
A table
</td>
<td>
<button type="button" class="btn btn-sm">Servis</button>
</td>
</tr> ';
}
}
?>
<div class="col-xs-6 col-md-4" style="margin-bottom:10px;">
<div class="tiket">
<div class="tikeheader <?php echo $bgclas ?>">
<span class="commandenumber">
<i class="fa fa-star iconheader">
</i>
<?php echo $ArrayCat["commande_id"] ?> A Table
</span>
<span class="importance">
<?php echo $importance?>
</span>
</div>
<div class="tiketbody">
<table class="tiketbodytable">
<tbody>
<?php echo $Prodss ?>
</tbody>
</table>
</div>
</div>
</div>
<?php
}
}
?>
</div>
</div>
</div>
</div>
<?php
}
?>

Left-join foreach loop over array with nested array

I have two tables one for users and one for their reviews. On one page I need to show thumbnails of each user and the reviews that match that user. The problem is the LEFT JOIN creates a row for every time there is a review. So if a user has two reviews they are showing up twice in the list of thumbnails. Do I need a loop inside the loop? Everything I can think of seems really clunky. Thanks.
// Get Data
$qry = "SELECT * FROM `users` LEFT JOIN `reviews` ON users.userId = reviews.user_id WHERE installation_id = $installation_id";
$res = mysqli_query($mysqli, $qry) or die('-1'.mysqli_error($mysqli));
//$uqry = "SELECT membership FROM users WHERE userId = $uid";
//$current_user = mysqli_query($mysqli, $uqry) or die('-1'.mysqli_error($mysqli));
$getUser = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT membership FROM users WHERE userId = $uid"));
$currentUserLevel = $getUser['membership'];
?>
<div class="container">
<div class="content">
<?php if ($msgBox) { echo $msgBox; } ?>
<div class="row">
<?php $lists = array();
while($list = mysqli_fetch_assoc($res)) {
$lists[] = $list;
}
foreach($lists as $list) {
$name = stripslashes($list['usersName']);
$bio = stripslashes($list['usersBio']);
$review = stripslashes($list['comments']);
$stars = stripslashes($list['stars']); ?>
<div class="col-md-4">
<div id = "user-square">
<div class="avatar">
<img src="<?php echo $avatarDir.$list['usersAvatar']; ?>" class="publicAvatar" />
</div>
Name:<?php echo $name; ?> <br />
Bio:<?php echo $bio; ?> <br />
Review:<?php echo $review; ?> <br />
Stars: <?php echo $stars; ?> <br />
<?php
if ($currentUserLevel == 'pro') {
echo 'CONTACT SCOUT';
}
else {
echo 'Sorry you must upgrade to a Pro membership to contact this Scout';
}
?>
</div>
</div>
<?php }
?>
</div>
</div>
</div>
</div>
Change the while loop to the following:
while($list = mysqli_fetch_assoc($res)) {
$lists[$list['usersName']][$list['usersBio']][$list['stars']][] = $list['comments'];
}
That will give you a nice multidimensional array with the user name as the first key, and all that users reviews ordered by star rating. You should probably use a unique key rather than the users name as there could be duplicates, so either the email or unique row ID would be better.
You can then (VERY basic example):
$reviews = "";
foreach($lists as $username => $array) {
foreach($array as $bio => $array2) {
$name = stripslashes($username);
$bio = stripslashes($bio);
foreach($array2 as $stars => $comments_array) {
$stars = stripslashes($stars);
foreach($comments_array as $comments) {
$reviews .= $stars . " - " . stripslashes($comments) . "<br />";
}
}
// Your HTML here using $name, $bio, and $reviews(which will be star rating followed review for that user each on a new line)
echo '
<table width="400">
<tr>
<td>' . $name . '</td><td>' . $bio . '</td><td>' . $reviews . '</td>
</tr>
</table>
';
}
$reviews = "";
}

links php mysql pagination not working

i'm trying to paginate my results, the limit is working, the number of pages is properly set, but the links of the pagination don't work, i've been looking for a while and nothing, ¿can you take a look and tell me what i'm doing wrong? thanks
<?php
include("config/conexion.php");
$limit = 3;
if(isset($_GET['pag'])){
$pag= $_GET['pag'];
}else{
$pag=1;
}
$offset = ($pag-1) * $limit;
$sql = "SELECT SQL_CALC_FOUND_ROWS id, nombre, local, telefono, celular, email FROM almacenes WHERE id_cat = '".$_GET["id"]."'";
$sqlTotal = "SELECT FOUND_ROWS() as total";
$currentid = $_GET["id"];
$rs = mysql_query($sql);
$rsTotal = mysql_query($sqlTotal);
$rowTotal = mysql_fetch_assoc($rsTotal);
// Total de registros sin limit
$total = $rowTotal["total"];
?>
<?php if($_GET["id"]){ $cat = mysql_query("SELECT * FROM almacenes WHERE id_cat = '".$_GET["id"]."' ORDER BY id ASC LIMIT $offset, $limit"); if(mysql_num_rows($cat)>0){
while($row = mysql_fetch_object($cat)){ ?>
<div class="almacenbox">
<div class="shadow"></div>
<div class="white">
<div class="image"><img src=almacenes/local_111.jpg></div>
<div class="title"><?php echo $row->nombre?></div>
<div class="text">Local: <?php echo $row->local?></div>
<div class="text">Teléfono: <?php echo $row->telefono?></div>
<div class="text">Celular: <?php echo $row->celular?></div>
<div class="text"><?php echo $row->email?></div>
</div>
</div>
<?php } ?>
<?php } }else{ echo "<p>No hay resultados para mostrar</p>"; }?>
<table border="1" bordercolor="#000">
<tfoot>
<tr>
<td colspan="2">
<?php
$totalPag = ceil($total/$limit);
$links = array();
for( $i=1; $i<=$totalPag ; $i++)
{
$links[] = "<a href=almacenes.php?id=$currentid?pag=$i\>$i</a>";
}
echo implode(" - ", $links);
?>
</td>
</tr>
</tfoot> </table>
$links[] = "<a href=almacenes.php?id=$currentid?pag=$i\>$i</a>";
Should be
$links[] = '$i';
Query strings start with a ? but any name-value pairs after that first one require an ampersand.
On a side note you should never place user data directly into your query. This leaves you open to an SQL injection attack. Consider using mysql_real_escape_string or switching to the mysqli library.

Php foreach echo issue

I have this code which produces me a number which is equal to the number of id's i've got in my database of star rating system.
This code generates me a five star voting for each id i've got, but the problem is, it generates them all in a div, while i need them specifically in different div's. let's suppose i print out in a div information for each hostess i've got, i print out their photo and name with the following code:
$sql =" select * from hostess";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo "<div id='photo'>";
echo "<div id='picture'>";
echo "<div id='scotch'><img src='images/Scotch.png'></div>";
echo "<td> <img src=foto/photo1/".$row['photo'] . "></td>";
echo "</div>";
echo "<div id='text'>";
echo '<td>'. $row['first_name_en']." ". $row['family_name_en']."</td>";
echo "</div>";
echo "</div>";
echo "<div id='photo2'>";
echo "<div id='picture'>";
echo "<div id='notes'>";
echo '<form action="index.php" method="post" >';
echo "<label>Notes</label></br><textarea>".$row['courrent_occupation'] . "</textarea></br>";
echo '<input type="submit" value="edit" name="edit"></div>';
echo "</div>";
echo "<div id='notes'>";
echo "<label>profile</label></br><textarea>".$row['profile_en'] . "</textarea>";
echo "</div>";
echo "</div>";
}
?>
</div>
Now, i've got this other php which generates me all the star ratings for all hostess id's
<?php
// include update.php
include_once 'update.php';
// get all data from tabel
$arr_star = fetchStar();
?>
<?php
// start looping datas
foreach($arr_star as $star){ ?>
<h2>Star Rater - <?php echo $star['id'];?></h2>
<ul class='star-rating' id="star-rating-<?php echo $star['id'];?>">
<?php /* getRating($id) is to generate current rating */?>
<li class="current-rating" id="current-rating-<?php echo $star['id'];?>" style="width:<?php echo getRating($star['id'])?>%"><!-- will show current rating --></li>
<?php
/* we need to generate 'id' for star rating.. this 'id' will identify which data to execute */
/* we will pass it in ajax later */
?>
<span class="ratelinks" id="<?php echo $star['id'];?>">
<li>1</li>
<li>1.5</li>
<li>2</li>
<li>2.5</li>
<li>3</li>
<li>3.5</li>
<li>4</li>
<li>4.5</li>
<li>5</li>
</span>
</ul>
<?php } ?>
What i need is to assign each hostess profile i print their system rating.
I try to insert the foreach inside the first script but it then shows me just one profile, not all profiles.
The fetchstar() code is:
function fetchStar(){
$sql = "select * from `hostess`";
$result=#mysql_query($sql);
while($rs = #mysql_fetch_array($result,MYSQL_ASSOC)){
$arr_data[] = $rs;
}
return $arr_data;
}
First, you probably shouldn't use SELECT *. That aside I would combine the two queries you have to return a multidimensional array with MySQL and then use nested for each loops to echo out the data you want.
Someone answered a similar question for me here.
Looping through MySQL left join in php vs. 2 separate queries
$sql =" select * from hostess";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
if ($lastID <> $row['id']) {
$lastID = $row['id'];
$hostess[$lastID] = array('id' => $row['id'],
'first_name_en' => $row['first_name_en'],
etc
'arr_star' => array() );
}
$hostess[$lastID]['arr_star'][] = array('star_id' => $row['star_id'] etc);
}
Then you would use nested for each statements
for each($row as $rows){
//echo your hostess information
for each ($arr_star as $star){
//echo your star rating information
}
}

Categories