使用PHP / phpmyadmin将整数插入SQL

时间:2018-08-31 10:50:06

标签: php html mysql forms phpmyadmin

我正在尝试在SQL数据库中存储“ $ phone”,但是如果我在phpmyadmin中将COLUMN类型设置为“ INT”,则不会输入任何数据。我将COULMN类型更改为“ VARCHAR”后,就可以立即推送数据

在form.php中:

<fieldset>
   <input placeholder="Your Phone Number" type="text" name="phone" value="<?= $phone ?>" tabindex="4">
   <span class="error"><?= $phone_error ?></span>
</fieldset>

$ phone在formprocess.php中声明:

$fname_error = $lname_error = $email_error = $phone_error = $job_error = $nameauth_error = $privacy_error = $decline_error = "";
$fname = $lname = $email = $phone = $message = $jobtitle = $nameauth = $success = $privacy = "";

if (empty($_POST["phone"])) {
$phone_error = "Phone is required";
  } else {
 $phone = test_input($_POST["phone"]);
 // check if e-mail address is well-formed
  if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3} 
  [\s-]?\d{4}$/i",$phone)) {
  $phone_error = "Invalid phone number"; 
  }
 }`

if ($privacy == 'agree') {

if ($fname_error == '' and $lname_error == '' and $email_error == '' and $phone_error == '' and $privacy_error == '' and $nameauth_error == '' and $job_error == '') 
    {   
        $sql = "INSERT INTO data (phoneNo) VALUES ('$phone');";
        mysqli_query($con, $sql);
        $success = "Enjoy your game!!";
        $fname = $lname = $email = $phone = $message = $jobtitle = $nameauth = "";
    }   

} else if ($privacy == '') {
    $privacy_error = "Please Accept or Decline Our Policy";
} else if ($privacy == 'disagree') {
    $decline_error = "Please Accept Our Privacy Policy to Continue";
}   

}  

如果phpmyadmin中的列数据类型为varchar,则此代码可完美运行,但如果我使用INT,则该代码会中断

是否与我将变量初始化为=“”使其变为varchar的事实有关?

我是否必须将INT值初始化为= 0; ?

2 个答案:

答案 0 :(得分:0)

大家好,我设法用下面的代码来解决它,现在可以正常工作:   if ($fname_error == '' and $lname_error == '' and $email_error == '' and $phone_error == '' and $privacy_error == '' and $nameauth_error == '' and $job_error == '') { $intphone = (int)$phone; $sql = "INSERT INTO data (phoneNo) VALUES ('$intphone');"; mysqli_query($con, $sql); $success = "Enjoy your game!!"; $fname = $lname = $email = $phone = $message = $jobtitle = $nameauth = ""; 我得到了$ phone的值,并通过以下方式将其转换为int: $intphone = (int)$phone;

假设电话号码为:99999999999 在我的数据库中,我得到:2147483647

我认为这是INT字段可以显示的最高值,并且由于我电话号码中的过滤仅允许11个数字且不小于11个数字,因此我认为这将转换为高于INT可以显示的值。

我在phpmyadmin中选择了我的INT(40),但是这似乎不是实际的字符长度,而是某种形式的位表示形式(我会继续读下去!)

感谢所有,如果在任何方向都有任何指示,您可以建议我阅读!

谢谢!

答案 1 :(得分:0)

必须将其转换为整数才能使用。

$phone = (int) $phone.

此外,电话号码始终为字符串,因为它们可能带有“ +”或以“ 0”开头。