sql & php associative array - php

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.

Related

in_array() validation not working

So i'm trying to use in_array to call a list back from the database and then i'm checking with those results to see if the field "Title" is present in the array by doing the following.
$qGetAllTitles = "SELECT ArticleTitle FROM articles
UNION
SELECT ArticleTitle FROM temp_article";
$rGetAllTitles = mysqli_query($dbc, $qGetAllTitles);
$GetAllTitlesRow = mysqli_fetch_array($rGetAllTitles, MYSQLI_ASSOC);
if (in_array($Title, $GetAllTitlesRow['ArticleTitle'])){
$errors[0] = "The title is already taken by another article, please pick a different title";
} else {
$TTL = mysqli_escape_string($dbc, trim($Title));
$errors[0] = "Title worked";
}
I'm aware that the strings are case sensitive (and i'm looking how to negate this but that's another unrelated question)
My problem is, when i put an already used article title into the title field (which works, all other checks i use work, just not this one) it still returns "title worked", even though the check shouldn't unless the title is unique.
I've checked the SQL input in phpmyadmin (for my MySQL database) and that works getting all (3) results and the method of fetching the query is reused from elsewhere in my code, which also works, same as the in_array check so i'm really not sure why it's not working.
Your query returns multiple rows but you are only retrieving data for the first row. So unless the title matches the first row's title you won't find any duplicates. You need to do one of the following:
1) Loop through the result set and make an array of page titles before using in_array()
$GetAllTitlesRows = array();
while ($row = mysqli_fetch_array($rGetAllTitles, MYSQLI_ASSOC)) {
$GetAllTitlesRows[] = $row['ArticleTitle'];
}
or
2) Just search for any articles using that title right in your query which makes the code a whole lot simpler (recommended). In other words, use a WHERE clause specifically looking for that title in the ArticleTitle field. If you get any results you know it is taken.
$qGetAllTitles = "SELECT ArticleTitle FROM articles WHERE ArticleTitle = '$Title'
UNION
SELECT ArticleTitle FROM temp_article WHERE ArticleTitle = '$Title'";
$rGetAllTitles = mysqli_query($dbc, $qGetAllTitles);
if (mysqli_num_rows($rGetAllTitles) > 0){
$errors[0] = "The title is already taken by another article, please pick a different title";
}

How to get max(id) of row data MySql

I want to get the maximum id of row data. In my table first column is id then firstname and etc.
this is the sql command I used to get the max(id) of row data.
<?PHP $maxid=$this->db->query("SELECT MAX(id) FROM `emplyee_personal_details`");
print_r( $maxid) ;?>
but it prints bunch of data as it is a array. But I need only the maximam id of row data for validation before data inserting and updating.
How to get the maxid. I use codeigniter framework.
Try this:
$maxid = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row()->maxid;
UPDATE
This will work even if your table is empty (unlike my example above):
$maxid = 0;
$row = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row();
if ($row) {
$maxid = $row->maxid;
}
The problem with using a raw query like "SELECT MAX(id) ..." is it is not abstract and may not work for every SQL engine. I think the active record way to do it is like this:
$this->db->select_max('id');
$query = $this->db->get('emplyee_personal_details');
// Produces: SELECT MAX(id) as age FROM emplyee_personal_details
See: http://ellislab.com/codeigniter/user-guide/database/active_record.html
SELECT id FROM table ORDER BY id DESC LIMIT 1
That will get you the highest id value, and when I read this, "it prints bunch of data as it is a array" I get the sense that what you really want is a part of that array. DB queries always return complex structures like arrays or objects. So if you wanted just the scalar value (the number as an integer) you might use something like this:
$maxid = (int)$maxid['id'];
or like this (if you have an object):
$maxid = (int)$maxid->id;
HTH, ~Ray
Try this,hope it helps,
return $this->db->select_max('id')
->get('your_table_name')
->row()->id;
public function getMaxCategoryId() {
$query = $this->db->query("SELECT category_id+1 AS maxid FROM " . DB_PREFIX . "category ORDER BY category_id DESC LIMIT 1");
return $query->row['maxid'];
}
error undefined index maxid
<?php`$qry = "select max(ID)+1 As ID from records";`
$result = $con->query($qry);
$row = $result->fetch_assoc();`echo "New ID To Enter = ".$row["ID"];?>
After Connection Just Write This Code It Will Work

PHP query returns no results

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.

MySQL Query Isnt Returning A Result

i got a fairly simple layout going and for the life of me i cant figure out why this returns nothing:
<?php
// Gets A List Of Comic Arcs
$result = mysql_query("SELECT * FROM ".$db_tbl_comics." GROUP BY ".$db_fld_comics_arc." ORDER BY ".$db_fld_comics_date." DESC LIMIT 20");
while ($comic = mysql_fetch_array($result)) {
// Now Go Back And Count Issues For Each Comic Arc Above
$result22 = mysql_query("SELECT * FROM ".$db_tbl_comics." WHERE ".$db_fld_comics_arc."=".$comic[$db_fld_comics_arc]);
$total_issues = mysql_num_rows($result22);
echo $total_issues;
}
?>
No other query is refered to as $result22.
$comic[] has already been defined in the previous query.
echo mysql_error($result22); returns no errors.
Let me know if you need any other info.
I am assuming that the column $db_fld_comics_arc is a string.
Change:
$result22 = mysql_query("SELECT * FROM ".$db_tbl_comics." WHERE ".$db_fld_comics_arc."=".$comic[$db_fld_comics_arc]);
To:
$result22 = mysql_query("SELECT * FROM ".$db_tbl_comics." WHERE ".$db_fld_comics_arc."='".$comic[$db_fld_comics_arc]."'");
Am I wrong? If so, let me know the table structure, and what your error reporting is set to.
Also, could you let us know the purpose of your SQL? It may also be possible to put the data together in one query, instead of looping sql queries through, and using data from a first query.
Maybe it is because $db_fld_comics_arc is in $comic[$db_fld_comics_arc]
if both are the same then you should try replacing $db_fld_camics_arc with $comic[$db_fld_comics_arc].

Is there a way to echo this only once and not have it repeat?

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.

Categories