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;
}
Related
I've hit a little wall in something I'm trying to do.
I have a table, entitled 'projects', in a database in SQL.
My issue is that I can't seem to select every row in a specific column.
This is the code that I've got so far relevant to this question (keep in mind that '$conn' is the connection to the SQL database, and the include command on the second line is just to include that connection):
//CONNECTION FILE
include "../include/dbh-inc.php";
//ASSIGNING QUERY VALUES TO VARIABLES
$q1 = mysqli_query($conn,"SELECT pid FROM projects;");
$q2 = mysqli_query($conn,"SELECT ptitle FROM projects;");
$q3 = mysqli_query($conn,"SELECT plink FROM projects;");
//SETTING ARRAYS FROM VARIABLES
$ids = mysqli_fetch_array($q1);
$titles = mysqli_fetch_array($q2);
$links = mysqli_fetch_array($q3);
mysqli_close($conn);
file_put_contents("newtest.txt","$titles\n");
foreach($titles as $title) {
file_put_contents("newtest.txt","$title\n", FILE_APPEND); //Testing
}
if(count($ids) > 0) {
file_put_contents("TEST.txt","");
for($i = 0; $i < count($ids)-1; $i+=1) {
$count = count($ids);
$title = $titles[$i];
$id = $ids[$i];
$link = $links[$i];
file_put_contents("TEST.txt","$i: $title, $id ($count), $link\n",FILE_APPEND);
echo("
<div class=\"projlink\">
<a href=\"$link\" style=\"width:190px;height:90px\">
<h2>$title</h2>
</a>
</div>
");
}
}
else {
echo("
<h2>Nothing here currently!<br>Be patient!</h2>
");
}
Any thoughts?
Thanks!
- Raphael
You are only fetching one row with mysqli_fetch_array. Also, you can get all columns in one query:
$q1 = mysqli_query($conn,"SELECT pid, ptitle, plink FROM projects;");
$rows = mysqli_fetch_all($q1, MYSQLI_ASSOC);
If you don't have mysqli_fetch_all then:
while($rows[] = mysqli_fetch_assoc($q1));
Then just loop $rows and use the columns:
foreach($rows as $row) {
echo $row['pid'] . ' ' . $row['ptitle'] . ' ' . $row['plink'];
}
If you really need separate arrays (this is rarely necessary):
$ids = array_column($rows, 'pid');
$titles = array_column($rows, 'ptitle');
$links = array_column($rows, 'plink');
It is a tracking system like DHL. Tracking shipment number from MySQL database using php form.
but I need it Search multiple row separate by comma from mysql using php.
<?php
$ship=$_POST['Consignment'];
$cons = explode(',',$ship);
?>
<?php
$sql = "SELECT * FROM tbl_courier WHERE cons_no = '$cons[]'";
$result = dbQuery($sql);
$no = dbNumRows($result);
if($no == 1){
while($data = dbFetchAssoc($result)) {
extract($data);
?>
Shipment Name: <?php echo $ship_name; ?>
Shipment Phone: <?php echo $phone; ?>
<?php }//while
}//if
else {
echo 'In else....';
?>
Consignment Number not found.Search Again.
<?php
}//else
?>
So I need my search will work with separating by comma(,).
Thanks for helping me.
You can use IN operator in that case.
<?php
$ship=$_POST['Consignment'];
?>
<?php
$sql = "SELECT * FROM tbl_courier WHERE cons_no IN(".$ship.")";
$result = dbQuery($sql);
$no = dbNumRows($result);
if($no == 1){
while($data = dbFetchAssoc($result)) {
extract($data);
?>
Hope it will help to you.
change your sql query you have written '$cons[]' in select query which is wrong . after explode you will get data as 1,2,3 so you just need to write variable in query not array and user IN Operator like this.
`$sql = "SELECT * FROM tbl_courier WHERE cons_no IN(".$ship.")";`
You should always prepare/sanitize the POST data before using it in MySql query (in terms of security):
<?php
if (isset[$_POST['Consignment']] && !empty($_POST['Consignment'])) {
$ship = $_POST['Consignment'];
$cons = explode(',', $ship);
$cons = array_filter($cons, function($v){
return trim(strip_tags($v));
});
$cons = '"' . implode('","', $cons) . '"';
$sql = "SELECT * FROM tbl_courier WHERE cons_no IN ($cons)";
$result = dbQuery($sql);
$no = dbNumRows($result);
if ($no == 1) {
while ($data = dbFetchAssoc($result)) {
extract($data);
....
}
....
}
?>
Please Use Find IN SET
SELECT * FROM tbl_courier WHERE FIND_IN_SET(cons_no,'1,2,3,4,5')
Updated
SELECT * FROM tbl_courier WHERE FIND_IN_SET(cons_no,'$ship')
Note :- $ship Comma Separated Value not an array
I found the Answer:
if(isset($_POST['Consignment'])){
$ship=$_POST['Consignment'];
$shipment= explode(',',$_POST['Consignment']);
$ship = implode("', '",$shipment) ;
$query = "SELECT * FROM `tbl_courier` WHERE `cons_no` IN('$ship')";
$results = $mysqli->query($query);
if($results){
print '<table border="1">';
while($row = $results->fetch_assoc()) {
print '<tr>';
print '<td>'.$row["cons_no"].'</td>';
print '<td>'.$row["customerName"].'</td>';
print '<td>'.$row["customerPhone"].'</td>';
print '</tr>';
}
print '</table>';
// Frees the memory associated with a result
$results->free();
}
else {
echo "Query Not Match";
}
$mysqli->close();
}
Thanks to Answer.
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();
?>
I've been working on getting an RSS feed setup and with the help of some people here I got it done. However, I really need some advice from some of you more experienced coders to show me what needs to be changed to keep the same functionality but speed up the page load.
It looks 30 RSS items and gets the URLs from my MySQL database. The problem is that it randomly selects 30 rows out of over 100 million rows in that table. That is what it's supposed to do, but with their being so many rows in the table, it's really slowing down the script and I need help!
<?php header("Content-type: text/xml"); ?>
<?php echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; ?>
<?php include('directory/database.php'); ?>
<rss version="2.0">
<channel>
<title>Website Reviews</title>
<link>http://www.mywebsite.com</link>
<description>Professional Services</description>
<pubDate><?echo date('Y/m/d H:i:s');?></pubDate>
<?php
foreach( range( 1, 30 ) as $i ):
$number = mt_rand( 1, 141754641 );
$query="SELECT * FROM `list` LIMIT $number , 1";
$result = mysql_query($query);
if($result == false)
{
user_error("Query failed: " . mysql_error() . "<br />\n$query");
}
elseif(mysql_num_rows($result) == 0)
{
echo "<p>Sorry, we're updating this section of our website right now!</p>\n";
}
else
{
while($query_row = mysql_fetch_assoc($result))
{
foreach($query_row as $key => $domain)
{
echo "$value";
}
}
}
?>
<item>
<title><?php echo $domain; ?> REVIEW</title>
<pubDate><?echo date('Y/m/d H:i:s');?></pubDate>
<link>http://www.mywebsite.com/review/<?php echo $domain; ?></link>
<description>Looking for a review on <?php echo $domain; ?>? We've got it!</description>
</item>
<?php endforeach; ?>
</channel>
</rss>
Thanks in advance for any help that anyone can give!
Limit has to do table scans, so what you want to do is use indexes to your advantage. So first, let's add an autoincrement ID field to the table named "id".
Then,
<?php
$result = array();
$maxRow = mysql_fetch_assoc(mysql_query("SHOW TABLE STATUS LIKE 'list';"));
$max = $maxRow["Auto_increment"];
$minRow = mysql_fetch_assoc(mysql_query("SELECT id FROM 'list' LIMIT 1;"));
$min = $minRow["id"];
while (count($result) < 30) {
$ids = array();
while (count($ids) < 100) {
$id = mt_rand($min, $max);
$ids[$id] = 1;
}
$res = mysql_query("SELECT * from 'list' WHERE id IN (" . join(',', array_keys($ids)) . ") LIMIT 30");
while (($row = mysql_fetch_assoc($result)) && (count($result) < 30)) {
$result[] = array( ... ); // stuff results here
}
}
// output
?>
You can still select all 30 at once. It shouldn't be that slow to get 30 records.
$numbers=array();
foreach( range( 1, 30 ) as $i ):
$numbers[] = mt_rand( 1, 141754641 );
endforeach;
$query="SELECT * FROM `list` WHERE `whatever_primary_key_is` IN (".implode(',', $numbers).")";
May i suggest a more robust approach.
You have to take in account that the number you go look for may not exist
Only using one MySql query is often faster
Base on url1 and url2
You can have this php code instead :
<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password') or die('Could not connect: ' . mysql_error());
mysql_select_db('my_database') or die('Could not select database');
$query = "SELECT `url`
FROM `liste`
ORDER BY RAND()
LIMIT 30" ;
$result = mysql_query($query);
if($result == false)
{
user_error("Query failed: " . mysql_error() . "<br />\n$query");
}
elseif(mysql_num_rows($result) == 0)
{
echo "<p>Sorry, we're updating this section of our website right now!</p>\n";
}
else
{ $query_row = array();
while($query_row = mysql_fetch_assoc($result))
{
echo $query_row['url']; // no need to do the extra foreach
}
}
?>
The values mysql_host,mysql_user,mysql_password,my_database should be replaced by your connection.
As long as you have 30 row in your title table your are ok.
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>