문제

I have a PHP function that I am converting from using the mysql extension to the mysqli extension.

Everything is going okay, until here. I previously used a mysql_result to get a single piece of data. There is no direct equivalent in mysqli, so I have tried the following but it still doesn't work.

function getdbvalue($table,$value,$idfield,$id) {
  $qrytext = "SELECT $value FROM $table WHERE $idfield LIKE '$id'";
  $valueqry = mysqli_query($dbh,$qrytext);
  if (FALSE === $valueqry) die("Select failed: ".mysqli_error);
  $result = mysqli_fetch_row($valueqry);
  $returnvalue = $result[0];
  return $returnvalue;
}

I have verified that the variables are passing to the function okay, and the function is actually getting triggered. If I return $id I see the ID numbers.

I don't get an error for the query.

SOLVED:

I needed to add the database connection variable as a global in the function:

Working code:

function getdbvalue($table,$value,$idfield,$id) {
  global $dbh; // This was missing!
  $qrytext = "SELECT $value FROM $table WHERE $idfield LIKE '$id'";
  $valueqry = mysqli_query($dbh,$qrytext);
  if (FALSE === $valueqry) die("Select failed: ".mysqli_error);
  $result = mysqli_fetch_row($valueqry);
  $returnvalue = $result[0];
  return $returnvalue;
}

Thanks to everyone for their help. :)

도움이 되었습니까?

해결책

Although it's good idea to automate simple selects, the implementation is highly insecure, and should never be used.

Make it accept SQL query and parameters. It will make it secure.
And also you have to use PDO instead of mysqli

function getdbvalue() {
  global $pdo;
  $args = func_get_args();
  $sql  = array_shift($args);
  $stm  = $pdo->prepare($sql);
  $stm->execute($args);
  return $stm->fetchColumn();
}

have to be used like this (you have to connect to PDO first):

$name = getdbvalue("SELECT name FROM users WHERE id=?", $is);

this is the only proper way

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top