准备插入查询

时间:2013-11-23 01:50:44

标签: php mysql

这是我的代码:

    <form>
    <fieldset>
        <label>Site ID:
        <input type="text" name="site"/>
        </label>
        <label>Location:
        <input type="text" name="location"/>
        </label>
        <input type="submit" name="Submit"/>
    </fieldset>
</form>

<?php
    $stmt = $db->prepare("INSERT INTO site(site_id, location) values (?,?)");

    $stmt->bindParam(1, $site_id);
    $stmt->bindParam(2, $location);


    $site_id = $_POST["site"];
    $location = $_POST["location"];

    $stmt->execute();



?>

我收到一个空错误

我知道当我进入页面时表单正在尝试提交数据,那么我需要做些什么才能对其进行排序?

2 个答案:

答案 0 :(得分:0)

这些方面是相反的:

<?php
    $stmt = $db->prepare("INSERT INTO site(site_id, location) values (?,?)");

    $site_id = $_POST["site"];
    $location = $_POST["location"];

    $stmt->bindParam(1, $site_id);
    $stmt->bindParam(2, $location);

    $stmt->execute();
?>

如果您仍然遇到null错误,请尝试像这样进行调试:

<?php
    $stmt = $db->prepare("INSERT INTO site(site_id, location) values (?,?)");

    $site_id = $_POST["site"];
    $location = $_POST["location"];

    // if $site_id is null (or maybe empty) your PDO will error  
    print "\$site_id is $site_id  <br/>"; 
    print "\$location is $location "; 

    $stmt->bindParam(1, $site_id);
    $stmt->bindParam(2, $location);

    $stmt->execute();
?>

进行调试,你可以检查你的帖子变量:

print "<pre>" . print_r($_POST, true) . "</pre>"; 

我包含<pre>所以它看起来更好。这将转储整个$_POST数组。如果你没有得到任何东西,这意味着你的表单或ajax或其他任何东西都不会向页面提交任何内容。


这对我有用:

<?php

if (!empty($_POST))
{
     $user = 'root'; 
     $pass = ''; 

    $db = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

    $stmt = $db->prepare("INSERT INTO site (site_id, location) values (?,?)");

    $site_id  = $_POST["site"];
    $location = $_POST["location"];

    $stmt->bindParam(1, $site_id);
    $stmt->bindParam(2, $location);  

    $success = $stmt->execute();  

     if ($success) { print "insert successful"; }
              else { print "not successful"; } 
}
?>

<form action="" method="post">
    <fieldset>
        <label>Site ID:
        <input type="text" name="site"/>
        </label>
        <label>Location:
        <input type="text" name="location"/>
        </label>
        <input type="submit" name="submit"/>
    </fieldset>
</form>

答案 1 :(得分:0)

您需要的代码

<form method=POST>
<fieldset>
    <label>Site ID:
    <input type="text" name="site"/>
    </label>
    <label>Location:
    <input type="text" name="location"/>
    </label>
    <input type="submit" name="Submit"/>
</fieldset>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $stmt = $db->prepare("INSERT INTO site(site_id, location) values (?,?)");
    $stmt->execute([$_POST["site"],$_POST["location"]]);
}