How to get integer output from 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 repeat this, the conclusion is:

resource id #4

How can I make this a simple whole?

+3
source share
5 answers
$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 the resource of the result, not the value in the query. You must use fetch functions to get the actual data .

If you want this code to be cleaner, make sure that $resultneither false(request error) $rownor false(nothing found).

+6
source

, .
, OP , , .

, :

<?
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];
  }
}

- , :

$tagID = dbgetvar("SELECT tagID FROM tags WHERE tagName = %s",$tag);
echo $tagID;
+3

. :

$resource = mysql_query("SELECT tagID FROM tags WHERE tagName = '$tag'");
$tagID = mysql_fetch_assoc($resource);

print_r($tag_id);

(.. ), :

$resource = mysql_query("SELECT tagID FROM tags WHERE tagName = '$tag'");
while($tagID = mysql_fetch_assoc($resource)) {
    echo $tagID['tagID'];
}

, , mysqli. , , mysql_*. :

mysqli, , , MySQL, , MySQL 4.1.3 . mysqli PHP 5 .

mysqli , mysql:

  • -

:

MySQL 4.1.3 , , [MySQL].

+1

mysql_query "" false . # 44, .

, mysql_query mysql_fetch_assoc . ( mysql_fetch_row mysql_fetch_field ). :

$query = "SELECT tagID FROM tags WHERE tagName = '$tag'";
$result = mysql_query($query);
$array = mysql_fetch_assoc($result);

$tagID = $array['tagID']; //your integer.

. PHP- mysql_query. .

+1

An SQL query always returns the result of an SQL resource, possibly an unreadable object containing the results of the query. Because of how databases are stored, the way users can manipulate data, as well as the amount of data, is easier to store as an identifier than as an object.

To get the data you need, you must first convert them 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 from which you want to extract data (

Or object:

$result = mysql_query("SELECT tagID FROM tags WHERE tagName = '$tag'");
$object = mysql_fetch_object($result);
echo $object->tagID;

(where the column $ object-> is the column from which you want to extract data)

Hope this helps.

0
source

Source: https://habr.com/ru/post/1792597/


All Articles