开发者

Using PDO to create a mysql query function, wont insert rows

开发者 https://www.devze.com 2022-12-18 20:50 出处:网络
Trying to get a grasp of using PDO, and I\'m using some pre-made functions to make things simpler for when I want to do a query. First one connects, second runs the query.

Trying to get a grasp of using PDO, and I'm using some pre-made functions to make things simpler for when I want to do a query. First one connects, second runs the query.

Unfortunately it won't let me INSERT rows using dbquery(). SELECT works fine, just can't seem to get anything else to work.

Here's the code:

function dbConnect() 
  {
  global $dbh;

  $dbInfo['database_target'] = "localhost";
  $dbInfo['database_name'] = "mysqltester";
  $dbInfo['username'] = "root";
  $dbInfo['password'] = "password";

  $dbConnString = "mysql:host=" . $dbInfo['database_target'] . "; dbname=" . $dbInfo['database_name'];
  $dbh = new PDO($dbConnString, $dbInfo['username'], $dbInfo['password']);
  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $error = $dbh->errorInfo();

  if($error[0] != "") 
    {
    print "<p>DATABASE CONNECTION ERROR:</p>";
    print_r($error);
    }
  }

function dbQuery($queryString) 
  {
  global $dbh;

  $query = $dbh->query($queryString);
  $i = 0;

  foreach ($query as $query2) 
    {
    $queryReturn[$i] = $query2;
    $i++;
    }

  if($i > 1) 
    {
    return $queryReturn;
    }
    else
    {
    return $queryReturn[0];
开发者_如何学Python    }
  }


PDO::query Only works with queries that return a result set (e.g. SELECT)

For INSERT/UPDATE/DELETE see PDO::exec

If you are going to be inserting user provided data into your DBMS I strongly suggest using the prepared statement functionality of PDO to provide automatic escaping to prevent SQL injection.

e.g.

<?php
$stmt = $dbh->prepare("INSERT INTO tester1 (name, age) VALUES (?, ?)");
$stmt->execute(array('James',25));

See PDO::prepare and PDOStatement::execute

0

精彩评论

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

关注公众号