Insert data into the database using mysqli

4

How do I insert this data into the database using mysqli :

print $data->access_token."<br />";
print $data->username."<br />";
print $data->full_name."<br />";
print $data->id."<br />";

...

$conexao = mysql_connect($localhost, $usuario, $senha) or die();
$select =mysql_select_db($bancodedados) or die();
$query = mysql_query("INSERT INTO 'usuarios' () VALUES()");

I'm trying (according to @ Lost's suggestion):

$mysqli = new mysqli('localhost','root','','instagram');
$sql = 'INSERT INTO instagram (acess_token, username, full_name, id) values(?,?,?,?)';
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ssss", $data->acess_token, $data->user->username, $data->user->full_name
, $data->user->id   );
$stmt->execute();

But I get the following error:

( ! ) Fatal error: Call to a member function bind_param() on a  
non-object in C:\wamp\www\instagram\example\success.php on line 30  
Call Stack  
#   Time    Memory  Function    Location 1  0.0020  146880  {main}( ) ..\success.php:0
    
asked by anonymous 05.05.2014 / 08:23

2 answers

6

To use mysqli with prepared statements is the following code:

$mysqli = new mysqli('host','usuario','senha','base');
$sql = 'INSERT INTO tabela (campo1, campo2, campo3) values(?,?,?)';
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sss", $variavel1, $variavel2, $varivavel3);
$stmt->execute();

The three s and bind_param() mean the type of past data that can be:

s: para 'string'
i: para 'inteiro'
d: para 'double'
b: para 'blob'
    
05.05.2014 / 12:51
3

First of all, connections using mysql_connect are being discontinued by PHP, so it is recommended to treat your connections using PDO.

But, roughly speaking, it would look like this:

$sql = "INSERT INTO tabela (coluna1, coluna2, coluna3, ... colunaN) VALUES ('val1', 'val2', 'val3', ... 'valN')";
$query = mysql_query($sql) or die(mysql_error());
    
05.05.2014 / 10:12