I'm learning PHP. I've seen these two approaches to connecting to a MySQL database.
Could someone explain what's the difference between them, and why the second approach doesn't work in a standard form submission (is there a syntax error I have missed)?
Approach 1 (works):
$mysqli = new mysqli("$mysql_server", "$mysql_user", "$mysql_pw", "$mysql_db");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
Approach 2 (throws a server error):
$link = mysqli_connect("$mysql_server", "$mysql_user", "$mysql_pw", "$mysql_db");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
Approach 1 is the object oriented approach. Approach 2 is the procedural approach.
Approach 1 is object oriented while 2 is procedural.
Code for Your Help is :
// connection
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
//consultation
$query = "SELECT name FROM mytable" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = mysqli_query($link, $query);
//display information:`enter code here`
while($row = mysqli_fecth_array($result)) {
echo $row["name"] . "<br>";
}