I'm probably missing something obvious but when I try to execute this query, it returns no results. I plugged it directly into MySQL and also tried replacing the variable with a valid row value and I get the correct output. When I use a variable, it gives me no results. Anyone have any thoughs?
$query = "SELECT title FROM le7dm_pf_tasks WHERE project = (SELECT id FROM le7dm_pf_projects WHERE title = '".$ws_title."') ORDER BY title DESC LIMIT 1";
$result_query = mysql_query($query) or die("Error: ".mysql_error());
while ($row = mysql_fetch_assoc($result_query)) {
$result_title = $row['title'];
}
$result_title = substr($result_title,0,6);
echo $result_title;
Your SQL could do with some rework (though not the reason for your issue). No need for the nested select (which can also cause an error if it returns > 1 row). Try a join.
$sql = "
SELECT title FROM le7dm_pf_tasks t
INNER JOIN le7dm_pf_projects p ON t.project = p.id
WHERE p.title = '{$ws_title}'
ORDER BY title DESC LIMIT 1
";
You are also iterating over an unknown number of rows using the while statement. And then you exit and attempt a substring. How do you know that the last row iterated in the while had a value.
Try outputting $result_title inside the while loop itself to confirm data.
echo $result_title;
If you truly only have a single row, there is no need for the while loop. Just do
$row = mysql_fetch_assoc($result_query);
strip_tags($ws_title); - is what did it! The title was wrapped in an anchor tag that linked to that particular project page.
Thanks for all the good suggestions though. I'm gonna use some of them in the future when bug testing.
Related
I'm working on a small self made CMS for a Blog.
Currently I have simple MySql database set up like this:
For a main page, I have a index.php which is supposed to fetch all the articles and print out their name, date, excerpt and all the tags this article has. Now the problem is I have no idea on how to print out all the tags of all articles, under each of them.
The articles are pulled and printed using a simple mysqli:
$sql = "SELECT id, nazwa, data, wstep, imgs, zdj
FROM art WHERE id BETWEEN $end AND $start ORDER BY id desc;";
$result = mysqli_query($link, $sql);
if(!$result){
echo "Problem\n";
echo "Kod problemu: ". mysqli_error($link);
exit;
}
...
while ($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
//Barfing out all the content
}
I would like to have a second query, inside that fetch assoc, but when I do that, the website fails to load posts completely.
Is there another, good way of doing this?
Why not modifying your query to include tags in line with articles? I'm not sure if this is what you wanted, but it would be simple enough to concatenate it w/ commas:
SELECT
a.id,
a.nazwa,
a.data,
a.wstep,
a.imgs,
a.zdj,
GROUP_CONCAT(t.name) all_tags
FROM
art a INNER JOIN tagarts ta ON a.id = ta.id INNER JOIN tags t ON t.idt = ta.idt
WHERE id BETWEEN $end AND $start
GROUP BY a.id
ORDER BY a.id desc;
Then do a split in PHP and voila!
foreach($rows as $row) {
foreach(explode(',', $row['all_tags']) as $tag) {
echo '{$tag}';
}
}
This would be much more preferable than using some query instead of that inner foreach.
In any case, your remark that everything breaks when you actually try doing these queries in a loop probably means that you simply have some issues with your code. Still, even if it worked, it would work slow.
But you might actually need something completely different, in which case don't kill me but someone else.
I'm building a website and I need an array of 'related posts', the array $previews. This array needs to contain three arrays, each of them with data from a related post. I tried getting the data using this code, but it fails:
$previews = array();
$query = mysql_query("SELECT TOP 3 title, url, category, date_published FROM post WHERE NOT(id = '$my_id') AND category = '$my_category' ORDER BY NEWID()");
while($row = mysql_fetch_assoc($query)) $previews[] = $row;
I keep getting "Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given".
Can somebody please help me out?
Thank you.
Try this, it may work.
$query = mysql_query("SELECT TOP 3 title, url, category, date_published FROM post WHERE NOT(id = '".$my_id."') AND category = '".$my_category."' ORDER BY NEWID()");
while($row = mysql_fetch_assoc($query)) $previews[] = $row;
If your query fails to return any values due to error or permission access issues, $query will be be the boolean false.
You are getting this error because something with your query went wrong. Try to call die(var_dump(mysql_error($query))); to see what went wrong.
Your SQL is wrong. It looks like MsSQL not MySQL. I'm not sure about the whole thing, but TOP 3 should be removed and you should use limit at the end of the query.
Was:
SELECT TOP 3 title, url, category, date_published FROM post WHERE NOT(id = '$my_id') AND category = '$my_category' ORDER BY NEWID()
Should be:
SELECT title, url, category, date_published FROM post WHERE id != '$my_id' AND category = '$my_category' ORDER BY NEWID limit 3
It works with:
$query = mysql_query("SELECT title, url, category, date_published FROM post WHERE NOT(id = '$my_id') AND category = '$my_category' limit 3");
So the problem must be the ORDER BY NEWID().
Thanks for your comments everybody.
Typically you would check to see if the query was successful before operating on the result object:
<?php
$query = "SELECT fields FROM table";
$result = mysql_query($query);
if ($result)
{
// operate on results i.e. fetching assoc etc.
}
else
{
// handle error accordingly
// use mysql_error() for debugging or maybe logging
}
?>
mysql_query() returns false if the query was unsuccessful.
Also, as a few others have mentioned, your SQL syntax is incorrect and looks like TSQL/MSSQL.
I have written some code to update certain rows of a table with a decreasing sequence of numbers. To select the correct rows I have to JOIN two tables. The last row in the table needs to have a value of 0, the second last -1 and so on. To achieve this I use ORDER BY DESC. Unfortunately my code brings up the following error:
Incorrect usage of UPDATE and ORDER BY
My reading suggests that I can't use UPDATE, JOIN and ORDER BY together. I've read that maybe subqueries might help? I don't really have any idea how to change my code to do this. Perhaps someone could post a modified version that will work?
while($row = mysql_fetch_array( $result )) {
$products_id = $row['products_id'];
$products_stock_attributes = $row['products_stock_attributes'];
mysql_query("SET #i = 0");
$result2 = mysql_query("UPDATE orders_products op, orders ord
SET op.stock_when_purchased = (#i:=(#i - op.products_quantity))
WHERE op.orders_id = ord.orders_id
AND op.products_id = '$products_id'
AND op.products_stock_attributes = '$products_stock_attributes'
AND op.stock_when_purchased < 0
AND ord.orders_status = 2
ORDER BY orders_products_id DESC")
or die(mysql_error());
}
Just remove your ORDER BY in your UPDATE statement, then put it in your SELECT statement.
sample:
$query = "SELECT ........ ORDER BY ..."
$result = mysql_query($query);
while(....){.... }
UPDATE statement wont accept ORDER BY clause.
You could use a SELECT call to loop through the rows, and include your WHERE and ORDER BY statements there, and then within your while($row = mysql_fetch_assoc($query)){ loop you'd have your UPDATE table SET key = 'value' WHERE id = '{$row['id']}' statement.
Sure, this would require executing mysql_query() a lot, but it'll still run pretty fast, just not at the same speed a single query would.
Why do you need an order by in an update. I think you could just remove it and you update will update everything that respect your where statement.
EDIT: And maybe you could call a stored proc to simplify your code
I have a while loop of a mysql call but I also am trying to run another mysql query inside of the while loop but it is only doing it once. I can not figure it out.
Here is my code:
$sql = "SELECT * FROM widget_layout WHERE module_id=".mysql_real_escape_string($id)." AND state='".mysql_real_escape_string($page)."' AND position=".mysql_real_escape_string($position);
$query = mysql_query($sql);
while ($row = mysql_fetch_assoc($query)) {
$layout .= $row['widget_id'].'<br/>'; //test if it is looping through all rows
$sql2 = "SELECT title FROM widgets WHERE id=".$row['widget_id'];
$query2 = mysql_query($sql2);
$result2 = mysql_fetch_array($query2);
$layout .= $result2[0]; // test the title output
}
It is looping through the first query no problem but the second query is only load the title of the first widget, return null for the rest. Any idea of why this is doing this?
You don't have to use a WHILE loop -- this can be done in a single SQL statement:
SELECT wl.widget_id,
w.title
FROM WIDGET_LAYOUT wl
JOIN WIDGETS w ON w.id = wl.widget_id
WHERE wl.module_id = mysql_real_escape_string($id)
AND wl.state = mysql_real_escape_string($page)
AND wl.position = mysql_real_escape_string($position);
The issue with NULL title values depends on if the WIDGET.title column is NULLable, or there isn't a record in the WIDGETS table for the id value. You need to check the values coming back from the first query, confirm they have supporting records in the WIDGETS table first, then look at the title value...
Directly from the mysql_query() docs: multiple queries are not supported. Your innery query is killing the outer one.
I have the following query:
$select = mysql_query("SELECT * FROM posts WHERE id = $postIds");
while ($return = mysql_fetch_assoc($select)) {
$postUrl = $return['url'];
$postTitle = $return['title'];
echo "<h1><a href='$postUrl'>".$postTitle."</a></h1>";
}
Now the problem is, the variable $postIds often times contain the same id multiple times. So the title of the post echos itself multiple times. Is there a way to have it echo only once?
Use DISTINCT in your query: SELECT DISTINCT url, title FROM posts WHERE id =
http://php.net/manual/en/function.array-unique.php
You can give that a shot. You might want to make a check to ensure $postIDs will be an array, or you'll probably get a warning error.
You want all the posts to be output, but only output the title(s) once? Use SELECT DISTINCT title, url FROM posts WHERE id = $postIds; for your query
Or do you only want the first matching record output? Two choices here:
Add a LIMIT clause to the query: "SELECT * FROM posts WHERE id = $postIds LIMIT 1";
Eliminate the while() loop in the script and just call the fetchrow once.