mysqli data fetch using explode no result getting - php

From table, i am fetching $rows['colorVariants']; but its value i am getting like:-
[JEADV9Q23ESG25HY,JEADV9Q2NFRNYV5Q,JEADV9Q2PNBTXGNX,JEADV9Q2XKWPXWSX,JEADY8ABWH9XNF4B,JEADZWEBDHWRJ2NQ,JEADZWEBRWZ4B4VS,JEADZWEBXDCGSYCF,JEAEYYX95YYC4DRA]
Then i used substr to remove square bracket.
Explode this value and again need to fetch it it the same table for similar products, but i am not getting any result.
<?php
$table = table1; // Table Name
$mysqli = mysqli connection // Mysqli Connection here
$result = $mysqli->query( "SELECT * FROM $table_name WHERE `id` = '$q' ");
while ( $rows = $result->fetch_assoc() ) {
$rows['colorVariants'] = [JEADV9Q23ESG25HY,JEADV9Q2NFRNYV5Q,JEADV9Q2PNBTXGNX,JEADV9Q2XKWPXWSX,JEADY8ABWH9XNF4B,JEADZWEBDHWRJ2NQ,JEADZWEBRWZ4B4VS,JEADZWEBXDCGSYCF,JEAEYYX95YYC4DRA] // Result Copy Sample
// substr using for remove square bracket
$colorVariants = substr($rows['colorVariants'], 1);
$newColorVariants = substr($colorVariants, 0, '-1');
$finalColorVariants = explode(',', $newColorVariants);
}
?>
<?php
for($i = 0; $i < count($finalColorVariants); $i++) {
$color = $finalColorVariants[$i];
$color = $mysqli->real_escape_string($color);
$colorVariants = $mysqli->query( "SELECT id,store,title,imageUrlStr,mrp,price,productBrand FROM $table_name WHERE `productId` = '".$color."' ");
if ($colorVariants) {
while ($rows = $colorVariants->fetch_assoc()) {
$id1 = $rows['id'];
$store1 = $rows['store'];
$title1 = $rows['title'];
$imageUrlStr1 = $rows['imageUrlStr'];
$mrp1 = $rows['mrp'];
$price1 = $rows['price'];
$productBrand1 = $rows['productBrand'];
}
?>
<div class="cloth-inner-similar-box">
<div class="cloth-inner-similar-boxin">
<img src="<?php echo $imageUrlStr1; ?>" />
</div>
<div class="cloth-inner-similar-boxin-offer">
<div class="cloth-inner-similar-boxin-offer-in">
<p>30% OFF</p>
</div>
</div>
<div class="cloth-inner-similar-boxin-head">
<?php echo $title1; ?>
</div>
<div class="cloth-inner-similar-price border-solid-bottom border-solid-top">
Best Buy # <?php echo $price1; ?>/-<?php echo $productBrand1; ?>
</div>
</div>
<?php
} }
$mysqli->close();
?>

Related

Nested while loop in PHP in getting data from database

<?php
$sqlquerypmenu = "select *
from subsubmenu
where submenu_id=1
and position='left'
and status=1";
if($querypmenu = sqlsrv_query($conn,$sqlquerypmenu)){
if(sqlsrv_has_rows($querypmenu) === true){
while($rowdata = sqlsrv_fetch_array($querypmenu, SQLSRV_FETCH_ASSOC)){
?>
<h4 class="title-small folder_name"> <?php echo $rowdata ['website_title']; ?> </h4>
<?php
$id = $rowdata['id'];
$filequerymenu = "select *
from upload_files
where main_menu='value_name'
and sub_menu='value_key'
and subsub_menu= $id ";
if($filemenu = sqlsrv_query($conn,$filequerymenu)){
if(sqlsrv_has_rows($filemenu) === true){
while($filedata = sqlsrv_fetch_array($filemenu, SQLSRV_FETCH_ASSOC)){ ?>
<a class="smalltext font_val" href="<?php echo DOCUMENT_URL.$filedata ['file_name']; ?> " target="_blank" ><?php echo $filedata['document_name']; ?></a>
<?php
}
}
}
}
}
}
?>
In the nested while loop the second while loop only shows the first row of data and does not show the rest of the data.
How can I fix this?
Consider querying the database once with one JOIN query. Possibly opening up another fetch within a while loop causes instances issues:
<?php
...
$sql = "select s.website_title, u.file_name, u.document_name
from upload_files u
inner join subsubmenu s ON u.subsub_menu = s.id
where u.main_menu = 'value_name'
and u.sub_menu = 'value_key'
and s.submenu_id = 1
and s.[position] = 'left'
and s.[status] = 1
order by s.id, s.website_title;"
$title = "";
if($result = sqlsrv_query($conn, $sql)){
if(sqlsrv_has_rows($result) === true){
while($rowdata = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
if($title != $rowdata['website_title']) {
$title = $rowdata['website_title']
?>
<h4 class="title-small folder_name"> <?php echo $rowdata ['website_title']; ?> </h4>
<?php
}
?>
<a class="smalltext font_val" href="<?php echo DOCUMENT_URL.$filedata ['file_name']; ?> " target="_blank" ><?php echo $filedata['document_name']; ?></a>
<?php
}
}
}
?>

How can echo 1 div differently from mysql data?

I have some sort of timeline on my page, and I am getting 3 late news from database like that:
<div id="timeline">
<?php
$SQLGetNews = $odb -> query("SELECT * FROM `news` ORDER BY `id` DESC LIMIT 3");
while ($getInfo = $SQLGetNews -> fetch(PDO::FETCH_ASSOC)) {
$name = $getInfo['name'];
/*It should be like that
<div class="left">'.$name.'</div>
<div class="right">'.$name.'</div>
I know that i have to echo it somehow by targeting first, second, third output?
*/
}
?>
</div>
So you want to print info like left then right then left aligned, You can do this like below.
<div id="timeline">
<?php
$SQLGetNews = $odb -> query("SELECT * FROM `news` ORDER BY `id` DESC LIMIT 3");
$i=1;
while ($getInfo = $SQLGetNews -> fetch(PDO::FETCH_ASSOC)) {
$name = $getInfo['name'];
if($i%2)
{
echo '<div class="right">'.$name.'</div>';
}
else
{
echo '<div class="left">'.$name.'</div>';
}
$i++;
/*It should be like that
<div class="left">'.$name.'</div>
<div class="right">'.$name.'</div>
I know that i have to echo it somehow by targeting first, second, third output?
*/
}
?>
</div>
This should illustrate something you could do to alternate between left and right while iterating.
function isEven(int $num):bool{
return $num % 2 == 0;
}
$len = count($names = ['foo','bar','fez']);
$i = 0;
while($i < $len){
$name = $names[$i];
$class = "right";
if(isEven($i)){
$class = "left";
}
echo $name . " is on the " . $class . "\n";
$i++;
}
// foo is on the left
// bar is on the right
// fez is on the left
<div id="timeline">
<?php
$SQLGetNews = $odb -> query("SELECT * FROM `news` ORDER BY `id` DESC LIMIT 3");
$i=1;
while ($getInfo = $SQLGetNews -> fetch(PDO::FETCH_ASSOC)) {
$name = $getInfo['name'];
if($i%2)
{
?>
<div class="right"><?php echo $name; ?></div>
<?php
}
else
{
?>
<div class="left"><?php echo $name; ?></div>
<?php
}
$i++;
/*It should be like that
<div class="left">'.$name.'</div>
<div class="right">'.$name.'</div>
I know that i have to echo it somehow by targeting first, second, third output?
*/
}
?>
</div>

php & pdo & mysql countrows returning 0

I have now spent several hours without getting anywhere.
I want to display number of rows in my query and here here is my code:
<?php
$user_id = 1;
$statement = $dbConn->query("select badoo_interest.*, badoo_category.icon_class from badoo_interest, badoo_user_interest, badoo_category where badoo_user_interest.interest_id = badoo_interest.id and badoo_user_interest.user_id = :id_user_profile and badoo_category.id = badoo_interest.category_id");
$statement->execute(array(':id_user_profile'=> $id_user_profile));
$rResult = $statement->fetchAll();
echo count($rResult);
echo "<h2>Interesi</h2>";
while( $row = $statement->fetch(PDO::FETCH_ASSOC) ){
?>
<div class="interest" id = "int<?php echo $row['id'];?>">
<span class = "intr-ico <?php echo $row['icon_class'];?>"></span>
<?php echo $row['name'];?>
</div>
<?php
}
?>
And i getting number 10 but now im not getting any interests displayed.
If you use this code now:
<?php
//$user_id = 1;
$statement = $dbConn->query("select badoo_interest.*, badoo_category.icon_class from badoo_interest, badoo_user_interest, badoo_category where badoo_user_interest.interest_id = badoo_interest.id and badoo_user_interest.user_id = :id_user_profile and badoo_category.id = badoo_interest.category_id");
$statement->execute(array(':id_user_profile'=> $id_user_profile));
echo "<p>" . $statement->rowCount(). " interests:</p>";
while( $row = $statement->fetch(PDO::FETCH_ASSOC) ){
?>
<div class="interest" id = "int<?php echo $row['id'];?>">
<span class = "intr-ico <?php echo $row['icon_class'];?>"></span>
<?php echo $row['name'];?>
</div>
<?php
}
?>
And now im getting all the interests displayed but it counts: 0 interests.
Any ideas who i can count number of interests?
If you read the documentation for PDOStatement::rowCount you will see this line
If the last SQL statement executed by the associated PDOStatement was
a SELECT statement, some databases may return the number of rows
returned by that statement. However, this behaviour is not
guaranteed for all databases and should not be relied on for portable
applications.
The work around is to count() function from php like you did. If that did not work then use COUNT(*) as result_count. then when you fetch read that value.
And i getting number 10 but now im not getting any interests displayed
problem
The reason why the result aren't displaying is because you fetched all the row already so you cannot use fetch() again.
solution
Use the array returned by fetchAll() instead and use a foreach instead
$rows = $statement->fetchAll();
echo "<p>" . count($rows). " interests:</p>";
foreach ($rows as $row){
//echo $row['name']
}
<?php
//$user_id = 1;
$statement = $dbConn->query("select badoo_interest.*, badoo_category.icon_class from badoo_interest, badoo_user_interest, badoo_category where badoo_user_interest.interest_id = badoo_interest.id and badoo_user_interest.user_id = :id_user_profile and badoo_category.id = badoo_interest.category_id");
$statement->execute(array(':id_user_profile'=> $id_user_profile));
echo "<p>" . $statement->rowCount(). " interests:</p>";
$counter = 0; //declare counter
while( $row = $statement->fetch(PDO::FETCH_ASSOC) ){
$counter++; //increment counter
?>
<div class="interest" id = "int<?php echo $row['id'];?>">
<span class = "intr-ico <?php echo $row['icon_class'];?>"></span>
<?php echo $row['name'];?>
</div>
<?php
}
?>
[NOTE: Edit by #DinoAmino removed the emphasis characters around the two uses of $counter, which caused the code to not compile for the question asker]
I solved my problem like this:
Here is the updated solving version. Thank you all for the input:
<?php
$user_id = 1;
$statement = $dbConn->query("select badoo_interest.*, badoo_category.icon_class from badoo_interest, badoo_user_interest, badoo_category where badoo_user_interest.interest_id = badoo_interest.id and badoo_user_interest.user_id = :id_user_profile and badoo_category.id = badoo_interest.category_id");
$statement->execute(array(':id_user_profile'=> $id_user_profile));
$rows = $statement->fetchAll();
if(count($rows) >= '1') {
?>
<div class="your-interests">
<?php
echo "<p>" . count($rows). " interests:</p>";
foreach ($rows as $row){
?>
<div class="interest" id = "int<?php echo $row['id'];?>">
<span class = "intr-ico <?php echo $row['icon_class'];?>"></span>
<?php echo $row['name'];?>
</div>
<?php
}
?>
</div>
<?php } ?>

PHP while statement only working for one row

I am trying to have a while statement display all table rows. I have three rows at the moment such as R1 Business R2 Communication and R3 Education. It is display three but all of R1. So instead of listing Business Communication Education it is Business Business Business.
The code I have is:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'\includes\format.php');
$con = mysql_connect("server","user","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("foundation", $con);
$result = mysql_query("select * from `database`.`collegemeter");
?>
<?php
if (!$result || !($row = mysql_fetch_assoc($result))) {
echo "DB error";
exit;
}
$college = $row["college"];
$date = $row["date"];
$goal = $row["goal"];
$url = $row["url"];
$current = $row["current"];
$percent = round($current / $goal * 100);
$totalwidth = 245;
$ourwidth = $totalwidth * $percent / 100;
?>
<?php
$halfofarrowheight = 36;
$arrowheight = $ourwidth-$halfofarrowheight;
if($arrowheight < 0)
$arrowheight = 0;
?>
<?php do { ?>
<div class="progresswrap">
<p><?php echo $college;?></p>
<div class="progresscontainer">
<div class="progress"></div>
</div>
<div class="arrow"> $<?php echo formatmoney($current);?></div>
<h4>$<?php echo formatmoney($goal);?></h4>
</div>
<?php } while ($row_college = mysql_fetch_assoc($result)); ?>
So, how do I get it to list ascending down and not repeating the first row?
you should try this one, you were defining your variables only once
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'\includes\format.php');
$con = mysql_connect("server","user","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("foundation", $con);
$result = mysql_query("select * from `database`.`collegemeter");
while($row = mysql_fetch_assoc($result)){
$college = $row["college"];
$date = $row["date"];
$goal = $row["goal"];
$url = $row["url"];
$current = $row["current"];
$percent = round($current / $goal * 100);
$totalwidth = 245;
$ourwidth = $totalwidth * $percent / 100;
$halfofarrowheight = 36;
$arrowheight = $ourwidth-$halfofarrowheight;
if($arrowheight < 0)
$arrowheight = 0;
?>
<div class="progresswrap">
<p><?php echo $college;?></p>
<div class="progresscontainer">
<div class="progress"></div>
</div>
<div class="arrow"> $<?php echo formatmoney($current);?></div>
<h4>$<?php echo formatmoney($goal);?></h4>
</div>
<?php } ?>
That code is a mess.
a)
require_once($_SERVER['DOCUMENT_ROOT'].'\includes\format.php');
Don't use backslashes in paths. Use forward / slashes only. PHP will compensate for you if you're on Windows, and auto-transate into backslashes. Backslashes in strings like that open the door to misinterpretation as an escape character, and not a path reference.
b)
$result = mysql_query("select * from `database`.`collegemeter");
You're missing the closing backtick on collegemeter, and unless your're using a reserved word for your database name, the backticks are totally unnecessary.
c)
if (!$result || !($row = mysql_fetch_assoc($result))) {
The proper (+ simplest) method to check for a DB error is:
if ($result === false) {
die(mysql_error());
}
Don't check if there's any results by trying to fetch a row. That's what mysql_num_rows() is for.
if (mysql_num_rows($result) == 0) then
die("No results!");
}
d) Stylistically, do/while loops for database results are a bit ugly. You'd be better off with a more standard:
while($row = mysql_fetch_assoc($result)) { ... }
construct. This would also let you see that you're only defining your $college and other vars only ONCE, OUTSIDE of your fetch loop. There's no need to fetch the retrieve DB row into individual variables, you can ouput them directly:
while ($row = ...) {
$money = moneyformat($row['goal']);
echo <<<EOL
<div class="progresswrap">
<p>{$row['college']}</p>
<div class="progresscontainer">
etc...
EOL;
}

Pagination links not working

I've searched through the web and can't really find what's the problem with my code. The next and prev links are not working. it only gets the first entry.
Hope you guys can help with this! Thanks.
<?php
// ROWS DISPLAYED PER PAGE
$rows_per_page = 1;
// GET PAGE NUMBER
$page = $_GET['page'];
$offset = (!empty($page)) ? $page : $page = 1;
// URL CLEAN UP
$self = $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];
$self = str_replace("page={$offset}", "", $self);
// GET LIST OF STATES
$offset = ($page) ? ($page - 1) * $rows_per_page : 0;
$id = $_GET['id'];
$sql = "SELECT * FROM updates WHERE update_categoryID = '$id' ORDER BY update_date DESC LIMIT {$offset},{$rows_per_page}";
$result = mysql_query($sql)or die('Error, query failed');
// GET NUMBER OF PAGES
$query1 = "SELECT * FROM updates WHERE update_categoryID = '$id'";
$result1 = mysql_query($query1)or die('Error, query failed');
$total = mysql_num_rows($result1);
$NumPgs = ceil($total/$rows_per_page);
while($row = mysql_fetch_assoc($result))
{
?>
<h2><?php echo $row['update_title']; ?></h2>
<p class="datetime"><?php echo $row['update_date'];?></p>
<br>
<p class="post"><?php echo $row['update_content'];?></p>
Post a Comment
<?php
}
?>
<span style="float:right">
<? if ($NumPgs > 0 && $page!=1) {
echo "<<Prev "; } ?>
[Page <?php echo $page; ?>]
<? if ($page < $NumPgs) {
echo " Next>>"; } ?>
<b><? echo $offset+1;?> to <? echo $offset+$rows_per_page;?>, of <? echo $total; ?> Entries</b>
</span>
</div>
Uhm maybe your page param is appended to the query string, try this :
$self = $_SERVER['PHP_SELF']."?".
preg_replace( $_SERVER[ 'QUERY_STRING' ], 'page=[0-9]+', '');
instead of :
// URL CLEAN UP
$self = $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];
$self = str_replace("page={$offset}", "", $self);
Short open tags are not working in your case.
http://us3.php.net/echo
http://us3.php.net/manual/en/ini.core.php#ini.short-open-tag
Try the following code.
<?php
// ROWS DISPLAYED PER PAGE
$rows_per_page = 1;
// GET PAGE NUMBER
$page = $_GET['page'];
$offset = (!empty($page)) ? $page : $page = 1;
// URL CLEAN UP
$self = $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];
$self = str_replace("page={$offset}", "", $self);
// GET LIST OF STATES
$offset = ($page) ? ($page - 1) * $rows_per_page : 0;
$id = $_GET['id'];
$sql = "SELECT * FROM updates WHERE update_categoryID = '$id' ORDER BY update_date DESC LIMIT {$offset},{$rows_per_page}";
$result = mysql_query($sql)or die('Error, query failed');
// GET NUMBER OF PAGES
$query1 = "SELECT * FROM updates WHERE update_categoryID = '$id'";
$result1 = mysql_query($query1)or die('Error, query failed');
$total = mysql_num_rows($result1);
$NumPgs = ceil($total/$rows_per_page);
while($row = mysql_fetch_assoc($result))
{
?>
<h2><?php echo $row['update_title']; ?></h2>
<p class="datetime"><?php echo $row['update_date'];?></p>
<br>
<p class="post"><?php echo $row['update_content'];?></p>
Post a Comment
<?php
}
?>
<span style="float:right">
<? echo ($prev = ($NumPgs > 0 && $page!=1) ? "Prev ":
"Prev "); ?>
[Page <?php echo $page; ?>]
<? echo ($next = ($page < $NumPgs) ? "Next":
"Next");?>
<b> <? echo $offset+1?> to <?=$offset+$rows_per_page?>, of <? echo $total?> Entries</b>
</span>
</div>

Categories