Hopefully this will be quite simple for someone.
I have the following code:
<?php
// Connects to your Database
mysql_connect("localhost", "xxxxx", "xxxxx") or die(mysql_error());
mysql_select_db("xxxxx") or die(mysql_error());
require("../includes/common.php");
require("admin_header.php");
require("admin_menu.php");
$query = "Truncate TABLE pt_menutitles";
$result = mysql_query($query) or die(mysql_error());
// Menu Headers for Category
$data = "select a.menuheader, a.total from(SELECT distinct (menuheader),count(*) as total FROM `pt_products` WHERE `menuheader` <> '' group by `menuheader` order by total desc limit 4) a order by a.menuheader";
$result = mysql_query($data) or die(mysql_error());
while($info = mysql_fetch_array($result))
{
$menudata = "select a.subcategory, a.menuheader,a.totcount FROM(SELECT distinct (subcategory),menuheader,count(*) as totcount FROM `pt_products` WHERE `menuheader`='".$info['menuheader']."' AND subcategory <> ''group by `subcategory` order by totcount desc limit 4) a order by a.subcategory";
$menuresult = mysql_query($menudata) or die(mysql_error());
while($menuinfo = mysql_fetch_array($menuresult))
{
$sql = "Insert into pt_menutitles (menu, title, totalcount) select '".$menuinfo['menuheader']."','".$menuinfo ['subcategory']."','".$menuinfo ['totcount']."'";
$result = mysql_query($sql) or die(mysql_error());
}
}
?>
Basically I take the top 4 menu titles that have the most items in them, then select the top 4 subcategories in them titles and insert them into a table.
What is happening though is that i'm onlyt getting Menu Title 1 and Subcategories 1 to 4 inserted into my table.
It's as though the the loop is ending after the first time round?
Any advise would be great!
Cheers
Chris
This line replaces your existing result and ends the loop. Use any other (non-existing) variable name, but not $result.
$sql = "Insert into pt_menutitles (menu, title, totalcount) select '".$menuinfo['menuheader']."','".$menuinfo ['subcategory']."','".$menuinfo ['totcount']."'";
$result = mysql_query($sql) or die(mysql_error());
Related
I am using the following to fetch the latest articles from the database:
//Latest Article
$title_query1 = "SELECT title FROM articles ORDER BY id DESC LIMIT 1";
$description_query1 = "SELECT description FROM articles ORDER BY id DESC LIMIT 1";
$content_query1 = "SELECT content FROM articles ORDER BY id DESC LIMIT 1";
$image_query1 = "SELECT image FROM articles ORDER BY id DESC LIMIT 1";
$title_result1 = mysqli_query($con, $title_query1) or die(mysqli_error($con));
$description_result1 = mysqli_query($con, $description_query1) or die(mysqli_error($con));
$content_result1 = mysqli_query($con, $content_query1) or die(mysqli_error($con));
$image_result1 = mysqli_query($con, $image_query1) or die(mysqli_error($con));
//Second Latest Article
$title_query2 = "SELECT title FROM articles ORDER BY id DESC LIMIT 2,1";
$description_query2 = "SELECT description FROM articles ORDER BY id DESC LIMIT 2,1";
$content_query2 = "SELECT content FROM articles ORDER BY id DESC LIMIT 2,1";
$image_query2 = "SELECT image FROM articles ORDER BY id DESC LIMIT 2,1";
$title_result2 = mysqli_query($con, $title_query2) or die(mysqli_error($con));
$description_result2 = mysqli_query($con, $description_query2) or die(mysqli_error($con));
$content_result2 = mysqli_query($con, $content_query2) or die(mysqli_error($con));
$image_result2 = mysqli_query($con, $image_query2) or die(mysqli_error($con));
However, i'm not sure how I can then do something like this:
<h1>Here is the first article: <?php $title_result1 ?><h1>
<h2>Here is the first article description: <?php $description_result1 ?>
<h1>Here is the second article: <?php $title_result2 ?><h1>
<h2>Here is the second article description: <?php $description_result2 ?>
Also, is this method not good? If I am going to do this for 100+ articles, will it cause the web page to load slowly?
Thanks
You do not need to do a single query for each column. You can get all columns for a row by doing select * Also, as mentioned, you can fetch as many rows as you want, and loop through them.
I prefer the while method.. Example, show last 100 articles
// fetch latest 100
$sql = "SELECT * FROM articles ORDER BY id DESC LIMIT 100";
if ($result = mysqli_query($con, $sql)){
// got results, convert result object to array called $row
while ($row = mysqli_fetch_array($result)) {
// echo out $row array elements with
//the column names from the database as array index
echo '<h2>'. $row['title'] .'</h2>'; // example wrap results with HTML
echo '<b>' .$row['description'] .'</b>';
echo $row['content'];
echo <img src="'. $row['image'] .'" title="'.$row['description'].'">';
echo '<br>'; //so next result is on new line
} // end of while loop
} else {
//no result, error
}
In the "user_id" column of my table, I'd like to insert the ID of the user who just registred from my page. The idea is to associate his recent generated income with the users id, just to spot an eventual double registration of the income.
In order to do this, I tought to update the user_id column, on the row where income_id has the biggest value, i.e. the last generated income, but something isn't working. My code is:
$query = "SELECT max( id_income ) FROM `affiliate_income`";
$last_income = mysql_query($query, $conn) or die(mysql_error());
$last = mysql_fetch_assoc($last_income);
$updtsql = "UPDATE affiliate_income SET `id_user`=".$row_user_code['id_user']."WHERE id_income =".$last;
$result = mysql_query($updtsql, $conn) or die(mysql_error());
any ideas?
Actually you can do it in one query,
UPDATE affiliate_income a
INNER JOIN (SELECT MAX(id_income) id_income FROM affiliate_income) b
ON a.id_income = b.id_income
SET a.id_user = 'valueHere'
You get the value of $last as array.So you have to giv the query like the following
$updtsql = "UPDATE affiliate_income SET `id_user`=".$row_user_code['id_user']."WHERE id_income =".$last['id_income'];
You try to get the max id_income but in the second query (updtsql) you try to find the id_income = array. Besides, you do not put a white space before WHERE clause.
$query = "SELECT max( id_income ) AS ii FROM `affiliate_income`";
$last_income = mysql_query($query, $conn) or die(mysql_error());
$last = mysql_fetch_assoc($last_income);
$updtsql = "UPDATE affiliate_income SET `id_user`=".$row_user_code['id_user']." WHERE id_income =".$last['ii'];
$result = mysql_query($updtsql, $conn) or die(mysql_error());
I have a problem with my code:
<?php
echo $s_country;
$sql2="SELECT prod_id FROM tbl_order_item WHERE order_id='$order_id'";
$res=mysql_query($sql2) or die(mysql_error());
$i=0;
$j="";
while($rs=mysql_fetch_array($res)){
$j = $rs['prod_id'];
if(trim($s_country)=='US' || trim($s_country=='United States' )){
$sql3 = "SELECT shipping_us FROM tbl_product WHERE prod_id=".$j;
$res=mysql_query($sql3) or die(mysql_error());
$shipping_cost1=mysql_fetch_object($res);
}
$i++;
}
?>
What I actually want to do is to fetch the products id from the table tbl_order_item and with that products id select the shipping cost for those ids from the table tbl_product.
For example, if there is two product ids, it should select shipping cost for both the ids.
But here it only works for one product id like this:
SELECT shipping_us FROM tbl_product WHERE prod_id=526
But what I'm trying to do is :
SELECT shipping_us FROM tbl_product WHERE prod_id=526
SELECT shipping_us FROM tbl_product WHERE prod_id=527
you could use OR, like
SELECT shipping_us FROM tbl_product WHERE prod_id=526 OR prod_id=527
you can also use it like this with IN
SELECT shipping_us FROM tbl_product WHERE prod_id IN (526,527)
First Solution:
Change
$res=mysql_query($sql3) or die(mysql_error()); // you have overwritten result set of first query
$shipping_cost1=mysql_fetch_object($res);
To
$newres=mysql_query($sql3) or die(mysql_error());
$shipping_cost1=mysql_fetch_object($newres);
Second Solution (much better):
$sql2="SELECT GROUP_CONCAT(prod_id SEPARATOR ',') as pid FROM tbl_order_item WHERE order_id='$order_id'";
$res=mysql_query($sql2) or die(mysql_error());
if(mysql_num_rows($res) > 0){
$rs=mysql_fetch_array($res);
$sql3 = "SELECT shipping_us FROM tbl_product WHERE prod_id IN (".$rs['pid'].")";
$res=mysql_query($sql3) or die(mysql_error());
while ($row = mysql_fetch_array($res)){
echo $row['shipping_us']
}
}
Recommendations:
1.Learn to prevent from MySQL Injections: Good Link
2.Mysql extension is not recommended for writing new code. Instead, either the mysqli or PDO_MySQL extension should be used. More reading: PHP Manual
my pblm was solved... and special tnx to GBD..
here is my final code...
<?php
echo $s_country;
$sql2="SELECT GROUP_CONCAT(prod_id SEPARATOR ',') as pid FROM tbl_order_item WHERE order_id='$order_id'";
$res=mysql_query($sql2) or die(mysql_error());
$shipping_cost1 = 0;
if(mysql_num_rows($res) > 0){
$rs=mysql_fetch_array($res);
if(trim($s_country)=='US' || trim($s_country=='United States' )){
$sql3 = "SELECT shipping_us FROM tbl_product WHERE prod_id IN (".$rs['pid'].")";
$res=mysql_query($sql3) or die(mysql_error());
if(mysql_num_rows($res) > 0){
while ($row = mysql_fetch_array($res)){
$shipping_cost1 = $shipping_cost1 + $row['shipping_us'];
}
}
} else {
$sql3 = "SELECT shipping_outside FROM tbl_product WHERE prod_id IN (".$rs['pid'].")";
$res=mysql_query($sql3) or die(mysql_error());
while ($row = mysql_fetch_array($res)){
$shipping_cost1= $shipping_cost1 + $row['shipping_outside'];
}
}
}
?>
I have following script:
$sql = "SELECT * FROM `users`"
$q = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($q);
$sql1 = "SELECT * FROM `other_table`";
$q1 = mysql_query($sql1) or die(mysql_error());
$row1 = mysql_fetch_array($q1);
$item = $row1[$row['username']];
How can I set one variable row inside another, since it does not work. Basically, I need to select username, and then select column with user username from other table, in which is written user points.
I was thinking about adding:
$sql = "SELECT * FROM `users`"
$q = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($q);
$sql1 = "SELECT `".$row['username']."` FROM `other_table` WHERE `uid` = 1";
$q1 = mysql_query($sql1) or die(mysql_error());
$row1 = mysql_fetch_array($q1);
$item = $row1[xxxxxxxxxx]; // DONT KNOW HOW TO DEFINE IT, so it takes out found variable (there is only one).
Guess you want something like
SELECT * FROM table1 t1, table2 t2 WHERE t1.user_name = t2.user_name?
Think about using JOIN
$sql = "SELECT * FROM users;";
$q = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($q);
$sql1 = sprintf("SELECT * FROM other_table where username='%s';", $row['username']);
$q1 = mysql_query($sql1) or die(mysql_error());
$row1 = mysql_fetch_array($q1);
// now $row1 contains the tuple of this user and could access the variables are you would
// normally do e.g. $row1['ID']
SELECT * FROM users AS u INNER JOIN other_table AS o ON u.username = o.username
I'm assuming you want to do this because you want to be able to access all the rows from either table where a particular user name is the same (e.g. the data from users where username="john" and the data from other_table where username="john" for all usernames). No need to nest a result set to do this, just use a JOIN statement and then you can access all the columns as if it was a single result set (because it is):
$sql = "SELECT * FROM users AS u INNER JOIN other_table AS o ON u.username = o.username";
$q = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($q);
$item = $row['any_column'];
FYI you should list out the column you want to retrieve instead of using *, even if you want to retrieve them all, as it is better practice in case you add new columns in the future.
My page displays an image, and I want to display the previous and next image that is relevant to the current one. At the moment I run the same query 3x and modify the "where" statement with =, >, <.
It works but I feel there must be a better way to do this.
The image id's are not 1,2,3,4,5. and could be 1,2,10,20,21 etc. But if it is much more efficient I am willing to change this.
mysql_select_db("database", $conPro);
$currentid = mysql_real_escape_string($_GET['currentid']);
$query ="SELECT * FROM database WHERE id ='".$currentid."' LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$current_id = $row['id'];
$current_header = $row['title'];
$current_description =$row['desc'];
$current_image = "http://".$row['img'];
$current_url = "http://".$row['id']."/".$db_title."/";
$current_thumb = "http://".$row['cloud'];
}
mysql_select_db("database", $conPro);
$query ="SELECT * FROM database WHERE id <'".$currentid."' ORDER BY id DESC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$previous_id = $row['id'];
$previous_header = $row['title'];
$previous_description =$row['desc'];
$previous_image = "http://".$row['img'];
$previous_url = "http://".$row['id']."/".$db_title."/";
$previous_thumb = "http://".$row['cloud'];
}else{
$previous_none = "true"; //no rows found
}
mysql_select_db("database", $conPro);
$query ="SELECT * FROM database WHERE id >'".$currentid."' ORDER BY id ASC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$next_id = $row['id'];
$next_header = $row['title'];
$next_description =$row['desc'];
$next_image = "http://".$row['img'];
$next_url = "http://".$row['id']."/".$db_title."/";
$next_thumb = "http://".$row['cloud'];
}else{
$next_none = "true"; //no rows found
}
mysql_close($conPro);
Thank you for your time
You don't have to do select_db each time. Once you 'select' a db, it stays selected until you select something else.
You can't really get away from doing two separate queries to get the next/previous images, but you can fake it by using a union query:
(SELECT 'next' AS position, ...
FROM yourtable
WHERE (id > $currentid)
ORDER BY id ASC
LIMIT 1)
UNION
(SELECT 'prev' AS position, ...
FROM yourtable
WHERE (id < $currentid)
ORDER BY id DESC
LIMIT 1)
This would return two rows, containing a pseudofield named 'position' which will allow you to easily identify which row is the 'next' record, and which is the 'previous' one. Note that the brackets are required so that the 'order by' clauses apply to the individual queries. Without, mysql will take the order by clause from the last query in the union sequence and apply it to the full union results.
You can get the "previous" one first WHERE id <'".$currentid."' ORDER BY id DESC, and then query for two "above" it: SELECT * FROM database WHERE id >= '".$currentid."' ORDER BY id ASC then it takes only two queries instead of three.