Home » Php » Inserting indexed array into an database with PHP and MySqli

Inserting indexed array into an database with PHP and MySqli

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m trying to get an indexed array’s values inserted into a SQL database with MySQLi and PHP but I can’t figure out why it’s not working.

$con = mysqli_connect("localhost","user","pword","db");
if (mysqli_connect_errno()) {
   echo "Unable to connect to MySQL! ". mysqli_connect_error();
   exit();
}

$sqli = "INSERT INTO path_info (path_name,operating_frequency,pi_description,pi_note) VALUES (?,?,?,?)";
$stmt= $con->prepare($sqli);
$stmt->bindParam("ssss",$csv[0],$csv[1],$csv[2],$csv[3]);
$status = $stmt->execute();
if (!$status) {
    echo "Error ".$stmt->errorCode()."\nMessage ".implode($stmt->errorInfo())."\n";
    exit(1);
}
How to&Answers:

problem is at bindParam

$stmt->bindParam(1,$csv[0]);
$stmt->bindParam(2,$csv[1]);
$stmt->bindParam(3,$csv[2]);
$stmt->bindParam(4,$csv[3]);

correct format is as above

also use try-catch

$con= new PDO("mysql:host=127.0.0.1;dbname=task", 'root', 'root');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$csv = array('test', 15, 'testing', 'noted');
$sqli = "INSERT INTO path_info (path_name,operating_frequency,pi_description,pi_note) VALUES (?,?,?,?)";

$stmt= $con->prepare($sqli);
$stmt->bindParam(1,$csv[0]);
$stmt->bindParam(2,$csv[1]);
$stmt->bindParam(3,$csv[2]);
$stmt->bindParam(4,$csv[3]);
$status = $stmt->execute(); 
if (!$stmt) {
    echo PDO::errorInfo();
}

Answer:

It’s bind_param when working with mysqli.
It’s bindParam when working with PDO.

<?php
    $con = mysqli_connect("localhost","user","pword","db");
    if (mysqli_connect_errno()) {
       echo "Unable to connect to MySQL! ". mysqli_connect_error();
       exit();
    }

    $sqli = "INSERT INTO path_info (path_name,operating_frequency,pi_description,pi_note) VALUES (?,?,?,?)";
    $stmt= $con->prepare($sqli);
    $stmt->bind_param("ssss", $csv[0],$csv[1],$csv[2],$csv[3]);
    $status = $stmt->execute();