-1

I've been advised to use anti-sql injection methods, as I am inserting values inside my database. I've looked around the web, and my first failed attempt is this, of which I need some help, with the PDO method. I found examples online to be waaay too empty of substance for me to understand (btw, I ran a line and it told me PDO is enabled):

Is this good in any way, shape or form?

<?php
include ('config.php');
// Host, User, Pass, DB
$con=mysqli_connect("127.0.0.1","*****","*****","*****");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQLi: " . mysqli_connect_error();
  }

$host = 'localhost';
$dbname = '****';
$user = '****';
$pass = '*****';

try {
  # MS SQL Server and Sybase with PDO_DBLIB
  $DBH = new PDO("mssql:host=$host;dbname=$dbname, $user, $pass");
  $DBH = new PDO("sybase:host=$host;dbname=$dbname, $user, $pass");

  # MySQL with PDO_MYSQL
  $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

  # SQLite Database
  $DBH = new PDO("sqlite:my/database/path/database.db");
}
catch(PDOException $e) {
    echo $e->getMessage();
}  

Also, I get this error upon submitting my form:

Fatal error: Call to a member function prepare() on a non-object in /home/product/*****/*****/*****/processForm-test.php on line 68
4

1 回答 1

2

您的代码中的一个大问题是它同时使用mysqli_connectPDO创建数据库连接。不要那样做;不支持。使用其中一种。

建立 PDO 连接的行尝试连接到四个单独的数据库,SQL Server、Sybase、MySQL 和 SQLLite,它们都在 localhost 上运行。但是您只保留最后一个句柄,因为您将数据库连接分配给同一个变量。

如果连接成功,该变量$DBH是您对数据库会话(连接)的引用。如果它不成功,它会被分配一个值false,您可以在继续之前对其进行测试。

我认为您只需要一个与 MySQL 的 PDO 连接,如下所示:

<?php
include ('config.php');

$host = 'localhost';
$dbname = '****';
$user = '****';
$pass = '*****';
try {
  # MySQL with PDO_MYSQL
  $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e) {
  echo "Connect failed: " . $e->getMessage();
}

我在这里推断,但您收到的错误消息最可能的解释是您有一行代码(未在代码示例中显示),如下所示:

$sth = $DBH->prepare($sql);

问题是这$DBH不是对有效数据库连接的引用。$DBH值为“false”,这是因为尝试连接到数据库失败。Andfalse不是一个对象,所以它不可能有一个名为“prepare”的方法与之关联。

于 2013-07-29T19:24:14.813 回答