How to get an integer output from an SQL query - php

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.

Related

Selecting data from database in a foreach loop is always 7

I am making this for adding storage in an admin section of my site. I have encountered a very strange problem. $voorraad always equals 7, no matter what product I choose(id changes), it keeps coming up as 7.
I am echoing $voorraad by making a session and echoing it in an other page.
The table name and column is correct. Can someone explain why $voorraad always equals seven?
If you need more code, I will provide it.
$cartItems = $cart->contents();
foreach($cartItems as $item){
$sql = ("SELECT voorraad FROM Producten WHERE id =".$item['id']);
$voorraad = (float)mysql_query($sql);
$itm = (float)$item['qty'];
$_SESSION['voorraad'] = $voorraad;
$_SESSION['itm'] = $itm;
$up = $itm + $voorraad;
$sql1 = "UPDATE Producten SET voorraad = $up WHERE id =".$item['id'];
$res = mysql_query($sql1);
}
Because you are converting the mysql response object into a float, you're not actually getting the result.
$voorraad = mysql_query($sql);
$voorraad = mysql_fetch_assoc($voorraad)['voorraad']; // get the row, and the cell from the row
$voorraad should now contain the actual response.
First of all: You are wide open to SQL injection. Filter and validate your user input before passing it to the query.
Second thing: Don't use mysql_*, it's deprecated and considered not safe anymore. Use mysqli_* or PDO instead.
mysql_query() returns a resource, which you try to cast to float. To access the Value(s) you have to use
$result = mysql_query(....);
$row = mysql_fetch_array($result);
$voorraad = $row['voorraad'];
First of all - mysql_*-functions are deprecated and if you update your php version, you couldn't use them anymore. Second, you should use prepared statements, to prevent sql injections.
Back to your main problem:
You execute the query, but you never fetch the result, so you just cast a resource return type to an float, which gives you your unexpected result. In your case, you could use mysql_fetch_assoc to get the row, you want
Because you are converting the mysql response object into a float, you're not actually getting the result.
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$column = $row['column_name'];

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

Can I do a mysql_query in eval()?

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);

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 "field names" using PHP ADOdb?

I'm using PHP ADOdb and I can get the result set:
$result = &$db->Execute($query);
How do I get the field names from that one row and loop through it?
(I'm using access database if that matters.)
It will depend on your fetch mode - if you setFetchMode to ADODB_FETCH_NUM (probably the default) each row contains a flat array of columns. If you setFetchMode to ADODB_FETCH_ASSOC you get an associative array where you can access each value by a key. The following is taken from ADODB documentation - http://phplens.com/lens/adodb/docs-adodb.htm#ex1
$db->SetFetchMode(ADODB_FETCH_NUM);
$rs1 = $db->Execute('select * from table');
$db->SetFetchMode(ADODB_FETCH_ASSOC);
$rs2 = $db->Execute('select * from table');
print_r($rs1->fields); # shows array([0]=>'v0',[1] =>'v1')
print_r($rs2->fields); # shows array(['col1']=>'v0',['col2'] =>'v1')
To loop through a set of results:
$result = &$db->Execute($query);
foreach ($result as $row) {
print_r($row);
}
Small improvement to the solution posted by #thetaiko.
If you are ONLY needing the field names, append LIMIT 1 to the end of your select statement (as shown below). This will tell the server to send you a single row with column names, rather than sending you the entire table.
SELECT * FROM table LIMIT 1;
I'm working with a table that contains 9.1M records, so this minor change speeds up the query significantly!
This is a function I use to return a field array - I've stripped out some extra stuff that, for example, allows it to work with other DBs than MySQL.
function getFieldNames($strTable, $cn) {
$aRet = array();
# Get Field Names:
$lngCountFields = 0;
$strSQL = "SELECT * FROM $strTable LIMIT 1;";
$rs = $cn->Execute($strSQL)
or die("Error in query: \n$strSQL\n" . $cn->ErrorMsg());
if (!$rs->EOF) {
for ($i = 0; $i < $rs->FieldCount(); $i++) {
$fld = $rs->FetchField($i);
$aRet[$lngCountFields] = $fld->name;
$lngCountFields++;
}
}
$rs->Close();
$rs = null;
return $aRet;
}
Edit: just to point out that, as I say, I've stripped out some extra stuff, and the EOF check is therefore no longer necessary in the above, reduced version.
I initally tried to use MetaColumnNames, but it gave differing results in VisualPHPUnit and actual site, while running from the same server, so eventually
I ended up doing something like this:
$sql = "select column_name, column_key, column_default, data_type, table_name, table_schema from information_schema.columns";
$sql .= ' where table_name="'.$table.'" and table_schema="'.$database_name.'"';
$result = $conn->Execute($sql);
while($row = $result->fetchRow()) {
$out[] = strToUpper($row['column_name']);
}
I think it should work with mysql, mssql and postgres.
The benefit of doing it like this, is that you can get the column names, even if a query from a table returns an empty set.
If you need the Coloumn names even for empty tables or for joins about multiple tables use this:
$db->Execute("SELECT .......");
// FieldTypesArray - Reads ColoumnInfo from Result, even for Joins
$colInfo = $res->FieldTypesArray();
$colNames = array();
foreach($colInfo as $info) $colNames[] = $info->name;
The OP is asking for a list of fieldnames that would result of executing an sql statement stored in $query.
Using $result->fetchRow(), even with fetch mode set to associative, will return nothing if no records match the criteria set by $query. The $result->fields array would also be empty and would give no information for getting the fieldnames list.
Actually, we don't know what's inside the $query statement. Besides, setting limit to 1 may not compatible with all database drivers supported by PHP ADOdb.
Answer by Radon8472 is the right one, but the correct code could be:
$result = $db->Execute($query);
// FieldTypesArray - an array of ADOFieldObject Objects
// read from $result, even for empty sets or when
// using * as field list.
$colInfo = [];
if (is_subclass_of($result, 'ADORecordSet')){
foreach ($result->FieldTypesArray() as $info) {
$colInfo[] = $info->name;
}
}
I have the habit of checking the class name of $result, for as PHP ADOdb will return false if execution fails.

Categories