简体   繁体   中英

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

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

PDO::query Only works with queries that return a result set (eg 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.

eg

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

See PDO::prepare and PDOStatement::execute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM