【问题标题】:Converting from MYSQL to MYSQLI [duplicate]从MYSQL转换为MYSQLI [重复]
【发布时间】:2013-12-06 12:32:00
【问题描述】:

我正在尝试将旧网站转换为使用 mysqli 而不是 mysql。

用这部分代码遇到了一个绊脚石

if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysqli_real_escape_string") ? mysqli_real_escape_string($theValue) : mysqli_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;   
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

我不断收到错误

Warning:  mysqli_real_escape_string() expects exactly 2 parameters, 1 given in 

Warning:  mysqli_real_escape_string() expects exactly 2 parameters, 1 given in

如果我添加这样的连接

$theValue = function_exists("mysqli_real_escape_string") ? mysqli_real_escape_string($test,$theValue) : mysqli_escape_string($test,$theValue);

得到错误

Warning:  mysqli_real_escape_string() expects parameter 1 to be mysqli, null given



Warning:  mysqli_real_escape_string() expects parameter 1 to be mysqli, null given

谁能告诉我我做错了什么

非常感谢

【问题讨论】:

  • 错误信息准确地告诉您出了什么问题。如果您使用 RTM,您可以看到该函数有两个参数。你只提供一个。您丢失了连接。
  • 你必须将mysqli句柄传递给函数php.net/manual/en/mysqli.real-escape-string.php
  • 你不需要测试function_exists("mysqli_real_escape_string")。如果 mysqli 存在,mysqli_real_escape_string 也存在。就叫吧。
  • FFS,请学习使用准备好的语句。

标签: php mysql mysqli


【解决方案1】:

得到。摆脱。的。这。所有的。功能。

它不应该与 mysqli 一起使用。因为 mysqli 有它自己的机制,必须使用它。

但是,这些机制很不方便,所以,最好转向PDO prepared statements.

【讨论】:

  • 这是正确的答案,开始使用 PDO 并使用准备好的语句。这将提高代码的可读性和安全性。
  • 但是mysqli比PDO快
  • @Darline 哦,拜托。这种想象中的差异是否会以任何特定方式影响
【解决方案2】:

mysqli_real_escape_string 也需要通过数据库连接。因此,您需要将其提供给函数,然后执行:

mysqli_escape_string($connection, $theValue);

http://php.net/manual/en/mysqli.real-escape-string.php

此外,它告诉您您的$test 变量是null - 同样,它期待您使用myqli_connect() 创建的实时数据库连接。您可能需要将其作为参数传递给函数。

【讨论】:

  • 您不应使用或链接到w3schools。它不是可靠的信息来源,我们不想鼓励使用它。更不用说 php.net 是 PHP 函数的权威来源。
  • 请阅读整个问题。
猜你喜欢
  • 2012-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-29
  • 1970-01-01
  • 2014-07-02
  • 1970-01-01
相关资源
最近更新 更多