0

There are a lot of questions with this error. I've read all of them but none of them resolves my problem. Their problems are totally differents, that's why I'm asking.

I'm getting this error: Fatal error: Call to a member function query() on a non-object. It's on line $conexion->query($consulta);. I've checked if the connection object ($conexion) is null and it's not, it's correctly filled with the connection. I've also tried to make a custom default query (just in case the query wasn't correct) but I'm still having the problem.

So, what's going on here?

This is my code:

<?php 

function conectar(){

    $data = include_once('configDB.php');
    $c = mysql_connect($data["server"], $data["user"], $data["pass"]);

    if ($c)
        return $c;
    else
        exit("fail");
}

function insertar($nombre, $resultados, $tiempo){

    $conexion = conectar();

    $consulta = "INSERT INTO juegopreguntas (nombre, p1, p2, p3, p4, p5, tiempo) VALUES 
('".$nombre."',".$resultados[0].",".$resultados[1].",".$resultados[2].",".$resultados[3]
.",".$resultados[4].",'".$tiempo."')";

    $conexion->query($consulta);

    cerrarConexion($conexion);

}

function cerrarConexion($conexion){

    mysql_close($conexion);
}
?>
Drumnbass
  • 867
  • 1
  • 14
  • 35
  • 1
    If you can, you should [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Dec 01 '15 at 21:11
  • 1
    Your conectar() function returns a resource handle, not an object, and so you would have to use: mysql_query ( $consulta, $conexion ) – Kris Oye Dec 01 '15 at 21:12
  • 1
    mysql_*() functions are not, have NEVER been, and never WILL be, object-enabled. mysql != mysqli – Marc B Dec 01 '15 at 21:15

1 Answers1

0

You should select the database on connection

<?php 

function conectar(){

    $data = include_once('configDB.php');
    $c = mysql_connect($data["server"], $data["user"], $data["pass"], $data['database']);

    if ($c)
        return $c;
    else
        exit("fail");
}

function insertar($nombre, $resultados, $tiempo){

    $conexion = conectar();

    $consulta = "INSERT INTO juegopreguntas (nombre, p1, p2, p3, p4, p5, tiempo) VALUES 
('".$nombre."',".$resultados[0].",".$resultados[1].",".$resultados[2].",".$resultados[3]
.",".$resultados[4].",'".$tiempo."')";

    $query = mysql_query($consulta);

    cerrarConexion($conexion);

}

function cerrarConexion($conexion){

    mysql_close($conexion);
}
?> 
Fahed Alkaabi
  • 269
  • 2
  • 10