简体   繁体   English

用PHP插入MySQL数据库时的空白数据

[英]blank data when inserting into MySQL database with PHP

I made a form to insert and modify categories in my project. 我制作了一个表格来插入和修改项目中的类别。 when i hit "submit" i get the record submitted into the database but it appears empty ! 当我点击“提交”时,我将记录提交到数据库中,但它显示为空! and if i go to the databse field and write the text myself it will appear good in MySQL and and "????" 如果我进入databse字段并自己编写文本,它将在MySQL和“ ????”中显示良好 in the browser ! 在浏览器中!

here is the code i wrote: 这是我写的代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>

 <?php
$con = mysql_connect("localhost","user","pass");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("mydb", $con);

$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('$_POST[name]','$_POST[parent_id]','$_POST[description]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con)
?>

<form action="ins.php" method="post">
category: <input type="text" name="name" /><br><br>
parent: <input type="text" name="parent_id" /><br><br>
description: <input type="text" name="description" /><br><br>

<input type="submit" />
</form>

</body>
</html>

You have to quote (using ") around your index name in your SQL request because $_POST is an array: 因为$ _POST是一个数组,所以必须在SQL请求中的索引名附近用引号引起来(使用“”)。

$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('".$_POST["name"]."','".$_POST["parent_id"]."','".$_POST["description"]."')";

But generally speaking please dont trust directly what's user are posting to your script to avoid SQL Injections. 但是通常来说,请不要直接信任用户将什么内容发布到脚本中,以避免SQL注入。 You can use mysqli::query which is way better and safer : 您可以使用mysqli :: query更好,更安全的方式:

Mysqli Mysqli

First sanitize your user input. 首先清理您的用户输入。

If you after that want to use the values from the array without all the concatenation everyone else mentions use {} around array accessors. 如果此后您想在没有所有串联的情况下使用数组中的值,则其他所有人都提到在数组访问器周围使用{}。

$sql="INSERT INTO categories (name, parent_id, description)
VALUES
('{$_POST['name']}','{$_POST['parent_id']}','{$_POST['description']}')";

To clean for example $_POST do something like this is a good start. 例如,清理$ _POST就是一个好的开始。 This is a bit of my older code. 这是我较早的代码。 As others have written use mysqli instead 正如其他人写的那样,使用mysqli代替

function clean_array($t_array)
{
    foreach($t_array as $key=>$value)
        $array[$key] = mysql_real_escape_string( trim($value) );

    return $t_array;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>

 <?php
 if ($_POST['action']=="doformpost") {
    //only do DB insert if form is actually posted

    $con = mysql_connect("localhost","user","pass");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }

    mysql_select_db("mydb", $con);

    $sql="INSERT INTO categories (name, parent_id,description)
    VALUES
    ('".$_POST['name']."','".$_POST['parent_id']."','".$_POST['description']."')";


    if (!mysql_query($sql,$con))
      {
      die('Error: ' . mysql_error());
      }
    echo "1 record added";

    mysql_close($con)
}
?>

<form action="ins.php" method="post">
<input type="hidden" name="action" id="action" value="doformpost" />
category: <input type="text" name="name" /><br><br>
parent: <input type="text" name="parent_id" /><br><br>
description: <input type="text" name="description" /><br><br>

<input type="submit" />
</form>

</body>
</html>
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
("'.$_POST['name'].'","'.$_POST['parent_id'].'","'.$_POST['description'].'")";

Please provide quotes while inserting values in database 在数据库中插入值时,请提供引号

Try using double quotes in your statement like this: 尝试在语句中使用双引号,如下所示:

$sql="INSERT INTO categories (name, parent_id,description) VALUES ("'.$_POST['name'].'","'.$_POST['parent_id'].'","'.$_POST['description'].'")"; $ sql =“ INSERT INTO类别(名称,parent_id,说明)VALUES(”'。$ _ POST ['name']。'“,”'。$ _ POST ['parent_id']。'“,”。$ _ POST [ '描述']。'”)”;

lots of issues here. 这里有很多问题。

  • $_POST[name] should be $_POST['name'] $_POST[name]应为$_POST['name']
  • your query will run even if the form is not submitted. 即使未提交表单,您的查询也将运行。
  • you are using deprecated mysql_* functions. 您正在使用不mysql_*使用的mysql_*函数。 Use PDO or mysqli 使用PDOmysqli
  • Your code is vulnerable to sql injection 您的代码容易受到sql注入的攻击

With all that out, here's what you need to do. 有了这些,这就是您需要做的。

Just to verify that the form is submitted, use 只是为了验证表单已提交,请使用

if( !empty($_POST['name']) && 
!empty($_POST['parent_id']) && 
!empty($_POST['description']) )

(use isset if empty value is allowed.) (如果允许为空值,请使用isset 。)

Then run the query. 然后运行查询。


In PDO, the code will look like this -> 在PDO中,代码将如下所示->

<?php
// configuration
$dbtype     = "mysql";
$dbhost             = "localhost";
$dbname     = "mydb";
$dbuser     = "user";
$dbpass     = "pass";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// query
$sql = "INSERT INTO categories (name, parent_id,description)
        VALUES
       (?,?,?)";
$q = $conn->prepare($sql);
$q->execute(array($_POST[name],$_POST[parent_id],$_POST[description]));


?>

This is just a start. 这只是一个开始。 you can use try and catch block to catch exceptions. 您可以使用try and catch块来捕获异常。

Before running query, check if form is submitted by !empty() or isset() as described above. 在运行查询之前,请检查表单是由如上所述的!empty()还是isset()提交的。

use this statement for your code 使用此语句作为您的代码

if( isset($_POST['name']) && isset($_POST['parent_id']) && isset($_POST['description']) )

//your insert query

Don't forgot about safety! 不要忘记安全!

$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('".mysql_real_escape_string($_POST['name'])."','".intval($_POST['parent_id'])."','".mysql_real_escape_string($_POST['description'])."')";

And i think a problem with encodings. 而且我认为编码存在问题。

launch query before you inserting a data: 在插入数据之前启动查询:

$sql = 'set names `utf-8`'; (for example)

Use Below insert query to insert data , im sure it will definitely help you. 使用下面的插入查询来插入数据,确定它一定会对您有所帮助。

$sql="INSERT INTO categories (name,parent_id,description)
VALUES
('".$_POST['name']."','".$_POST['parent_id']."','".$_POST['description']."')";

Try this 尝试这个

<?php
if(isset($_POST['submit'])) {
    $con = mysql_connect("localhost","user","pass");
    if (!$con){
      die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("mydb", $con);

    $sql="INSERT INTO categories (name, parent_id,description) VALUES
    ('".$_POST['name']."','".$_POST['parent_id']."','".$_POST['description']."')";

    if (!mysql_query($sql,$con)) {
      die('Error: ' . mysql_error());
    } else {
        echo "1 record added";
    }
    mysql_close($con);
}
?>
<html>
<body>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
category: <input type="text" name="name" /><br><br>
parent: <input type="text" name="parent_id" /><br><br>
description: <input type="text" name="description" /><br><br>
<input type="submit"name="submit" value="Submit" />
</form>
</body>
</html>

Me too faced the same problem. 我也面临同样的问题。

Proceed your insert query like this, this helped me. 像这样继续插入查询,这对我有所帮助。

$email_id = $_POST['email_id'];
$device_id = $_POST['device_id'];
***For My Sqli***
if(!empty($email_id ))
    {
        $result_insert = mysqli_query($db_conn,"INSERT INTO tableName (user_email, user_device_id,last_updated_by) VALUES('".$email_id."', '".$device_id."', '".$email_id."') ");

        if(mysqli_affected_rows($db_conn)>0)
        {
            $response["success"] = 1;
            $response["message"] = "Successfully Inserted";
        }
        else
        {
            $response["success"] = 0;
            $response["message"] = "Problem in Inserting";
        }
    }
    else
    {

        $response["success"] = 4;
        $response["message"] = "Email id cannot be Blank";
    }
}
///////////////////////////////////////////////////////////////////////////////
 **For My Sql**
if(!empty($email_id ))
    {
        $result_insert = mysql_query("INSERT INTO tableName (user_email, user_device_id,last_updated_by) VALUES('".$email_id."', '".$device_id."', '".$email_id."') ");

        if(mysql_affected_rows()>0)
        {
            $response["success"] = 1;
            $response["message"] = "Successfully Inserted";
        }
        else
        {
            $response["success"] = 0;
            $response["message"] = "Problem in Inserting";
        }
    }
    else
    {

        $response["success"] = 4;
        $response["message"] = "Email id cannot be Blank";
    }
}

NOTE : here i have checked only for email. 注意:这里我仅检查电子邮件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM