Can I do a mysql_query in eval()? - php

The community builder I am using requires php blocks to be parsed through eval(). Can I use the mysql_query in eval? If not how can I call info from the database in this eval()?
Here's my code so far:
$iProId = $this->oProfileGen->_iProfileID;
$sCat = mysql_query("SELECT genres from Profiles WHERE ID = ". $iProId);
print_r($sCat);
This gives me:
Resource id #167

If that code gave you that result when eval'd then yes, you can use mysql_query in eval and the rest of your question boils down to how you would have to use that result set.
In that case I would suggest something like:
$iProId = $this->oProfileGen->_iProfileID;
$sCat = mysql_query("SELECT genres from Profiles WHERE ID = ". $iProId);
while($row = mysql_fetch_assoc($sCat)) {
print_r($row);
}
To loop over all rows in the resultset. If you want to know more the PHP website has all the goods on how to use mysql_* functions.

Have a look at mysql_fetch_array (and the other mysql_fetch_* functions) for how to get your data from the resource.

Using a query in eval() sounds strange to me, but you code is working right. mysql_query returns a mysql resource. Then you need to you mysql_fetch_array, mysql_fetch_row, or mysql_fetch_assoc to read it like:
$iProId = $this->oProfileGen->_iProfileID;
$result = mysql_query("SELECT genres from Profiles WHERE ID = ". $iProId);
$sCat = mysql_fetch_assoc($result);
print_r($sCat);

Related

Counting the values of rows in a column and using the total value in PHP

I know this is something simple. I'm just forgetting something.
I'm counting the values of the rows in the "numberattending" column of my database.
When I run the SQL statement
SELECT COUNT(numberattending) AS Total FROM RSVP
in the mySQL window I get the total I'm looking for.
When I try to extract that value and echo "num_seats" I get "Resource id #3"
$num_seats = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
echo $num_seats;
What I'm I missing?
Thanks for any help ahead of time.
$num_seats represents a MySQL Resource, not the value of the field selected. You'll need to use either mysql_fetch_array() or mysql_fetch_object() depending on which you prefer.
For example:
$number = mysql_fetch_array($num_seats);
echo $number['Total'];
It's also worth noting that the mysql_* family of functions are now deprecated, and you should really be using MySQLi or PDO.
You need to loop through the result sets:
From the PHP site:
// Use result // Attempting to print $result won't allow access to
information in the resource // One of the mysql result functions must
be used // See also mysql_result(), mysql_fetch_array(),
mysql_fetch_row(), etc.
$num_seats = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
while ($row = mysql_fetch_assoc($num_seats )) {
echo $row['total'];
}
PS: As others will surely tell you, use of the mysql* functions have been deprecated. Look for the mysqli functions instead.
Try
$query = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
$result = mysql_fetch_row($query);
echo $result['Total'];

Return and parse results from mysql_fetch_assoc

I'm having trouble getting values out of my array returned from a MySQL query.
The results that are being returned are a table with these columns:
|team_id|name|pos|available|
There are multiple rows in the result. I need to go through each row and extract name and pos into their respective variables.
Here is my code:
$query = sprintf("SELECT * FROM `player_user` WHERE team_id = '$teamID[0]'");
$answer = mysql_query($query);
if ($answer === FALSE)
die(mysql_error());
while($row = mysql_fetch_assoc($answer))
{
$pname = $row['name'];
$pos = $row['pos'];
... do something with $pname and $pos
}
The example above should work, as long as the mysql query will return data. You should verify this using var_dump($row); inside the loop.
Although you should use the mysqli extension or PDO to access mysql databases. mysql_* functions as you currently use are deprecated and will once being dropped from PHP
You should use mysqli_fetch_array instead of mysql_fetch_assoc. That should return the results as you want.
http://php.net/manual/en/mysqli-result.fetch-array.php

php: iterate recordset - easier way?

i've just changed from ASP to php and i'm a bit confused about the way php is handling recordsets.
i'd like to know if there's an easier way to iterate a recordset by creating a php class.
here's the ASP syntax to show what i mean:
sq = "select * from myData"
set rs = db.execute(sq)
do while not rs.eof
response.write rs("name") // output data (response.write = echo)
rs.movenext
loop
any ideas?
thanks
You'd pretty much do the same thing...
$sql = "select * from myData";
$result = mysql_query($sql) or die(mysql_error()); //executes query
while($row = mysql_fetch_array($result)){ //will automatically return false when out of records
echo $row['name'];
}
You're probably looking for a function contains word fetch in it's name.
E.g. mysql_fetch_assoc() or $pdo->fetchAll().
Most of database API functions in PHP returns some sort of pointer variable called "resource", which can be passed to the fetch-family function, like this:
$res = mysql_query();
while($row = mysql_fetch_assoc($res)){
echo $row['name'];
}
However, some of them (like PDO's fetchAll method) returns but regular PHP array, which you can iterate using as regular foreach operator.

How to get an integer output from an SQL query

I have an SQL query as follows:
$tagID = mysql_query("SELECT tagID FROM tags WHERE tagName = '$tag'");
echo $tagID;
I want $tagID to contain something like 3, or 5, or any integer. But when I echo it, the output is:
resource id #4
How can I make it a simple integer?
$result = mysql_query("SELECT tagID FROM tags WHERE tagName = '$tag'"); // figure out why an existing tag gets the ID zero instead of 'tagID'
$row = mysql_fetch_assoc($result);
echo $row["tagID"];
mysql_query() returns result resource, not the value in the query. You have to use fetch functions to get the actual data.
If you want this code to be cleaner, check that $result is not false (query error) and $row is not false (nothing found).
It's always a shock to see not a single programmer in the answers.
I know the OP is not a programmer too, so, my answer would be totally in vain but what the heck.
Here is a example of a thing called a function:
<?
function dbgetvar(){
$args = func_get_args();
$query = array_shift($args);
foreach ($args as $key => $val) {
$args[$key] = "'".mysql_real_escape_string($val)."'";
}
$query = vsprintf($query, $args);
$res = mysql_query($query);
if (!$res) {
trigger_error("dbgetarr: ".mysql_error()." in ".$query);
return FALSE;
} else {
$row = mysql_fetch_row($res);
if (!$row) return NULL;
return $row[0];
}
}
this code can be saved in some configuration file and then called in this manner:
$tagID = dbgetvar("SELECT tagID FROM tags WHERE tagName = %s",$tag);
echo $tagID;
The mysql_query function, by itself, returns a 'resource' on success and false on error. In this case, you're getting a resource that has id #44, which is what you might expect from that function.
What you could do is take the result of mysql_query and use mysql_fetch_assoc to convert the resource to an associative array. (Also check out mysql_fetch_row, or mysql_fetch_field for other techniques). Here's a typical way of structuring this problem:
$query = "SELECT tagID FROM tags WHERE tagName = '$tag'";
$result = mysql_query($query);
$array = mysql_fetch_assoc($result);
$tagID = $array['tagID']; //your integer.
Please see the mysql_query PHP Manual entry for more info. Check out the user comments at the bottom for particularly good advice and sample code.
You're missing a single step. Try this:
$resource = mysql_query("SELECT tagID FROM tags WHERE tagName = '$tag'");
$tagID = mysql_fetch_assoc($resource);
print_r($tag_id);
If your query returns more than one row (i.e. there is more than one tag with the same tagName), you'll want to put it in a loop:
$resource = mysql_query("SELECT tagID FROM tags WHERE tagName = '$tag'");
while($tagID = mysql_fetch_assoc($resource)) {
echo $tagID['tagID'];
}
Addendum
Although the above code will solve your problem, I urge you to stop right there and learn about mysqli instead. It's a much newer, more robust solution than using the mysql_* functions. From the docs:
The mysqli extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. The mysqli extension is included with PHP versions 5 and later.
The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:
Object-oriented interface
Support for Prepared Statements
Support for Multiple Statements
Support for Transactions
Enhanced debugging capabilities
Embedded server support
Also from the docs:
If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use [the MySQLi] extension.
A SQL query always returns a SQL Resource result, an arguably unreadable object that contains the results of the query. Because of the way that databases are stored, the way that users may want to manipulate data, and the sheer amount of data, it's easier to store it as an identifier than as an object.
To get the data, you need, you must first convert it to an array:
$result = mysql_query("SELECT tagID FROM tags WHERE tagName = '$tag'");
$row = mysql_fetch_assoc($result);
echo $row["tagID"];
(Where $row[column] is the column you want to pull data from(
Or an object:
$result = mysql_query("SELECT tagID FROM tags WHERE tagName = '$tag'");
$object = mysql_fetch_object($result);
echo $object->tagID;
(where $object->column is the column you want to pull data from)
Hope this helps.

Get the full result

Is there a PHP function to get the full result with a mysql query in a multidimensional array?
SELECT * FROM table
Usually I would make something like this:
$query = mysql_query = ("SELECT * FROM table");
while ($result = mysql_fetch_array($query){
echo $result[0];
}
You can create your own function like mysql_fetch_array_complete() and imagine that it's builtin ;-)
If you are using PDO to access mysql there is.
http://www.php.net/manual/en/pdostatement.fetchall.php
Otherwise you need to do it yourself.
$query = mysql_query = ("SELECT * FROM table");
$all_results = array();
while ($result = mysql_fetch_array($query){
$all_results[] = $result;
}
print_r($all_results);
The $all_results variable will be a multi-dimensional array with all the records.
You could always write your own function to do this, but it would often lead to an unnecessary iteration through the result set (once when you call your function, another time when you actually USE the resulting array).
Since you're in php5, you could create a database result class that implements the Iterator interface. Then, you can use your class in foreach () loops and have much of the ease-of-use that you get from an array.
As of PHP 5.3 there is a built in function:
fetch_all

Categories