PHP Catchable fatal error: Object of class mysqli could not be converted to string

0

I'm starting in PHP, and I think my code is missing something so that it can work, because the error that I mentioned occurs.

The code of my mysqlcon.php is:

<?php
session_start();
$host=;
$username=;
$password= ;
$db_name=;
$link=mysqli_connect("$host", "$username", "$password")or die("Cannot Connect");
mysqli_select_db("$link", "$db_name")or die("Cannot Select DB");
?>
    
asked by Esteban Carvajal 26.04.2018 в 02:29
source

2 answers

1

The problem

The error:

  

Object of class mysqli could not be converted to string

means that here:

$link=mysqli_connect("$host", "$username", "$password") or die ("Cannot Connect");

you would normally get a object of type mysqli

but then in this line you treat it as a string when you write it in quotes:

mysqli_select_db("$link", "$db_name")or die("Cannot Select DB");

Solutions

The most optimal

Select the database when you create the connection, so you make a single call:

$link = mysqli_connect($host, $username, $password, $db_name);

Le least optimal

Leave it as you have it, but remove the quotes. The only thing that justifies this second form would be that you are going to change the database at some point ... In fact, the Manual says the following about it:

  

This function should only be used to change the database by   defect for the connection. You can select the database by   defect in the fourth parameter of the function mysqli_connect() .

$link=mysqli_connect($host, $username, $password) or die("Cannot Connect");
mysqli_select_db($link, $db_name) or die ("Cannot Select DB");

The use of quotes in the other variables does not give an error because they are still strings, but it does not make sense to use quotes in them.

Also

You can use the Object Oriented style to create the connection. It is more modern and understandable.

$link = new mysqli($host, $username, $password, $db_name);
if ($link->connect_errno) {
    echo "Fallo al conectar a MySQL: (" . $link->connect_errno . ") " . $link->connect_error;
}

In that case, it is convenient that all the sub-following code is object oriented.

    
answered by 26.04.2018 в 02:48
0
<?php
    session_start();
    $host=;
    $username=;
    $password= ;
    $db_name=;
    $link=mysqli_connect($host, $username, $password, $db_name)or die("Cannot Connect");

I'll tell you the following about your code

Variables are not enclosed in quotation marks, otherwise they are read as text strings Since you are using mysqli, you pass even the name of the database in the first connect function, you did not need the one that says select_database

    
answered by 26.04.2018 в 02:41