Mohan Wijesena
Mohan Wijesena

Reputation: 235

Sanitizing insert with prepared statements

I have this snippet where I'm trying to insert large set of data to MySQL database.

$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
    $sql = "INSERT into universe (`zone`, `area`, `sub`) values('$emapData[0]','$emapData[1]','$emapData[2]')";
}

I tried 'preparing' the data prior to the insert and made an attempt to sanitize,

$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
    $sql = $conn->prepare ("INSERT into universe (`zone`, `area`, `sub`) values(?,?,?)");
    $sql = bind_param("sss", '$emapData[0]','$emapData[1]','$emapData[2]');
}

And this gives me an error :

Uncaught Error: Call to undefined function bind_param()

Where and how do you suggest that I define bind_param earlier? Thank you.

Upvotes: 0

Views: 183

Answers (1)

Cid
Cid

Reputation: 15247

You aren't far from the expected result.

bind_param() is a method from the mysqli_stmt class. You get an instance of this class when doing $sql = $conn->prepare(...);

All you have to do is to call that function from the $sql object.

By the way, you don't have to wrap $emapData[x] into single quotes.

$sql = $conn->prepare("INSERT into universe (`zone`, `area`, `sub`) values(?, ?, ?)");
$sql->bind_param("sss", $emapData[0], $emapData[1], $emapData[2]);

Upvotes: 1

Related Questions