使用 PDO (PHP) 在 mySQL 数据库中插入数字数据

我正在尝试使用 PHP 数据对象(PDO)在 MySQL 数据库中插入字符串(:make 和:model)和数字(:year 和:mileage)数据。问题是代码没有在数据库中插入数字数据(我猜原因是代码自动将 :year 和 :mileage 数据类型从 int 更改为 str。“year”和DB 表中的“里程”列是 INT 类型。)如何更改代码以插入 :year 和 :mileage 作为 INT 数据?


//PDO

<?php

$pdo = new PDO('mysql:host=localhost;port=8888;dbname=xxxx', 

   'xxx', 'xxx');

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


 //SQL 

 $sql = "INSERT INTO autos (make, model, year, mileage)

                  VALUES (:make, :model, :year, :mileage)";

        $stmt = $pdo->prepare($sql);

        $stmt->execute(array(

            ':make' => $_POST['make'],

            ':model' => $_POST['model'],

            ':year' => $_POST['year'],

            ':mileage' => $_POST['mileage']));

        $_SESSION['success'] = 'Record Added';

        header( 'Location: index.php' ) ;

        return;

?>


<form method="post">

<p>Make:

<input type="text" name="make"></p>

<p>Model:

<input type="text" name="model"></p>

<p>Year:

<input type="number" name="year"></p>

<p>Mileage:

<input type="number" name="mileage"></p>

<p><input type="submit" value="Add New"/>


<!--SQL schema--!>

CREATE TABLE autos (

  autos_id INTEGER NOT NULL KEY AUTO_INCREMENT,

  make VARCHAR(255),

  model VARCHAR(255),

  year INTEGER,

  mileage INTEGER

) ENGINE=InnoDB DEFAULT CHARSET=utf8;


一只甜甜圈
浏览 88回答 1
1回答

Qyouu

这里的问题是 PHP POST 数据是字符串,因此您需要在插入之前对其进行转换。<--PDO code--><?php$pdo = new PDO('mysql:host=localhost;port=8888;dbname=xxxx',&nbsp;&nbsp; &nbsp;'xxx', 'xxx');$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);&nbsp;//SQL&nbsp;&nbsp;$sql = "INSERT INTO cars (make, model, year, mileage)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; VALUES (:make, :model, :year, :mileage)";&nbsp; &nbsp; &nbsp; &nbsp; $stmt = $pdo->prepare($sql);&nbsp; &nbsp; &nbsp; &nbsp; $stmt->execute(array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ':make' => $_POST['make'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ':model' => $_POST['model'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ':year' => intval($_POST['year']),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ':mileage' => intval($_POST['mileage'])));&nbsp; &nbsp; &nbsp; &nbsp; $_SESSION['success'] = 'Record Added';&nbsp; &nbsp; &nbsp; &nbsp; header( 'Location: index.php' ) ;&nbsp; &nbsp; &nbsp; &nbsp; return;?><form method="post"><p>Make:<input type="text" name="make"></p><p>Model:<input type="text" name="model"></p><p>Year:<input type="number" name="year"></p><p>Mileage:<input type="number" name="mileage"></p><p><input type="submit" value="Add New"/>
打开App,查看更多内容
随时随地看视频慕课网APP