I am trying to access some information from mysql, but am getting the warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource for the second line of code below, any help would be much appreciated.
$musicfiles=getmusicfiles($records['m_id']);
$mus=mysql_fetch_assoc($musicfiles);
for($j=0;$j<2;$j++)
{
if(file_exists($mus['musicpath']))
{
echo ''.$mus['musicname'].'';
}
else
{
echo 'Hello world';
}
}
function getmusicfiles($m_id)
{
$music="select * from music WHERE itemid=".$s_id;
$result=getQuery($music,$l);
return $result;
}
Generally, the mysql_* functions are used as follows:
$id = 1234;
$query = 'SELECT name, genre FROM sometable WHERE id=' . $id;
// $query is a string with the MySQL query
$resource = mysql_query($query);
// $resource is a *MySQL result resource* - a mere link to the result set
while ($row = mysql_fetch_assoc($resource)) {
// $row is an associative array from the result set
print_r($row);
// do something with $row
}
If you pass something to mysql_fetch_assoc that is not a MySQL result resource (whether it's a string, an object, or a boolean), the function will complain that it doesn't know what to do with the parameter; which is exactly what you are seeing.
A common gotcha: you get this warning if you pass something (other than a valid query string) to mysql_query:
$id = null;
$query = 'SELECT name, genre FROM sometable WHERE id=' . $id;
$res = mysql_query($query);
// $res === FALSE because the query was invalid
// ( "SELECT name, genre FROM sometable WHERE id=" is not a valid query )
mysql_fetch_assoc($res);
// Warning: don't know what to do with FALSE, as it's not a MySQL result resource
Without seeing the code of getmusicfiles there's not a lot we can really help you with. You should be returning a valid mysql resource in that function.
As others have noted, you need to return a valid mysql resource into the mysql_fetch_assoc function to retrieve the next row. For example:
$sql = "select * from table";
$resultSet = mysql_query($sql) or die("Couldn't query the database.");
echo "Num Rows: " . mysql_num_rows($resultSet);
while ($resultRowArr = mysql_fetch_assoc($resultSet)) {
...
}
I think you need to specify what the function getQuery()
$result=getQuery($music,$l);
does
It depends on what exactly getmusicfiles() does. It must return a result of mysql_query() function call, then it will be a "valid MySQL result".
And you most probably wanted to put the line $mus=mysql_fetch_assoc($musicfiles) inside of the for cycle to fetch several rows one after another.
function getmusicfiles($m_id) {
$music="select * from music WHERE itemid=".$s_id;
$m_id != $s_id ?
Related
I am trying to select a table within my database with a GET Method.
Now when I hardcode the value of the variable in there (the table name) it works as expected and it returns the values in an array.
But when I try to determine the table name through a variable, I get the following error:
Fatal error: Call to a member function fetch_array() on a non-object in
Now I have tried the var_dump($result); but that returns bool(false).
Now the variable does carry a value, because when I echo it back to the screen it gives the value I would expect.
So why does not return the value when making the query for my table search???
$result = $mysqli->query("SELECT * FROM PodcastSermons WHERE sermonSeries = ". $series); //This where a change needs to happen
var_dump($result);
$posts = array();
while($row = $result->fetch_array())
{
$ID=$row['ID'];
$sermonTitle=$row['sermonTitle'];
$sermonSpeaker=$row['sermonSpeaker'];
$sermonSeries=$row['sermonSeries'];
$sermonDate=$row['sermonDate'];
$linkToImage=$row['linkToImage'];
$linkToAudioFile=$row['linkToAudioFile'];
$posts []= array (
'ID'=> $ID,
'sermonTitle'=> $sermonTitle,
'sermonSpeaker'=> $sermonSpeaker,
'sermonSeries'=> $sermonSeries,
'sermonDate'=> $sermonDate,
'linkToImage'=> $linkToImage,
'linkToAudioFile'=> $linkToAudioFile
);
}
$response['posts'] = $posts;
var_dump($posts);
PS I have read about the depreciation in mysql style and that I know have to use mysqli writing. I am running PHP Version 5.2.6-1+lenny16
If the $series is a string you need to put quotes around the variable..
Try...
$result = $mysqli->query("SELECT * FROM PodcastSermons WHERE sermonSeries = '". $series ."'");
Hope it helps.
Now I have tried the var_dump($result); but that returns bool(false).
Because your query failed.
Try:
if( ! $result = $mysqli->query("SELECT * FROM PodcastSermons WHERE sermonSeries = ". $series); ) {
echo "An error has occurred: \n" . var_export($mysqli->error_list, TRUE);
} else {
//do stuff
}
The central question seems to me: Where does $series come from? Where does that variable ever get initialized?
If you're passing this in from the web form, two things: either use $_GET or $_POST (whatever action you use in your form). And then you have to sanitize what comes from there, in order to not be vulnerable to SQL injection attacks. Prepared statements are your friend in this case; they help harden your script against this kind of attacks.
try this
$result = $mysqli->query("SELECT * FROM PodcastSermons WHERE sermonSeries = '$series' ");
$result = $mysqli->query("SELECT * FROM PodcastSermons WHERE sermonSeries = ". $series); //This where a change needs to happen
You should be using Prepared Statements if the variable: $series is user defined.
$result->prepare("SELECT * FROM PodcastSermons WHERE `sermonSeries`=?");
$result->bind_param('s', $series);
$result->execute();
Also, Print_r($result); to check if your initial $result to see if it has been populated; Furthermore, in your SQL Query is sermonSeries properly matched to your SQL Table?
Update:
while($row = $result->fetch_array())
{
Try Modifying this to:
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
http://uk1.php.net/manual/en/mysqli-result.fetch-array.php
your query simply fails. check var_dump($series); before executing.
i assume it might be a string and you just don't quote it?
just a tip: first build a string with your commandtext before
calling $mysqli->query. and use that string (like $mysqli->query($cmd);
dump that string :) might open your eyes ;)
that way you can extract it and execute it directly against the database (f.e. phpmyadmin).
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given
my code php is :
function getResourceLevel($vid) {
$q = "SELECT * from " . TB_PREFIX . "fdata where vref = $vid";
$result = mysql_query($q, $this->connection);
return mysql_fetch_assoc($result);
}
Please Help me
It looks like mysql_query() has returned false.
This could by due to an error in your mysql syntax or due to a lack of permissions for accessing the database table you have requested.
In either case, you can try calling mysql_error() which will return a string with a best guess of what went wrong with your last mysql function.
Edit: As mentioned in some of the comments, the use of mysql_* functions is discouraged, so if you have opportunity you should update your code to use the mysqli or PDO MySQL extensions. Better yet, use something like Zend DB to move you one layer further away from the database API.
Try to echo your query and run in some mysql query browser and check if its giving required results.
function getResourceLevel($vid) {
$q = "SELECT * from " . TB_PREFIX . "fdata where vref = $vid";
echo $q;
$result = mysql_query($q, $this->connection);
return ($result) ? mysql_fetch_assoc($result) : false;
}
Try this
function getResourceLevel($vid) {
$q = "SELECT * from " . TB_PREFIX . "fdata where vref = $vid";
$result = mysql_query($q, $this->connection) || die(mysql_error());
return mysql_fetch_assoc($result);
}
Notice the || die(mysql_error()) statement.
This will stop the code and show the sql error that is being returned as false.
Hope this helps.
I'm looking to label a string based on database results. I have the following code:
$loc1 = "A";
$query = "SELECT loc FROM User where nick='".$users[$j]."'";
$loc = mysql_query($query);
if($loc == 1)
$loc1 = "A";
if($loc== 2)
$loc1 = "B";
The loc1 location is always "A". I've confirmed that the query works in MySQL and I'm having a difficult time understanding why this simple case is not working. I would appreciate your help!
The function mysql_query does not return the value of the column fetched, instead it returns a MySQL resource which you use to extract the column value returned by the query.
Change:
$loc = mysql_query($query);
to:
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if ($row = mysql_fetch_assoc($result)) {
$loc = $row["loc"];
}
You are storing mysql_query() return value in $loc which is a resource.
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
So, $loc is not 1 or neither equals to 2.
You need to use mysql_fetch_array / mysql_fetch_object, etc to manipulate the resource.
You must fetch the recordset with, in example mysql_fetch_row
Example #1 Fetching one row with mysql_fetch_row()
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
But, be careful with SQL injection attacks!
http://es.php.net/manual/en/security.database.sql-injection.php
I m creating function that process query and pass it's return result back. so I used following code:
function test(){
$query = "select * from mytable where id=123";
$data = mysql_query($query) or die(mysql_error());
return $data;
}
$info = test();
is it possible and can i use $info to get values as $info[0],$info[1]..
take a look at mysql_fetch_array function.
This function lets you iterate a query result which is a resource and turn each row into an array.Therefore you should use a while loop to get all rows in a resource;
You're missing one vital part, returning the result of mysql_query() just returns a result pointer not the dataset. You should add mysql_fetch_array, mysql_fetch_assoc or mysql_fetch_row:
function test(){
$query = "select * from mytable where id=123 LIMIT 1";
$data = mysql_query($query) or die(mysql_error());
$result = mysql_fetch_row($data);
return $result;
}
$info = test();
now you can use $info[0], $info[1]. When using mysql_fetch_assoc you could use $info['fieldname'].
I also added LIMIT 1, since you're sending a long an ID, this probably is unique and after 1 result there is most likely nothing else to be returned.
You can do that, however it is better in my experience to keep the database stuff encapsulated, so you don't expose MySQL resources outside of the database context that then further need mysql_fetch_assoc() and the like on them.
I would use PDO there, and return the results of fetchAll(PDO::FETCH_ASSOC). That way, $info has the data it needs without needing to run further database functions on.
<?php
$link = mysql_connect('localhost', 'USERNAME', 'PASSWORD');
mysql_select_db('DB NAME', $link);
function test()
{
$result = mysql_query("select * from wp_options");
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = $row;
}
return $data;
}
echo "<pre>";
print_r(test());
echo "</pre>";
mysql_close($link);
?>
function procLogin($username,$password){
$query = "SELECT *
FROM members
WHERE login = '".mysql_escape_string($username)."'
AND passwd = '".mysql_escape_string($password)."'";
$result = mysql_query($query);
//$values = array();
while($row = mysql_fetch_array($result))
{
return 'gg';
return(array($row['member_id']));
}
}
Not able to get the userlevel field.... nor anything....
Not sure exactly what your question is, but one problem is that you're returning from within this while loop:
while($row = mysql_fetch_array($result))
{
return 'gg';
return(array($row['member_id']));
}
In fact, you're returning twice from within the loop... so the procLogin() function will always return a value of "gg", unless something goes wrong with your SQL query.
In general, you should avoid return statements within any loop, as it creates confusion and can lead to unexpected results.
return(array($row['member_id']));
Looks wrong - it should be:
return($row['member_id']);
You shouldn't need to define the array in the return like that.
You also use mysql_fetch_array () which returns as a numerical index - the function you probably want is mysql_fetch_assoc which is much nicer to work with as it returns the values with the keys as the column name rather than a numerical index.
Here's it again with a few tidy ups:
function procLogin($username,$password){
$query = "SELECT *
FROM members
WHERE login = '".mysql_escape_string($username)."'
AND passwd = '".mysql_escape_string($password)."'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row['member_id'] > 0)
{
return ($row['member_id']);
}
else
{
return false;
}
}
I'm thinking, based on your comments about the userlevel, that you want to return the entire array rather than just the member_id ? Here's a slight edit to Meep3D's answer above:
function procLogin($username,$password){
$query = "SELECT *
FROM members
WHERE login = '".mysql_escape_string($username)."'
AND passwd = '".mysql_escape_string($password)."'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if (mysql_num_rows($result) > 0)
{
$row = mysql_fetch_assoc($result);
return $row;
}
else
{
return false;
}
}
This should return an array of all your table columns, if you are looking for the userlevel, presumably you should be able to access it something like:
$loginInfo = procLogin("theband","password1");
//if ($loginInfo) or something similar here
$level = $loginInfo['userlevel'];
So are you getting anything returned? That is to say, is it actually going into the while loop?
I'd use a mysql_error() function call straight after the mysql_query call to see if anything went wrong there.
Maybe there was no connection made, for example.
Are you still having issues? If so try something like:
echo $query;
after you define the query, then copy+paste that into phpmyadmin to check if there are any valid returns from the database.
After that try placing:
if (mysql_error())
{
trigger_error ("MySQL Error: ". mysql_error(), E_USER_ERROR);
}
Just after you call mysql_query. This should trigger an error if there is one giving you details of what went wrong.