Emilien Lecoffre
Emilien Lecoffre

Reputation: 25

Read a MySQL DB with PHP

I have a MySQL database on my hosting and am trying to query it with PHP on a dedicated PHP file, content.php :

<?php
//on inclue un fichier contenant nom_de_serveur, nom_bdd, login et password d'accès à la bdd mysql
include ("membersarea/connect.php");
//on se connecte à la bdd
$connexion = mysqli_connect (SERVEUR, LOGIN, MDP);    
if (!$connexion) {echo "LA CONNEXION AU SERVEUR MYSQL A ECHOUE\n"; exit;}
mysqli_select_db ($connexion, BDD); print "Connexion BDD reussie";echo "<br/>"; 

$result = mysqli_query($connexion, "SELECT contenu FROM content WHERE id=1");
$text =  mysqli_fetch_field($result);
?>

I want to display the BDD data on my index.php file so I included the content.php at the begining of index.php :

<?php
include ("content.php");
?>

and display between HTML balises with :

<?= $text ?>

Unfortunately i get the following error "Recoverable fatal error: Object of class stdClass could not be converted to string"

I don't really understand why (as the data in the DB is a "text") or how to fix it. Thank you for reading until here, any help is welcome ! :)

Upvotes: 0

Views: 64

Answers (2)

ScaisEdge
ScaisEdge

Reputation: 133370

mysqli_fetch_field($result) return a row object not a text

$obj=  mysqli_fetch_field($result);

echo  $obj->contenu;

https://www.php.net/manual/en/mysqli-result.fetch-field.php;

Upvotes: 1

Joni
Joni

Reputation: 111259

Use mysqli_fetch_row instead of mysqli_fetch_field:

$row =  mysqli_fetch_row($result);
$text = $row[0];

The mysqli_fetch_field function returns field metadata (what is its name, which table did it come from, ...). You need to use a different function to get the field values for the rows in the result set.

Upvotes: 1

Related Questions