将图像添加到数据库html表单

时间:2016-07-22 00:20:54

标签: php mysql

我正在尝试将记录添加到数据库中。每条记录都有相应的图像。记录将被插入到数据库中,但它不适用于图像。我收到此错误"连接成功注意:未定义的变量:第35行的C:\ xampp \ htdocs \ Syokimaufc \ addplayer.php中的sql错误:查询为空"我该如何解决这个问题?

<form action="addplayer.php"method ="post" enctype="multipart/form-    data">

     <p> id: <input type="text" name="playerid"/></p>
     <p> Name: <input type="text" name="name"/></p>
     <p> Age: <input type="text" name="age"/></p>
     <p> Position: <input type="text" name="position"/></p>
     <p> Nationality: <input type="text" name="nationality"/></p>
     <p> Photo: <input type="file" name="image"/></p>
 <input type="submit"  value="submit"/>

 <form/>



 <?php
require 'connection.php';


$id = filter_input(INPUT_POST, 'playerid');
$name = filter_input(INPUT_POST, 'name');
$age = filter_input(INPUT_POST, 'age');
$position = filter_input(INPUT_POST, 'position');
$nationality = filter_input(INPUT_POST, 'nationality');

$_id = mysql_real_escape_string( $id );
$_name = mysql_real_escape_string( $name );
$_age = mysql_real_escape_string( $age );
$_position = mysql_real_escape_string( $position );
$_nationality = mysql_real_escape_string( $nationality );

if (isset($_POST['submit']))
{
    $imageName = mysql_real_escape_string($_FILES ["image"]["name"]);
    $imageData = mysql_real_escape(file_get_contents($_FILES["image"]["tmp_name"]));
    $imageType = mysql_real_escape_string($_FILES["image"]["name"]);

    if (substr($imageType,0,5) == "image")
    {
        $sql = "INSERT INTO players ( playerid, name, age, position, nationality, iname, image ) VALUES ( '$_id', '$_name', '$_age', '$_position', '$_nationality', '$imageName', '$imageData' )";
    }
    else
    {
        echo "only images are allowed";
    }
}


if (!mysql_query($sql)){
    die('Error: ' . mysql_error());
}

1 个答案:

答案 0 :(得分:0)

把:

if (!mysql_query($sql)){
    die('Error: ' . mysql_error());
}

之后
$sql = "INSERT IN..."

问题在于,因为您在所有if项检查之外运行查询,即使没有输入数据(例如:没有提交表单),$sql也会运行查询在这种情况下将不存在。因此“未定义变量:sql ”和“查询为空”错误