Insert data into database using PDO

Asked

Viewed 66 times

0

$servidor = "localhost";
$usuario ="root";
$senha="";
$db="pdo";

$conexao = new PDO('mysql:host = localhost; dbname = pdo', $usuario,$senha);

$stmt = $conexao->prepare('INSERT INTO tabela_pdo(nome) VALUES(:nome)');
$stmt->execute( array(':nome' => 'Lucas') );

I can’t find the error in this code, it’s not adding the data. Would someone please give me a hint? Thanks in advance for your attention.

  • Which error is returned?

  • Birth, remove these spaces, leave so $conexao = new PDO('mysql:host=localhost;dbname=pdo', $usuario,$senha);, Otherwise I see no error, here it works, just remove the spaces in your DSN. If it’s not that, it’s probably the port, you need to change the port. To change the door would be: $conexao = new PDO("mysql:host=$servidor;port=$port;dbname=$db", $usuario,$senha);

  • Thanks for the tips

1 answer

1


Use the variables in your DSN, remove the spaces of type(host = $servidor) and set the door even if it’s the standard that is 3306.

<?php

$servidor="localhost"; 
$usuario="root"; 
$senha=""; 
$db="pdo";
$port='3306';

$conexao = new PDO("mysql:host=$servidor;port=$port;dbname=$db", $usuario,$senha);

$stmt = $conexao->prepare('INSERT INTO tabela_pdo(nome) VALUES(:nome)'); 

$stmt->execute( array(':nome' => 'Lucas') );
  • Thanks for the tips

  • @Birth has solved its problem, only accept this answer as the correct one. Hug!

Browser other questions tagged

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