开发者

Pass a PHP variable to a MySQL query

What is wrong with this code? I get an empty array. I am passing a PHP variable to the query, but it doesn’t work; when I give a hardcoded value the query returns a result.

echo $sub1 = $examSubject[$i];
$subType = $e开发者_运维知识库xamType[$i];
$query = $this->db->query("select dSubject_id from tbl_subject_details where dSubjectCode='$sub1'");
print_r($query->result_array());


Look up “SQL injection”.

I’m not familiar with $this->db->query; what database driver are you using? The syntax for escaping variables varies from driver to driver.

Here is a PDO example:

$preqry = "INSERT INTO mytable (id,name) VALUES (23,?)";
$stmt = $pdo->prepare($preqry);

$stmt->bindparam(1,$name);
$stmt->execute();


failing to see what you database abstraction layer ($this->db) does, here's the adjusted code from example1 from the mysql_fetch_assoc documentation

<?php
  // replace as you see fit
  $sub1 = 'CS1';

  // replace localhost, mysql_user & mysql_password with the proper details
  $conn = mysql_connect("localhost", "mysql_user", "mysql_password");
  if (!$conn) {
    echo "Unable to connect to DB: " . mysql_error();
    exit;
  }

  if (!mysql_select_db("mydbname")) {
    echo "Unable to select mydbname: " . mysql_error();
    exit;
  }

  $sql = 'SELECT `dSubject_id` ';
  $sql .= 'FROM `tbl_subject_details` ';
  $sql .= "WHERE `dSubjectCode` ='$sub1';";

  $result = mysql_query($sql);

  if (!$result) {
    echo "Could not successfully run query ($sql) from DB: " . mysql_error();
    exit;
  }

  if (mysql_num_rows($result) == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
  }

  while ($row = mysql_fetch_assoc($result)) {
    echo $row['dSubject_id'];
  }

  mysql_free_result($result);

?>

Let me know what the output is, I'm guessing it will say: 6


Is it CodeIgniter framework you're using (from the $this->db->query statement). If so, why don't you try:

$this->db->where('dSubjectCode',$sub1);
$query = $this->db->get('tbl_subject_details');

If this doesn't work, you've got an error earlier in the code and $sub1 isn't what you expect it to be.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜