Faily new to php and mysql, this will probably seem very messy.
This is what I came up with:
$query = "show tables like 'whatever%'";
$result = mysql_query($query);
$num_results = mysql_num_rows($result);
for ($i = 0; $i < $num_results; $i++)
{
$row = mysql_fetch_array($result);
$sql=mysql_query("SELECT * FROM ". $row[0] ." WHERE a=(SELECT MAX(a)) AND b=(SELECT MAX(b)) AND c LIKE 'd%' ORDER BY date DESC LIMIT 1");
while($info=mysql_fetch_array($sql)){
echo "...";
}
}
I get the desired value from each table, so x results depending on the amount of tables. What I would like is to have the results of the queried tables but only show the top 10-5 ordered by date/time.
Is this possible with the current script? Is there an easier way (while, number of tables changing constantly)? Is this query method database intensif?
Cheers!
I call constantly changing number of tables having similar structure a design error. also query switch to
$sql=mysql_query("SELECT * FROM $tbl WHERE c LIKE 'd%' ORDER BY a DESC, b DESC, date DESC LIMIT 1");
is a little relief to database.
Related
I'm trying to get specific rows in table 1 (stellingen). I want to store these rows to specify the rows im interested in for the second table (stelling). So lets say table 1 has 5 rows where stelling ID matches REGIOID = 5. These IDS from stelling ID I want to use to fetch the data from the second table. see the code to see what I tried. I'm not managing to find a way in order too make this happen.
So maybe too be clearer because people always say im not clear:
There are two tables. they both have a matching column. Im trying to tell the second table I want data but only if it matches the data of the first table. Like a branch of a tree. Then, I want to output some data that's in the second table.
I've tried something like this before:
SELECT
*
FROM
table2
LEFT JOIN
table1 ON
table1.ID = table2.table1_id
I've tried to create a while loop to get the data before(after the first if statement and the last += was for the variable $amountofstellinge):
$amountOfStellinge = 0;
while ($amountOfStellinge<5){
mysqli_data_seek($result, $amountOfStellinge);
Here is the code what it looks like now, its wrong, i've been messing with t a lot, but maybe it shows you what I'm trying to achieve better.
if($result = mysqli_query($con, "SELECT * FROM stellingen WHERE REGIOID=1;")) {
$row = mysqli_fetch_assoc($result);
$stellingid= $row["Stelling_ID"];
//checking.. and the output is obviously not what I want in my next query
printf($stellingid);
//defining the variable
$Timer=0;
$sql1="SELECT * FROM stelling WHERE stelling_iD=$stellingid ORDER BY Timer DESC;";
$records2 = mysqli_query($con, $sql1);
$recordscheck = mysqli_num_rows($records2);
//max 5 data
if ($recordscheck < 5){
while ($stelling = mysqli_fetch_assoc($records2)){
//At the end, i would like to only have the data that is most recent
$Timer = date('d F', strtotime($stelling['Timer']));
echo "<p><div style='color:#ED0887'>".$Timer.":</div><a target = '_blank' style='text-decoration:none' href='".$stelling['Source']."'>".$stelling['Title']."</a></p>";
}}
$recordscheck+=1; } // this is totally wrong
EDIT:
I've tried this, #noobjs
$Timer=0;
$sql1="SELECT
*
FROM
stelling
LEFT JOIN
stellingen
ON
stelling.ID = stellingen.stelling_id
WHERE
stellingen.REGIOID=1
ORDER BY stelling.Timer LIMIT 5 DESC ;";
$records2 = mysqli_query($con, $sql1);
printf($records2);
while ($stelling = mysqli_fetch_assoc($records2)){
$Timer = date('d F', strtotime($stelling['Timer']));
echo "<p><div style='color:#ED0887'>".$Timer.":</div><a target = '_blank' style='text-decoration:none' href='".$stelling['Source']."'>".$stelling['Title']."</a></p>";
}
with this error:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in
EDIT for more clarification
Here is some sample data
The expected results is:
every page has uses data from a different REGIOID. I expect the page to show data from the table stelling(Table 1). Accordingly to the REGIOID (Table2)
if i understand right:
SELECT
*
FROM
stelling
LEFT JOIN
stellingen
ON
stelling.stellingID = stellingen.stelling_id
WHERE
stellingen.REGIOID=1
ORDER BY stelling.Timer DESC LIMIT 5 ;
I know there are libraries etc that I could use to get this sorted but Im almost there with my code.
A little about the code and what it's trying to do. I have a mysql table where there are various news articles and grouped in categories of news.
I have managed to get a forward button working. So it looks for the next news article that is in the same category. This works and the code is below.
//Gets the next story from the same story type in line.
$query= "SELECT * FROM news WHERE storytype2 = '$storytype2' AND id > '$currentid'";
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$row = mysql_fetch_array($result);
$num_results = mysql_num_rows($result);
if ($num_results > 0){
echo "<td width=\"20%\"align=\"right\"><img title=\"Next News\" src=\"webImg/forwardarrow.png\"/></td></tr>";
}else{
echo "<td width=\"20%\"align=\"right\"></td></tr>";
}
//End of the next button
However, when I try do the same for the previous button. All I ever seem to get back is the first id of that category regardless of where my iteration is. For example, if I am on news article 10 and try to go to previous one which say has an id of 7 it will automatically show the first news article within that category, say id 4.
Below is the code.
//Gets the next story from the same story type in line.
$query= "SELECT * FROM news WHERE storytype2 = '$storytype2' AND id < '$currentid'";
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$row = mysql_fetch_array($result);
$num_results = mysql_num_rows($result);
if ($num_results > 0){
echo "<td width=\"20%\"align=\"left\"><img title=\"Previous News\" src=\"webImg/backarrow.png\"/></td>";
}else{
echo "<td width=\"20%\"align=\"left\"></td>";
}
//End of the next button
What have I done wrong?
Thanks
Neither of your queries is correct. Your "Next" code selects any row whose ID is higher than the current, not necessarily the next one; if you get the next one, it's just by accident.
You should use ORDER BY and LIMIT to control which row is selected:
Next:
SELECT *
FROM news
WHERE storytype2 = '$storytype2' AND id > '$currentid'
ORDER BY id
LIMIT 1
Previous:
SELECT *
FROM news
WHERE storytype2 = '$storytype2' AND id < '$currentid'
ORDER BY id DESC
LIMIT 1
Without any further information, I don't think you can assume that the first row of your queries will be the ID you're looking for. Ordering by ID first will probably solve your problem; you can also limit your query to one row, since it's the only one you're looking at. Something like the following would probably solve your problem (where x is $storytype2 and y is $currentid:
SELECT * FROM news
WHERE storytype2 = x
AND id < y
ORDER BY id DESC /* <-- THIS */
LIMIT 1
Use ORDER BY id ASC for the other case.
Note that the MySQL family of PHP is deprecated and support thereof will disappear, if it hasn't yet. Please look into PDO or MySQLi.
Note also that you are inserting a variable into SQL code directly, which is never a good idea. I hope you have some good input checks on your variables.
Let's look at the PDO way to get the previous article ID:
$dbh = new PDO(..);
// Use ? where dynamic input will come
$sql = $dbh->prepare('SELECT * FROM news
WHERE storytype2 = ?
AND id < ?
ORDER BY id DESC
LIMIT 1');
// Fill the ? safely with PDO's execute function
$sql->execute(array($storytype2, $currentid));
$result = $sql->fetch(PDO::FETCH_ASSOC);
if($result && isset($result['id'])) {
// Process previous ID
}
I am getting 10 rows with the highest ID from a table ...
$result = pg_query($dbconn, "SELECT w_news_id, name, w_newsnachricht, w_newsdatum FROM adempiere.w_news ORDER BY w_news_id DESC LIMIT 10");
... then I build 10 divs in a while loop:
while ($row = pg_fetch_row($result)) {
// building divs here
}
BUT I want to also include the name that belongs to the next w_news_id in that same div (as a "teaser" for the "next"-arrow). So I was thinking I have to run a second query with the ID that would be next in the loop.
How is the SQL syntax for that? Or is there maybe a better way to do this?
You can use the lead window function:
SELECT w_news_id, name, w_newsnachricht, w_newsdatum,
LEAD (name) OVER (ORDER BY w_news_id) AS next_name
FROM adempiere.w_news
ORDER BY w_news_id DESC
LIMIT 10
You can select one more record - LIMIT 11, instead of 10, and process it differently in PHP.
$result = pg_query($dbconn, "SELECT w_news_id, name, w_newsnachricht, w_newsdatum FROM adempiere.w_news ORDER BY w_news_id DESC LIMIT 11");
$i = 0;
while ($row = pg_fetch_row($result) and $i < 10) {
$i++;
// building divs here
}
// then process the arrow and teaser separately (if present)
if ($row = pg_fetch_row($result)) {
// show teaser div
}
UPDATE
The window function solution provided by Mureinik is better.
Hello I would like to query multiple identical tables in my db which has different prefixes and than display the results randomly but somehow I need to track the origin of the item and I couldn't figure out how
I do the query like this because I don't have access to information_schema
$query = "SHOW TABLES FROM mydb WHERE RIGHT( tables_in_mydb, 5 ) = 'table'";
$res = mysql_query($query);
$num = mysql_num_rows($res);
while($row = mysql_fetch_row($res)) {
$numbers = explode('_', $row[0]);
if($num > 0) {
$q = "SELECT `this`, `that`, `something` FROM ".$numbers[0]."_idetinticaltables"; // :)
$r = mysql_query($q);
while($c = mysql_fetch_array($r)) {
/*display the results randomly with an identifier where the come from*/
}
}
}
You could use ORDER BY RAND() to randomly sort it
The following might work:
Get the list of the tables you're interested in. You already do that.
Create a UNION of multiple SELECT statements. Each SELECT statement differs for the table being selected from and you add a column set to the name of the table (so you can identify it later):
(SELECT *, TABLENAME = 'first_name_of_table' FROM first_name_of_table ...)
UNION
(SELECT *, TABLENAME = 'second_name_of_table' FROM second_name_of_table ...)
UNION
...
ORDER BY RAND() LIMIT 10;
Because it is a UNION you can randomize the whole order then. See How can i optimize MySQL's ORDER BY RAND() function? because it is not that trivial to do well, the example above is only to have an ORDER BY and LIMIT clause placed there. With many entries in your tables, it will kill your server.
$aa=array()
while($c = mysql_fetch_array($r))
{
/*display the results randomly with an identifier where the come from*/
$aa[]=$c;
}
echo $aa; // print "Array"
Each page lists all the coupons available for a specific retailer. I query the database for all the coupon codes in the header since I count the number of rows returned and use that info in the meta title of the page. I now also want to display the titles of the first 2 coupons in the array. How would I go about extracting the first 2 results from the array without querying the database again?
This is what I have so far:
$retailer_coupons = "select C.couponid,C.fmtc_couponid,C.merchantid,C.exclusive,C.label,C.shoppingtip,C.restrictions,C.coupon,C.custom_order,C.link,C.image,C.expire,C.unknown,M.name,M.approved,M.homepageurl,M.category from tblCoupons C,tblMerchants M where C.merchantid=M.merchantid and C.begin < ".mktime()." and C.expire > ".mktime()." and C.merchantid=".$merchantid." and M.display='1' and C.user_submitted='' order by C.custom_order desc, C.coupon desc";
$retailer_coupons_result = mysql_query($retailer_coupons) or die(mysql_error());
$count_coupons=mysql_num_rows($retailer_coupons_result);
$meta_title = ''.$name.' Coupon Codes ('.$count_coupons.' coupons available)';
Suppose I have 3 records in my table. If I execute below query, I will get 2 results however the count(*) will give me 3 as output
SELECT count(*) FROM temp.maxID limit 2
In your case it will be
$retailer_coupons =
"select C.couponid,C.fmtc_couponid,C.merchantid,C.exclusive,C.label,C.shoppingtip,C.restrictions,C.coupon,C.custom_order,C.link,C.image,C.expire,C.unknown,M.name,M.approved,M.homepageurl,M.category
from tblCoupons C,tblMerchants M
where C.merchantid=M.merchantid
and C.begin < ".mktime()." and C.expire > ".mktime()."
and C.merchantid=".$merchantid." and M.display='1'
and C.user_submitted=''
order by C.custom_order desc, C.coupon desc
limit 2";
limit 2 will do the magic... Cheers!!!
Good Luck!!!
Something like this:
$res = mysql_fetch_assoc($retailer_coupons_result);
$i = 0;
while ($i < 2){
echo $res[$i]['label']."\n";
$i++;
}