简体   繁体   中英

how to store form data in mysql using php

I run the following code but it's displaying array values not storing data into mysqldb.

<?php

       if(! empty( $_POST)){
        print_r($_POST);exit;
        $mysqli = new mysqli('localhost', 'root','','mydb');
        if($mysqli->connect_error){
        die('connect error:'. $mysqli->connect_errno .':' . $mysqli->connect_error);
        }
        }

?>

register.php:

    <?php
     require('db.php');
     $conn=mysqli_connect("localhost","root","");
     $name = $_POST['name'];
     $name1 = $_POST['skill'];
     $name2= $_POST['exp'];
     $name3 = $_POST['sele'];
     $sql = "INSERT INTO register VALUES('".$name."','".$name1."','".$name2."','".$name3."')";
    $insert = $mysqli->query($conn,$sql);
    echo $insert;
     ?>

Getting array result in browser

The connection object is already defined - $mysqli . Why $conn again? Just do -

$sql = "INSERT INTO register VALUES('".$name."','".$name1."','".$name2."','".$name3."')";
$insert = $mysqli->query($sql);

$conn will be required if you were using the procedural approach.

mysqli

Just replace: $insert = $mysqli->query($conn,$sql);

With:

$insert = $mysqli->query($sql);

Let's start by the beginning.

  • Use PDO (optional). You look like a newbie, so start with good bases.
  • Check if your _POST variables exist (and eventually check for type (not array))
  • Use bindparam to automatically insert data (without risk of sql injections)

$fields = ["name", "skill", "exp", "sele"];
$params = [];
foreach($fields as $field) {
    if(!isset($_POST[$field])) {
        exit("Field required: $field");
    }
    $params[":$field"] = $_POST[$field];
}

$pdo = new PDO("mysql:host=localhost;dbname=database", 'username', 'password');
$sth = $pdo->prepare('
    INSERT INTO register VALUES(:name, :skill, :exp, :sele);
');
$sth->execute($params);

If you still wanna stick with mysqli ...

$fields = ["name", "skill", "exp", "sele"];
$params = [];
foreach($fields as $field) {
    if(!isset($_POST[$field])) {
        exit("Field required: $field");
    }
    $params[":$field"] = $_POST[$field];
}

$mysqli = new mysqli('localhost','username','password','database');
$query = $mysqli->prepare('
    INSERT INTO register VALUES(?, ?, ?, ?);
');
call_user_func_array(array($query, "bind_param"), $params);
$query->execute();

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