I'm having this error "Warning: mysqli_query () expects parameter 1 to be mysqli" in php when querying the database [duplicate]

-1

Hello, I'm trying to get the courses from the database. To see the courses already registered, do not register in db again. I'm getting this error:

  Warning: mysqli_query() expects parameter 1 to be mysqli, null given in 
  /storage/emulated/0/Documents/sistemaescolar/public/cad/curso.php on line 6

the connection code

$host="127.0.0.1";
$db="sistemaescolar";
$pswd="";
$user="root";
$connect  =  mysqli_connect ($host,$user,$pswd,$db);

if (mysqli_connect_errno()){
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
} 

I made this page below to decide what type will become of cadatro, coming from another form:
include_once "class_pessoa.php";
if(isset($_POST["buttonSubmit"])){
    $escolha = filter_input(INPUT_POST,'opselect',FILTER_SANITIZE_NUMBER_INT);
    if(filter_var($escolha,FILTER_VALIDATE_INT)){
        include_once "cad/conexao.php";
        $sql = "SELECT * from tipoCad where id=$escolha";
        $resultado = mysqli_query($connect,$sql);
        $dado= mysqli_fetch_assoc($resultado);
        if($dado["nome"] =="Curso"){
            $curso = new Curso($dado["nome"]);
        }
        mysqli_close($connect);
    }                           
}

In the part where you have the class Travel, you have a form to be able to register in db

Below is the code that is giving error when searching the database:

    $sql = "select * from cursos";
    $resultado=mysqli_query($connect,$sql); 
    while($dados= mysqli_fetch_assoc($resultado)){
        echo $dados['nome'];
    }

    
asked by anonymous 22.06.2018 / 05:29

1 answer

3

If you give echo in this SELECT statement

$escolha="qqcoisa";
$sql = "SELECT * from tipoCad where id=$escolha";
echo $sql;

return will be SELECT * from tipoCad where id=qqcoisa

and this SQL results in error Unknown column 'qqcoisa' in 'where clause'

translating Coluna desconhecida 'qqcoisa' em 'where cláusula'

The correct thing is to put the variable $escolha in single quotation marks

$escolha="qqcoisa";
$sql = "SELECT * from tipoCad where id='$escolha'";
echo $sql;

for the syntax to be correct, ie

 $sql = "SELECT * from tipoCad where id='$escolha'";
  

sql needs to use ' (single quotes) when it is string, for numbers do not need

$sql = "SELECT * from tipoCad where id=10";
  

If there is a column named qqcoisa in the SELECT * from tipoCad where id=qqcoisa it will return the records whose values of the id column are equal to the values of the qqcoisa column

    
22.06.2018 / 10:56