Connecting PHP to the Mysql database

Asked

Viewed 1,009 times

1

I need help I am trying to connect my PHP file with the database to be able to perform a query and present on the screen the records.

Connection code:

define('usuario_bd', 'root');
define('senha_bd', '');
define('nome_bd', 'loja');

mysql_connect('localhost/phpmyadmin', usuario_bd, senha_bd);
mysql_select_db(nome_bd);

$pesquisa = "SELECT * FROM nome";
$querybd = mysql_query($pesquisa);

while($correto = mysql_fetch_array($querybd)){
        echo $correto["nome"];
}

My server is Wampserver connection with phpMyAdmin.

  • put only localhost and mysql is being discontinued, use mysqli, Give some error?

  • Yes, the following errors have occurred Fatal error: Uncaught Error: Call to Undefined Function mysql_select_db() in C: wamp64 www pedemoca model conexao.php on line 7 ( ! ) Error: Call to Undefined Function mysql_select_db() in C: wamp64 www pedemoca model conexao.php on line 7

  • Do the Following $connected = mysql_connect('localhost', usuario_bd, password_bd); and in mysql_select_db(name_bd, $connected); and have this removed in php 7 if you are using 7 it will not work you have to go to mysqli

4 answers

4


The Phpmyadmin nay is a database and mysql nay connects via HTTP, mysql itself is already a proper TCP protocol.

Mysql and Phpmyadmin difference

read this:

Don’t use the old API

The functions that begins with mysql_ in the prefix are Old API, read this:

How to use the Mysqli API to connect to the Mysql database

The variable $host should contain only the HOST of your mysql server, which has nothing to do with Apache and nothing to do with HTTP:

<?php

$host = 'localhost';
$usuario = 'root';
$senha = 'minhasenha';
$banco = 'meubanco';

$link = mysqli_connect($host, $usuario, $senha, $banco);

if (mysqli_connect_error()) {
    printf('Erro de conexão: %s', mysqli_connect_error());
    exit;
}

if (!mysqli_set_charset($link, 'utf8')) {
    printf('Error ao usar utf8: %s', mysqli_error($link));
    exit;
}

if ($result = mysqli_query($link, 'SELECT * FROM nome')) {

    /* Pegando os dados */
    while ($row = mysqli_fetch_assoc($result)) {
        echo $row['nome'];
    }

    /* libera os resultados */
    mysqli_free_result($result);
} else {
    /*Trata o erro da query, se ocorrer*/
    printf('Erro na query: %s', mysqli_error($link));
    exit;
}

/* fecha a conexão */
mysqli_close($link);

Handling error in query:

Probably your query is wrong, so you commented:

With mysqli another error occurs, in the case of Mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given - Otávio Guilherme

As an example I made, have an if and an Else:

if ($result = mysqli_query($link, 'SELECT * FROM nome')) {
    ... SE OCORRER TUDO NORMAL ...
} else {
    ... SE TIVER UM ERRO NA QUERY ...
}

UTF-8

If not using UTF-8 remove this part:

if (!mysqli_set_charset($link, 'utf8')) {
    printf('Error ao usar utf8: %s', mysqli_error($link));
    exit;
}
  • Thank you very much for the detailed explanation now I am more attentive to the differences and the right way to use and speak.

  • 1

    @Otávioguilherme do not worry, it is normal even those who are starting and even some with experience do not understand what is TCP and how it works, by this same question that "Linkei" I answered, is like a basic tutorial for those who are starting ;)

1

Do the following if nothing I’ve been through works, it seems your php version has already removed mysql_select_db so do it with mysqli is that simple

define('usuario_bd', 'root');
define('senha_bd', '');
define('nome_bd', 'loja');

$conexao = mysqli_connect('localhost', usuario_bd, senha_bd, nome_bd);
$retorno = mysqli_query($conexao,"SELECT * FROM nome");

while($row = mysqli_fetch_array($retorno)) {             
 echo $row["nome"];
    }  
  • With mysqli another error occurs, in the case of Mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given

1

Friend, alternatively you can use PDO, which is a more consistent way of using multiple databases.

The mysql_* functions have been deprecated from PHP 7.0 if you still use an older version of PHP and need to update PHP for some reason you will have problems with these functions.

You can use the code snippet below to connect to a mysql database.

try {
        $dsn = sprintf("mysql:host=%s;dbname=%s;charset=utf8", $host, $dbname);
        $connection = new \PDO($dsn, $user, $password);
        $connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);


} catch (\PDOException $exc) {
     echo $exc->getTraceAsString();
}

Below is an example search with PDO:

$statement = $connection->prepare("SELECT * FROM tabela WHERE id = :id");
        try {
            $statement->bindValue( ':id', $id, \PDO::PARAM_INT );
            $statement->execute();


        $resultado = $statement->fetch(\PDO::FETCH_OBJ);

        } catch (\PDOException $exc) {
            throw new \Exception('Erro ao executar ' . $exc->getMessage());
        }
  • It worked, I will update my way of using PHP and start using PDO, thank you very much for the help.

  • Good that it worked. In these links you can get more information on how to work with PDO. http://www.rafaelwendel.com/2011/12/tutorial-pdo-php-data-object/ http://rberaldo.com.br/pdo-mysql/

-1

Try editing your "mysql_connect" line for this.

mysql_connect('localhost', usuario_bd, senha_bd);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.