【问题标题】:Data not being submited to SQL Database using MySQLi and PHP未使用 MySQLi 和 PHP 将数据提交到 SQL 数据库
【发布时间】:2015-04-19 20:31:16
【问题描述】:

这是我的原帖:Why is data I upload getting renamed, and corresponding data added to different rows?

我能够稍微编辑代码(使用我提供的解决方案),以便通过插入表单提交到服务器的图像与我上传的文件具有相同的名称。

示例:我将turtle.jpg 上传到表单中,然后单击“插入”。文件 “turtle.jpg”将被写入它所在的数据库中 在服务器上(图像/turtle.jpg)。然后一个成功的消息会 弹出来。

但是每次我发送数据时,图像和其他数据都会插入到数据库中的 2 个单独的行中。我不知道为什么。我还尝试修改我的代码,使其使用 mysqli 而不是 mysql 并且不再有效。没有错误,但没有数据发送到数据库中。

这是我的新 php 代码:

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Create connection
$conn = new mysqli('$host', '$user', '$pass', '$databasename');

// Check connection
if (mysqli_connect_error()) {
    die("Database connection failed: " . mysqli_connect_error());
}

if (!empty($_FILES["uploadedimage"]["name"])) {

	$file_name=$_FILES["uploadedimage"]["name"];
	$temp_name=$_FILES["uploadedimage"]["tmp_name"];
	$imgtype=$_FILES["uploadedimage"]["type"];
	$ext= GetImageExtension($imgtype);
	$imagename= $_FILES['uploadedimage']['name'];
        $target_path = "images/".$imagename;
        
        $result = $mysqli->query("INSERT INTO charts ( charts_URL ) VALUES ('".$target_path."')");
        or die(mysqli_error($mysqli));
        
} else {

        echo "<p> It is not working </p>";

    }


if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$date = $_POST['date'];
$retrace = $_POST['retrace'];
$start_of_swing_trade = $_POST['start_of_swing_trade'];
$end_of_swing_trade = $_POST['end_of_swing_trade'];
$bull_flag = $_POST['bull_flag'];
$bear_flag = $_POST['bear_flag'];
$ema_crossover = $_POST['ema_crossover'];
$trading_instrument = $_POST['trading_instrument'];
if($date !=''||$trading_instrument !=''){
//Insert Query of SQL
$sql = "INSERT into charts (charts_date, charts_retrace, charts_start_of_swing_trade, charts_end_of_swing_trade, charts_bullflag, charts_bearflag, charts_ema_crossover, charts_trading_instrument) VALUES ('$date', '$retrace', '$start_of_swing_trade', '$end_of_swing_trade', '$bull_flag', '$bear_flag', '$ema_crossover', '$trading_instrument')";

if (mysqli_query($conn, $sql)) {

    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn); // Closing Connection with Server

只有在我使用旧的 mysql_query 代码时才会将数据插入数据库。但是我的数据库说它支持 mysqli 扩展。

Database server
Server: Localhost via UNIX socket
Server type: MySQL
Server version: 5.5.35-cll-lve - MySQL Community Server (GPL)
Protocol version: 10
User: cpses_msLpFymSYl@localhost
Server charset: UTF-8 Unicode (utf8)

Web Server
cpsrvd 11.48.1.2
Database client version: libmysql - 5.1.73
PHP extension: mysqli Documentation

phpmyadmin
Version information: 4.0.10.7, latest stable version: 4.4.2

这是我当前的 PHP 代码(基本上是您在解决方案中发布的代码)的 sn-p,添加了 GetImageExtension 函数:

if(isset($_POST['submit'])){

    $conn = new mysqli($host, $user, $pass, $databasename);
    // Check connection can be established
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
        function GetImageExtension($imagetype)
    {
       if(empty($imagetype)) return false;
       switch($imagetype)
       {
           case 'image/bmp': return '.bmp';
           case 'image/gif': return '.gif';
           case 'image/jpeg': return '.jpg';
           case 'image/png': return '.png';
           default: return false;
       }
     }

    $target_path = '';
    if (!empty($_FILES["uploadedimage"]["name"])) {
        $file_name=$_FILES["uploadedimage"]["name"];
        $temp_name=$_FILES["uploadedimage"]["tmp_name"];
        $imgtype=$_FILES["uploadedimage"]["type"];
        $ext= GetImageExtension($imgtype);
        $imagename= $_FILES['uploadedimage']['name'];
        $target_path = "images/".$imagename;

    $date = $_POST['date'];
    $retrace = $_POST['retrace'];
    $start_of_swing_trade = $_POST['start_of_swing_trade'];
    $end_of_swing_trade = $_POST['end_of_swing_trade'];
    $bull_flag = $_POST['bull_flag'];
    $bear_flag = $_POST['bear_flag'];
    $ema_crossover = $_POST['ema_crossover'];
    $trading_instrument = $_POST['trading_instrument'];

【问题讨论】:

  • 您在那里进行了两个单独的查询。它要么结合所有两个查询,要么获取第一个查询的insert_id 并使用update 进行第二个查询。
  • 您有两个INSERT 语句。为什么要插入两行令人惊讶?
  • mysqli_connect() 参数中删除单引号。
  • 您已将 mysqli_connect 更改为 new mysqli。当然是行不通的。过程式和面向对象的风格有不同的实现方式。
  • 当您使用new mysqli 时,您正在创建一个对象。但是在代码的更下方,您使用程序mysqli_connect_error()mysqli_query...等。此外,您使用了未初始化的变量$mysqli。您想使用哪种方式并不重要,但使用准备好的语句。

标签: php mysql database mysqli


【解决方案1】:

您可能需要检查变量名称并根据自己的喜好进行调整。使用prepared statement来防止sql注入。

if(isset($_POST['submit'])){

    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection can be established
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $target_path = '';
    if (!empty($_FILES["uploadedimage"]["name"])) {
        $file_name=$_FILES["uploadedimage"]["name"];
        $temp_name=$_FILES["uploadedimage"]["tmp_name"];
        $imgtype=$_FILES["uploadedimage"]["type"];
        $ext= GetImageExtension($imgtype);
        $imagename= $_FILES['uploadedimage']['name'];
        $target_path = "images/".$imagename;
    }

    $date = $_POST['date'];
    $retrace = $_POST['retrace'];
    $start_of_swing_trade = $_POST['start_of_swing_trade'];
    $end_of_swing_trade = $_POST['end_of_swing_trade'];
    $bull_flag = $_POST['bull_flag'];
    $bear_flag = $_POST['bear_flag'];
    $ema_crossover = $_POST['ema_crossover'];
    $trading_instrument = $_POST['trading_instrument'];

    if($date !=''||$trading_instrument !=''){

        $sql = "INSERT into charts (charts_URL, charts_date, charts_retrace, charts_start_of_swing_trade, charts_end_of_swing_trade, charts_bullflag, charts_bearflag, charts_ema_crossover, charts_trading_instrument) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        // s = string, i = integer, d = double, b = blob
        //preparing statement
        $stmt = $conn->prepare($sql);
        if(!$stmt){ exit("prepare failed");}
        //binding param
        $bind = $stmt->bind_param('sssssssss',$target_path, $date, $retrace, $start_of_swing_trade, $end_of_swing_trade, $bull_flag, $bear_flag, $ema_crossover, $trading_instrument);
        if(!$bind){ exit("bind failed");}
        //will return 0 if fail
        if($stmt->execute() != 0){

            echo "New record created successfully";
        }else{ echo "Failed to insert new record";}

    }
//close connection
$conn->close();
}

【讨论】:

  • 我收到以下错误;致命错误:调用未定义函数 GetImageExtension()
  • 好的,所以我用上一篇文章中的原始function GetImageExtension($imagetype) 代码修复了错误。但现在没有数据发送到数据库,也没有显示失败/成功消息。
  • 修改后的答案。添加了一些代码以查看失败的位置。
  • 还是什么都没有。没有错误或任何消息显示。单击插入后只是一个空白屏幕。顺便说一句,我编辑了我的问题,使用新的 GetImageExtension 函数添加了我拥有的 PHP 代码的 sn-p。
  • 错误日志显示:[20-Apr-2015 07:59:57 UTC] PHP 解析错误:语法错误,/home/mscott62/public_html/chart-submission/insert_backend 中的文件意外结束。 php on line 72 我的文件末尾显示://close connection $conn-&gt;close(); } ?&gt; line 72 is the last line in the file.
【解决方案2】:

但是每次我发送数据时,图像和其他数据都会插入到数据库中的 2 个单独的行中。我不知道为什么。

您为什么希望它落在同一行?您执行两个不同的插入查询。如果您确实想使用两个查询,则第二个查询必须是对先前插入的行的更新。但显然,这不是首选方式,只需使用一个查询即可。

if (!empty($_FILES["uploadedimage"]["name"]))if(isset($_POST['submit'])) 组合起来,然后使用类似这样的方法,将URL 同时插入到与所有其他值相同的行中:

INSERT into charts (charts_URL, charts_date, charts_retrace, charts_start_of_swing_trade, charts_end_of_swing_trade, charts_bullflag, charts_bearflag, charts_ema_crossover, charts_trading_instrument) VALUES (?,?,?,?,?,?,?,?)

安全

请注意,您的代码非常不安全$imagename 是用户控制的,因此您的第一个查询对 SQL 注入开放。第二个查询中的值显然是用户控制的,这也很容易受到攻击。 SQL 注入可以发生在各种查询中,包括插入。它可能会泄漏数据、对您进行 DOS 操作,并可能执行代码或更改数据。 使用准备好的语句来防止 SQL 注入。它使用简单,代码很好,没有理由不使用它。

另请注意,$_FILES["uploadedimage"]["type"] 也是用户控制的,并且与实际文件类型或扩展名无关。 在决定在服务器上扩展图像时,您不应该信任它(如果这样做,攻击者可能会上传 PHP 脚本)。

【讨论】:

  • 是的,感谢您的提示,但我不知道如何在 mysqli 中执行准备好的语句。我试图弄清楚如何解决我遇到的这个问题。我可以自己编写代码,但这需要我多次尝试,并且通常会以我寻求帮助而告终。
  • mysqli prepared statements。这真的很简单,安全性非常重要。至于您的问题:我认为我的帖子包含您解决它所需的所有内容,您应该能够通过一些尝试来做到这一点(您这样做更容易,因为我们必须设置数据库等进行测试它;当你自己做的时候,你肯定会学到更多)。就像我说的,只需将你的两个 if 块和你的两个插入合二为一,就是这样。一旦它工作,迁移到准备好的语句。
  • 当然我可以做到,如果我自己做,我可以更快地学习并更好地保留更多信息,但是当我有另一个大脑在我偶然发现怪异时给我提示时,它也可以帮助我走得更快代码,我和 frz 已经把这两个插入合二为一了。现在试图找出导致错误的原因。
猜你喜欢
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
  • 2019-06-18
  • 1970-01-01
  • 1970-01-01
  • 2010-12-04
  • 2018-01-12
相关资源
最近更新 更多