MySQL到MySQLi转换php表单

时间:2017-11-26 21:59:20

标签: php mysql mysqli

我遇到了一个问题,我的表单通过过时的MySQL与DB连接。我试图根据在线资源和我自己的知识将其转换为MySQLi,但它似乎没有做到这一点。我已经检查了stackoverflow(How to solve Mysql to mysql as I have some problems),这确实涵盖了某些点的转换,但由于我有一些额外的功能,我不知道该怎么做。另外,使用MySQLi时仍然需要条带功能吗?非常感谢您的帮助和时间,脚本如下:

    <?php

    if($_POST['formSubmit'] == "Submit") 
    {
        $errorMessage = false;

        if(empty($_POST['formName'])) 
        {
            $errorMessage = true;
        }
        if(empty($_POST['formEmail'])) 
        {
$errorMessage = true;       }
        if(empty($_POST['formAddress'])) 
        {
$errorMessage = true;       }
    if(empty($_POST['formPrice'])) 
        {
$errorMessage = true;    }


    $varName = $_POST['formName'];
        $varEmail = $_POST['formEmail'];
        $varAddress = $_POST['formAddress'];
    $varPrice = $_POST['formPrice'];
        $varComments = $_POST['formComments'];

         if($errorMessage == false) 
        {

         $db = mysql_connect("","","");
      if(!$db) die("Error connecting to MySQL database.");
      mysql_select_db("" ,$db);

            $sql = "INSERT INTO formdata (name, email, address, price, comments) VALUES (".
                            PrepSQL($varName) . ", " .
                            PrepSQL($varEmail) . ", " .
                            PrepSQL($varAddress) . ", " .
              PrepSQL($varPrice) . ", " .
                            PrepSQL($varComments) . ")";
            mysql_query($sql);

            header("Location: thankyou.php");
            exit();
        }
    }

   //sql injection protection..
    function PrepSQL($value)
    {

        if(get_magic_quotes_gpc()) 
        {
            $value = stripslashes($value);
        }


        $value = "'" . mysql_real_escape_string($value) . "'";

        return($value);
    }


?>

我有连接部分工作,但它没有写入DB,所以我认为查询部分出错了。

1 个答案:

答案 0 :(得分:-1)

只是基本的变化:

$link = mysqli_connect('localhost','root','pass','myDB');
if (!$link) {
 die('Could not connect: ' . mysqli_connect_error());
}

$sql= "INSERT INTO keypairs (name, email, address, price, comments) VALUES ('$varName','$varEmail','$varAddress','$varPrice','$varComments')";
if (!mysqli_query($link,$sql)) {
  //error ...
}