Insert an ID into SQL+PHP

Asked

Viewed 103 times

1

I’m making a form where the user inserts the data and the same receives the confirmation along with a ID record in php with sql, I’m just not getting this final confirmation along with the id, someone can help me?

I know that in mysql is like this.

$exec_sql = mysql_query($select); 

if (!$exec_sql) {
    print mysql_error();
}
else {
    $id = mysql_insert_id();    
    print '<h3>Registro #'.$id.' inserido com sucesso</h3>';

but and in sql?

  • The code seems correct except for using obsolete functions but what is the problem?

  • I believe this code is correct, but subsequent or previous code may contain errors, it would be interesting to post all code. (do not use mysql because it is obsolete with already quoted)

1 answer

0

An example code for this action.

<?php
//Define as variáveis do banco
$servername = "localhost";
$username = "username";
$password = "password";

// Cria a conexão
$conn = new mysqli($servername, $username, $password);

//Verifica a conexão
if($conn->connect_error){
    die("Connection failed: " . $conn->connect_error);
}else{ 
echo "Conexão ok";
}
//Atribui a consulta a uma variável, você está usando select como nome de variável, mas é presumível um INSERT
$select = "INSERT INTO minhaTabela (colunaFoo, colunaBar)
VALUES ('dadoFoo', 'dadoBar')";

//Executa a consulta
$exec_sql = mysqli_query($conn, $select);

if(!$exec_sql){
print mysqli_error($conn);
}
else{
$id = mysqli_insert_id($conn);    
print '<h3>Registro #'.$id.' inserido com sucesso</h3>'; 
}

//Fecha a conexão   
mysqli_close($con);
?>

I hope it helps.

Browser other questions tagged

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