Warning: mysql_fetch_array () expects parameter 1 to be resource, null given in

1

I make the connection to the database:

$db_host="localhost";
$db_nombre="prueba"; 
$db_user="root"; 
$db_pass=""; 

$link=mysql_connect($db_host, $db_user, $db_pass);

Now I make the query:

$strQuery = "SELECT id, nombre FROM persona";
$resultado = mysql_query ($strQuery);

When I try to browse the ResulSet using mysql_fetch_array:

while($arreglo = mysql_fetch_array ($resultado)) {
    echo $arreglo ["nombre"];
}

Launches me the error

  

mysql_fetch_array () expects parameter 1

The fact is that if I recover the information as follows:

//Resultado 1
$arreglo = mysql_fetch_array ($resultado)
echo $arreglo["nombre"];
//Resultado 2
$arreglo = mysql_fetch_array ($resultado)
echo $arreglo["nombre"];
//Resultado 3
$arreglo = mysql_fetch_array ($resultado)
echo $arreglo["nombre"];

Print me the expected values.

Any ideas?

    
asked by nachfren 26.07.2016 в 17:25
source

2 answers

1

As @Hechi points in the comment of the question, you need to select the database, mysql uses two different functions to configure the connection correctly.

//...
$link     = mysql_connect($db_host, $db_user, $db_pass);
$selectDb = mysql_select_db($db_nombre, $link);
//...

Here you have the different basic connections, mysql , mysqli and class mysqli .

  

As an informative note, mysql is declared obsolete in new versions of php, from 5.5.0 and deleted from php 7.0.0.

    
answered by 27.07.2016 в 18:50
0

That happened to me, when connecting my database with a file conexion.php told me the same ( mysql_fetch_array() expects parameter 1 ). Then I decided to change all mysql by mysqli .

As a result, I also changed some things: I was not using $db_host but $host like this:

<?php
global $host,$user,$password,$database;
$host='mysql.hostinger.mx';
$user='usuario_nombre';
$pass='simulacro';
$database='numero_nombre';
$conexion=mysqli_connect($host,$user,$pass) or die ("conexion fallida");
mysqli_select_db($conexion,$database) or die ("Error al conectarse con la Base de Datos".mysqli_error($conexion));
?>

It's more for complexity, for not losing or damaging the code in case I later get to use some similarity, and then in all the files I'll just put require('conexion.php'); and ready, all pages connected with just that code

Then you put

<? 
$query="SELECT * FROM tabla (condisionales WHERE, ASC, DESC...)";
$resultado=$conexion->query($query);
while($row=$resultado->fetch_assoc()){ 
    ?>RESULTADO QUE QUIERES QUE SE MUESTRE
     y finalizas con
<?}?>

and voila, you have the data sampling of the table.

    
answered by 01.11.2016 в 03:45