Insert data into database using mysqli

Asked

Viewed 6,602 times

5

How do I insert this data into the database 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 the suggestion of @lost):

$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 mistake:

( ! ) 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
  • 2

    That’s not mysqli, is mysql same... (note that "i" is missing after "mysql" in all calls) And - as pointed out in the replies - this type of connection is obsolete (deprecated), use PDO would be preferable. I can’t talk about mysqli however as I have no experience.

  • I didn’t understand if you want to know how to do the sql query or how to apply this query with PHP (mysqli)

  • If you want to change, improve or update your question do not create an answer. The best thing to do is edit your post, to put the extra details. If you solve the problem of your question but it leads to a new doubt, there is no problem in creating a new question (you can even refer to your previous question, to give a context).

  • There is some error in your query, to display it use this code: $stmt = $mysqli->prepare($sql);&#xA; if($stmt == ''){ &#xA; echo $mysqli->error;&#xA; }

2 answers

7

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();

all three s in the bind_param() means the kind of past data that may be:

s: para 'string'
i: para 'inteiro'
d: para 'double'
b: para 'blob'

3

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

But in the brute way:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.