简体   繁体   中英

inserting data from form into my sql databse with php

Hello I have written a code to insert data from a form to mysql database :

$conn = new PDO("mysql:dbname=data12;host=$servername", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$ul = $_POST['fname'];
$sql="insert into t22 values('16',".$ul.")";

The record is added but the value is empty. I have also tried other syntaxes like :

$sql="insert into t22 values('16',$ul)";
$sql="insert into t22 values('16','".$ul."')";
$sql="insert into t22 values('16',$ul)";

please help me about that.

Use this code:

<?php
$conn = new PDO("mysql:dbname=data12;host=$servername", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$ul = $_POST['fname'];
$id = 16;


$sql="INSERT INTO t22 (data1,data2) VALUES(?,?)";
$result = $conn->prepare($sql); 
$result->execute(array($id,$ul)); 

?>

Change data1 and data2 with the names of the columns

This works for me.
I am sure it works for you!

First thing first to make sure that empty values are not inserted, you need to check if that value is set from the form then execute the query when the value is set, also you need to prepare your statements when using PDO, also don't directly enter you variables in your query use placeholders instead.

This how you code should look:

<?php
$conn = new PDO("mysql:dbname=data12;host=$servername", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


$errors = "";

$number = 16;

if (isset($_POST['buttonName'])) {

    //check if the field is not empty


    if (empty($_POST['fname'])) {

        echo "enter name";
        $errors++;
    } else {


        $ul = $_POST['fname'];
    }

    if ($errors <= 0) {//no errors lets insert

        $sql = $conn->prepare("INSERT INTO t22 (id,name) values(?,?)");
        $sql->execute(array(
            $number,
            $ul
        ));

        echo "record entered";
    }

}

?>

Hope this can point you on the correct direction.

NB: its important that you filter and sanitize $_POST values before storing them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM