douchangmian0305 2014-02-25 16:16
浏览 49
已采纳

输入文本值时,数据库无法创建记录($ _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:

<?php


//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)");

    mysqli_close($con);



    }


?>

The HTML code is:

<form method="post">

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

</form>

Cheers

  • 写回答

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置