Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting into database using mysqli

Tags:

php

mysql

mysqli

I am learning php and trying to make the following work:

<?php
require_once("db_connect.php");

    // TODO - Check that connection was successful.

    $dname = $_POST["dname"];
    $daddress = $_POST["daddress"];


    $stmt = $mysqli->prepare("INSERT INTO test (dname, daddress) VALUES (?, ?)");

    // TODO check that $stmt creation succeeded

    // "s" means the database expects a string
    $stmt->bind_param("s", $dname, $daddress);

    $stmt->execute();

    $stmt->close();

    $mysqli->close();
?>

It works with just one bind_param but not 2. If $daddress was removed from the code then it posts. The form has 26 posts into database I am doing it with 2 at the moment to keep it minimal.

I get the following error when the form is submitted.

Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of elements in type definition string doesn't match number of bind variables in /home/mymotorsportco/public_html/entry/actions/entry.php on line 15

like image 711
Joseph Thomas Mallinson Avatar asked Jan 06 '23 16:01

Joseph Thomas Mallinson


2 Answers

As per PHP manual:

types

A string that contains one or more characters which specify the types for the corresponding bind variables

i - corresponding variable has type integer

d - corresponding variable has type double

s - corresponding variable has type string

b - corresponding variable is a blob and will be sent in packets

You have to add types for all the parameters you are binding. So if the second parameter is a string, you have to do

$stmt->bind_param("ss", $dname, $daddress);
like image 84
Alex Karshin Avatar answered Jan 15 '23 12:01

Alex Karshin


You need to pass in the same amount of characters into the first argument, as you have values to inject into your query. For example:

 $stmt->bind_param("ss", $dname, $daddress);

Will say that the first param is a string, as well as the second. Additionally, the following will tell the database to expect a string, then an int:

 $stmt->bind_param("si", $dname, $daddress);

Big props for using prepared statements, most newbies will throw in variables with absolutely no sanitation. You're on the right track!

like image 42
samrap Avatar answered Jan 15 '23 12:01

samrap