Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do mysql_fetch_assoc in mysqli?

Tags:

php

mysqli

How can I do the following in mysqli prepare statement?

$result = mysql_query($sql);
$data = mysql_fetch_assoc($result);
return $data:
like image 544
dev Avatar asked Apr 16 '11 20:04

dev


People also ask

What will mysql_fetch_assoc () return?

Description ¶ Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.

How does mysql_fetch_assoc work?

The mysql_fetch_assoc() function returns a row from a recordset as an associative array. This function gets a row from the mysql_query() function and returns an array on success, or FALSE on failure or when there are no more rows.

What does mysqli_fetch_assoc () do in PHP?

The PHP mysqli_fetch_assoc() function returns an associative array which contains the current row of the result object. This function returns NULL if there are no more rows.

What is the difference between mysql_fetch_array () and mysql_fetch_assoc ()?

Difference: mysql_fetch_assoc() will always assing a non-secuencial key (like "color" and not a number). mysql_fetch_array() will assing a number key if there are not "word" key (0 and not "color" if there are not "color") but, you can choose to assing of key with a parameter...


2 Answers

You need to use the MySQLi version of the functions:

$result = mysqli_query($sql);
$data = mysqli_fetch_assoc($result);
return $data;

That should do it, you also might want to take a look at:

  • http://php.net/mysqli
  • http://www.php.net/manual/en/class.mysqli-result.php
like image 102
alizahid Avatar answered Sep 23 '22 08:09

alizahid


That's pretty simple after you've created the connection to mysql somewhere:

<?php
// create the connection to mysql.
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
?>

The refer to the mysqli object when you need to do a query or do something else.

<?php
// get the result object.
$result = $mysqli->query($sql);
// fetch the result row.
$data = $result->fetch_assoc();

return $data;
?>

Then at some point (if you have a class, you can write a destructor) you should close the connection to mysql if you won't need it anymore.

<?php
$mysqli->kill($mysqli->thread_id);
$mysqli->close();
?>

You can do much more with the result object you have. So read more about the MySQLi_Result here:

  • http://www.php.net/manual/en/class.mysqli-result.php
like image 40
Rihards Avatar answered Sep 26 '22 08:09

Rihards