PDO INSERT INTO无法正常工作

时间:2015-04-02 23:58:44

标签: php mysql pdo

我试图将新记录插入到MySQL Db中,但我使用的预处理语句方法并不正常。我使用了我发现here的查询,看起来应该可以完美运行,但事实并非如此。我没有错误。

这是我的表格:

<form name="registration" action="su-sql.php" method="post">  
    <ul>  

        <fieldset>
            <li><label for="email">Email</label></li>  
            <li><input type="email" name="email" id="email" required="required" aria-required="true" spellcheck="false" onblur="checkEmail(this.value);" onchange="checkEmail(this.value);"/></li>  
            <li><label for="password">Password</label></li>
            <li><input type="password" name="password" id="password" required="required" aria-required="true" spellcheck="false" onblur="checkPassword(this.value);" onchange="checkPassword(this.value);"/></li>  
            <li><label for="passconfirm">Confirm Password</label></li>
            <li><input type="password" name="passconfirm" id="passconfirm" required="required" aria-required="true" spellcheck="false" onblur="checkPassconfirm(this.value);" onchange="checkPassconfirm(this.value);"/></li>
        </fieldset>

        <fieldset>
            <li><label for="firstname">First Name</label></li>
            <li><input type="text" name="firstname" id="firstname" required="required" aria-required="true" onblur="checkFirstname(this.value);" onchange="checkFirstname(this.value);"/></li>
            <li><label for="lastname">Last Name</label></li>
            <li><input type="text" name="lastname" id="lastname" required="required" aria-required="true" onblur="checkLastname(this.value);" onchange="checkLastname(this.value);"/></li>
            <li><label for="country">Country</label></li>
            <li>
                <select name="country" id="country" required="required" aria-required="true" onblur="checkCountry(this.value);" onchange="checkCountry(this.value);">
                    <option selected value="" class="option" id="choose">Choose your Country</option>

                    <?php

                    $countries = array('Afghanistan','Akrotiri','Albania','Algeria','American Samoa','Andorra','Angola','Anguilla','Antarctica','Antigua and Barbuda',
                        'Argentina','Armenia','Aruba','Ashmore and Cartier Islands','Australia','Austria','Azerbaijan','Bahamas, The','Bahrain','Bangladesh','Barbados',
                        'Bassas da India','Belarus','Belgium','Belize','Benin','Bermuda','Bhutan','Bolivia','Bosnia and Herzegovina','Botswana','Bouvet Island','Brazil',
                        'British Indian Ocean Territory','British Virgin Islands','Brunei','Bulgaria','Burkina Faso','Burma','Burundi','Cambodia','Cameroon','Canada',
                        'Cape Verde','Cayman Islands','Central African Republic','Chad','Chile','China','Christmas Island','Clipperton Island','Cocos (Keeling) Islands',
                        'Colombia','Comoros','Congo, Democratic Republic of the','Congo, Republic of the','Cook Islands','Coral Sea Islands','Costa Rica','Cote d\'Ivoire',
                        'Croatia','Cuba','Cyprus','Czech Republic','Denmark','Dhekelia','Djibouti','Dominica','Dominican Republic','Ecuador','Egypt','El Salvador','Equatorial Guinea',
                        'Eritrea','Estonia','Ethiopia','Europa Island','Falkland Islands (Islas Malvinas)','Faroe Islands','Fiji','Finland','France','French Guiana',
                        'French Polynesia','French Southern and Antarctic Lands','Gabon','Gambia, The','Gaza Strip','Georgia','Germany','Ghana','Gibraltar','Glorioso Islands','Greece',
                        'Greenland','Grenada','Guadeloupe','Guam','Guatemala','Guernsey','Guinea','Guinea-Bissau','Guyana','Haiti','Heard Island and McDonald Islands',
                        'Holy See (Vatican City)','Honduras','Hong Kong','Hungary','Iceland','India','Indonesia','Iran','Iraq','Ireland','Isle of Man','Israel','Italy','Jamaica',
                        'Jan Mayen','Japan','Jersey','Jordan','Juan de Nova Island','Kazakhstan','Kenya','Kiribati','Korea, North','Korea, South','Kuwait','Kyrgyzstan',
                        'Laos','Latvia','Lebanon','Lesotho','Liberia','Libya','Liechtenstein','Lithuania','Luxembourg','Macau','Macedonia','Madagascar','Malawi','Malaysia',
                        'Maldives','Mali','Malta','Marshall Islands','Martinique','Mauritania','Mauritius','Mayotte','Mexico','Micronesia, Federated States of','Moldova',
                        'Monaco','Mongolia','Montserrat','Morocco','Mozambique','Namibia','Nauru','Navassa Island','Nepal','Netherlands','Netherlands Antilles','New Caledonia',
                        'New Zealand','Nicaragua','Niger','Nigeria','Niue','Norfolk Island','Northern Mariana Islands','Norway','Oman','Pakistan','Palau','Panama','Papua New Guinea',
                        'Paracel Islands','Paraguay','Peru','Philippines','Pitcairn Islands','Poland','Portugal','Puerto Rico','Qatar','Reunion','Romania','Russia','Rwanda',
                        'Saint Helena','Saint Kitts and Nevi','Saint Lucia','Saint Pierre and Miquelon','Saint Vincent and the Grenadines','Samoa','San Marino','Sao Tome and Principe',
                        'Saudi Arabia','Senegal','Serbia and Montenegro','Seychelles','Sierra Leone','Singapore','Slovakia','Slovenia','Solomon Islands','Somalia','South Africa',
                        'South Georgia and the South Sandwich Islands','Spain','Spratly Islands','Sri Lanka','Sudan','Suriname','Svalbard','Swaziland','Sweden','Switzerland','Syria',
                        'Taiwan','Tajikistan','Tanzania','Thailand','Timor-Leste','Togo','Tokelau','Tonga','Trinidad and Tobago','Tromelin Island','Tunisia','Turkey','Turkmenistan',
                        'Turks and Caicos Islands','Tuvalu','Uganda','Ukraine','United Arab Emirates','United Kingdom','United States','Uruguay','Uzbekistan','Vanuatu','Venezuela',
                        'Vietnam','Virgin Islands','Wake Island','Wallis and Futuna','West Bank','Western Sahara','Yemen','Zambia','Zimbabwe');  

                    foreach ($countries as $country) {
                        echo '<option value="'.$country.'" class="option">'.$country.'</option>';
                    }  

                    ?>

                </select>
                <div class="clear"></div>
            </li>         
            <li><label for="gender">Gender</label></li>
            <li>
                <input checked type="radio" name="gender" value="male" required="required" aria-required="true" onchange="checkGender(this.value);"> Male
                <input type="radio" name="gender" value="female" required="required" aria-required="true" onchange="checkGender(this.value);"> Female
            </li> 
            <li><input type="submit" value="Submit"/></li>      
        </fieldset>

    </ul>  
    <div class="clear"></div>
</form> 

这就是PHP:

error_reporting(E_ALL); 
ini_set('display_errors',1);



$db_host = "localhost";
$db_user = "user";
$db_pass = "pass";
$db_name = "name";


$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name, $db_user, $db_pass);


do {

    /*
        Generate random number between min and max
        min: 1000000000
        max: 2147483647
    */

    $uid = mt_rand(1000000001,2147483646);

    // make sure that uid isn't already being used

    $query = $db->prepare("SELECT * FROM `members` WHERE `uid` = :uid");
    $query->bindValue(":uid", $uid);
    $query->execute();

    $user = $query->fetch(PDO::FETCH_ASSOC);

} while ($user['uid'] === $uid);




$fbid = null;
$email = $_POST['email'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$country = $_POST['country'];
$gender = $_POST['gender'];


echo $firstname.' '.$lastname.': '.$uid;


// Using prepared statements almost eliminates the possibility of SQL Injection.

$query = $db->prepare("INSERT INTO `members`(uid, fbid, email, password, firstname, lastname, country, gender) 
    VALUES(:uid, :fbid, :email, :password, :firstname, :lastname, :country, :gender)");

$query->execute(array(
    "uid" => $uid,
    "fbid" => $fbid,
    "email" => $email,
    "password" => $password,
    "firstname" => $firstname,
    "lastname" => $lastname,
    "country" => $country,
    "gender" => $gender
));


// get the user's DB entry 

$query = $db->prepare("SELECT * FROM `members` WHERE `uid` = :uid");
$query->bindValue(":uid", $uid);
$query->execute();

// Retrieve the results from the database
$user = $query->fetch(PDO::FETCH_ASSOC);

if($user) {
    echo '<br/>'.$user['firstname'].' '.$user['lastname'].': '.$user['uid'];
} else {
    echo '<br/>No User';
}

当页面加载时,它会在第一行显示用户的姓名和新生成的ID号。第二行是&#34; No User&#34;。

请注意,密码不受保护。我刚刚开始这样做。

任何人都可以看到问题所在吗?

1 个答案:

答案 0 :(得分:1)

正如@ Fred-ii建议的那样,我在数据库连接后添加了以下行:

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

当我这样做时,我收到以下错误:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'fbid' cannot be null' in /home/ourfilmclub/public_html/build/su-sql.php:68 Stack trace: #0 /home/ourfilmclub/public_html/build/su-sql.php(68): PDOStatement->execute(Array) #1 {main} thrown in /home/ourfilmclub/public_html/build/su-sql.php on line 68

基本上,fbid列不能是null。我将null替换为'',现在一切都运行得非常好。 Kudos @ Fred-ii -