How to take the value of an sql record and store in PHP variable

Asked

Viewed 189 times

2

I have an sql table as follows:

usuario 
(`matricula` varchar(20) not null primary key,
  `nome` varchar(45) NOT NULL,
  `senha` varchar(15) NOT NULL);

In php I’m trying to get the name of a user who has the license plate specified by mysqli:

$nomeUsuario = mysqli_query($conexao, "SELECT nome FROM usuario WHERE matricula = $matricula");

But it’s not working very well, even using the mysqli_fetch_assoc.

Any idea what’s wrong?

  • Hello @Amanda, Welcome to Sopt, before you start a look at our [Tour] -- Your code shows some error? If yes is worth asking the question. How are you using the variable $nomeUsuario?, To $conexao this ok?, This information will help the community better understand their problem. = D

1 answer

1


the registration column, which is your primary key, is your primary key, is of the type varchar ; then your SQL needs to receive strings and not integer, as your example. The corrected code:

$nomeUsuario = mysqli_query($conexao, "SELECT nome FROM usuario WHERE matricula ='". $matricula."');

Some tips that might help you:

  1. Having a varchar as a primary key can slow your requests a little, it is recommended to have a column that auto fills with integer values, mainly to be more effective in uniting the tables with Inner Join.
  2. You can see the SQL error in your php if you use this code here: https://www.w3schools.com/php/func_mysqli_error.asp
  if (!mysqli_query($conexao,"SELECT nome FROM usuario WHERE matricula = $matricula")
   {
             echo("Descrição do erro: " . mysqli_error($conexao));
   }


Browser other questions tagged

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