使用MySQLi和PHP未将数据提交到SQL数据库

时间:2015-04-19 20:31:17

标签: php mysql database mysqli

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

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

  

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

但每次我发送数据时,图像和其他数据都将插入到2个SEPERATE行的数据库中。我不知道为什么。我也尝试修改我的代码,以便它使用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代码的片段(基本上是您在解决方案中发布的代码),添加了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'];

2 个答案:

答案 0 :(得分:2)

您可能需要检查变量名称并根据自己的喜好进行调整。使用预准备语句来防止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();
}

答案 1 :(得分:1)

  

但每次我发送数据时,图像和其他数据都将插入到2个SEPERATE行的数据库中。我不明白为什么。

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

合并您的if (!empty($_FILES["uploadedimage"]["name"]))if(isset($_POST['submit'])),然后使用类似的内容,您可以将其同时插入与所有其他值相同的行:

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脚本)。