2014-02-25 16:16
浏览 48

输入文本值时,数据库无法创建记录($ _POST)

Perhaps I'm making some obvious beginner mistake, but I just cannot seem to figure out why this happens.

Strangely enough, the code only seems to work properly if I enter a number into the "inputbox". I check this in the myphpadmin panel, and it shows a new record has been created. However, if I attempt to input a string as intended for my purposes (example: "hello") no new record appears in the database...

In short, the database only updates if I put a number into the "inputbox" but not when I enter a string.

Any ideas why this may be happening? It's driving me crazy. If it helps, the data type of the "Company" field is VARCHAR and the collation is set to latin1_swedish_ci

The PHP code is as follows:


//Retrieve data from 'inputbox' textbox

if (isset($_POST['submitbutton']))
    $comprating = $_POST['inputbox'];

    //Create connection

        $con = mysqli_connect("localhost","root","","test_db");

            if (mysqli_connect_errno())
                    echo "Failed to connect to MySQL: " . mysqli_connect_error();

    //Insert data into 'Ratings' table

    mysqli_query($con,"INSERT INTO Ratings (Company,Score)
    VALUES ($comprating,1)");




The HTML code is:

<form method="post">

    <input type="text" name="inputbox">
    <input type="submit" name="submitbutton">



  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongyin2390 2014-02-25 16:18

    Try this query,

    mysqli_query($con,"INSERT INTO Ratings (Company,Score)
    VALUES ('$comprating',1)");`
            ^           ^

    Note the single quotes that reserves the string value and don't forget to sanitize the input before inserting them to database.

    Sample standard escaping:

    $comprating = mysqli_real_escape_string($comprating) before executing a query that uses $comprating

    点赞 评论
  • dsff788655567 2014-02-25 16:49

    Hi here is the objected oriented method and also its secure because data binding is used in mysqli. I recommend to use this.

    if (isset($_POST['submitbutton'])) {
    $comprating = $_POST['inputbox'];
    $mysqli = new mysqli("localhost", "root", "", "test_db");
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s
    ", mysqli_connect_error());
    $stmt = $mysqli->prepare("INSERT INTO Ratings (Company,Score) VALUES (?, ?)");
    $stmt->bind_param($comprating, 1);
    /* execute prepared statement */
    printf("%d Row inserted.
    ", $stmt->affected_rows);
    /* close statement and connection */

    feel free to ask any questions if you have..

    点赞 评论

相关推荐 更多相似问题