Mohaideen
Mohaideen

Reputation: 303

How to insert Integer value in DB - PHP

I have using PHP for inserting integer value in Database.

Iam using like this

$postcode = $_POST['postcode'];
$mysql_user_resultset = mysqli_query($con, "INSERT into user (postcode) VALUES ($postcode)");

I have several field in DB. like name, username, etc. all are defined as varchar, but postcode only defined as int. If not enter the value for postcode, it doesn't insert into database

Upvotes: 2

Views: 10113

Answers (3)

Dmitriy.Net
Dmitriy.Net

Reputation: 1500

Use PDO or sprintf for formatting mysql query:

sprintf example:

$mysql_user_resultset = mysqli_query($con, sprintf(
  "INSERT into user (postcode) VALUES (%d)", 
$_POST['postcode']));

PDO example:

$st = $db->prepare("INSERT into vendors user (postcode) VALUES (:postcode)");
$st->bindParam(':postcode', $_POST['postcode'], PDO::PARAM_INT);
$mysql_user_resultset = $st->execute();

Upvotes: 1

poiseberry
poiseberry

Reputation: 143

Convert $_POST['postcode'] to int, using

$postcode = (int)$_POST['postcode'];

Upvotes: 1

Fadey
Fadey

Reputation: 430

You could simply cast your variable into int:

$postcode = (int) $_POST['postcode'];
$mysql_user_resultset = mysqli_query($con, "INSERT into user (postcode) VALUES ($postcode)");

Note that you're not using any precautions regarding SQL injections, I would suggest you to bind your parameters before query them, using PDO class.

Upvotes: 1

Related Questions