PHP-Mysql Error Return: Call to Undefined Function

Asked

Viewed 926 times

-2

Good evening, I’m trying to make a connection to the database. And mysql is returning the following error.:

Call to Undefined Function mysql_connect_db()

Follows my code:

<?PHP

//

$servidor ='localhost';
$usuario ='root';
$senha ='';
$banco= 'agenda';

// executando a conexão com o servidor

$link = mysqli_connect($servidor,$usuario,$senha);

// selecionando o banco de dados

$select = mysql_connect_db($banco);

// Aqui insere os novos usuários

$nome= $_POST["nome"];
$telefone= $_POST["telefone"];
$email= $_POST["email"];

$sql= mysql_query("INSERT INTO CONTATO(NOME,TELEFONE,EMAIL) VALUES ('$nome','$telefone','$email')");

// executando todas as chamadas do sql e armazenando os dados.

$result =  mysql_query($sql);

echo "CADASTRO REALIZADO COM SUCESSO !";


?>
  • Colleague, facilitate our help. your script is small, put the same here. In addition to trying to help we have to keep entering external link? Complicates...

3 answers

5

The first problem (which is what caused the error) is that you have invented a function.

The function mysql_connect_db does not exist. Probably you confused with mysql_select_db.

Basic problems like this are solved by reading at least the basics of the documentation.

The problem you have right after, as per explained by Simon Italo, is the mixture of two different libraries. As he demonstrated in his answer, mysqli do not need a separate function to select DB default. This is done in connection:

$link = mysqli_connect( $servidor, $usuario, $senha, $banco );
                                                     ^^^^^^

Always remember that you can use the following syntax if you prefer to omit the database when connecting, and/or need to select data from different databases (after all, the DB default is used only in case of omission in query):

SELECT id, nome FROM banco1.cadastro ORDER BY nome
                     ^^^^^^

Then you are committing one of the most barbaric security crimesTM, which is to use the data without any kind of sanitization:

$nome = $_POST["nome"];
$telefone = $_POST["telefone"];
$email = $_POST["email"];

As a consequence, sooner or later you will get your DB deleted or corrupted, and having your system and all kind of DB data improperly used.

The simplest solution is to sanitize the data, and both in the case of mysql how much of mysqli, there are appropriate functions for this. In the case of mysqli:

$nome = mysqli_real_escape_string ( $link, $_POST["nome"] );
$telefone = mysqli_real_escape_string ( $link, $_POST["telefone"] );
$email = mysqli_real_escape_string ( $link, $_POST["email"] );

This might help you understand better:

How to prevent SQL code injection into my PHP code?

In fact, for the sake of performance (and doing the right thing) I would have to do more and see if there really are the data posted, but in terms of safety, what matters is the sanitization above (and hit the correct set of characters used by the script).

Better than that would be using Prepared statements, that although they are neither more nor less secure than the above correction, has a much higher performance in the case of darlings with several lines, in addition to better organizing the code.

How to use Prepared statements with external variables in Mysqli

Also, good to remember that using mysqli in procedural mode, the $linkis always the first parameter:

$sql = mysqli_query( $link, 'INSERT ...

Which leads to another misconception in your code, because you soon try to do the "query of query":

$result = mysql_query( $link, $sql );

This series of things gives an impression of "kick-oriented programming". Do not take this as an offense, but as a constructive criticism to improve your attention with the basics, otherwise you run the risk of living copy & Paste as a lot of people who think you’re a programmer but you’re not, and what we want is for you to really learn and evolve.


So follow the adjusted code:

<?php
    $servidor ='localhost';
    $usuario ='root';
    $senha ='';
    $banco= 'agenda';

    // estabelecendo a conexão com o servidor

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

    // Aqui insere os novos usuários

    $nome = mysqli_real_escape_string ( $link, $_POST['nome'] );
    $telefone = mysqli_real_escape_string ( $link, $_POST['telefone'] );
    $email = mysqli_real_escape_string ( $link, $_POST['email'] );

    // quebrei em duas linhas só pra facilitar a leitura

    $sql = "INSERT INTO CONTATO( nome, telefone, email)";
    $sql .= " VALUES ( '$nome', '$telefone', '$email' )";

    // executando todas as chamadas do sql e armazenando os dados.

    $result = mysqli_query( $link, $sql );

    if( $result ) {
       echo 'CADASTRO REALIZADO COM SUCESSO!';
    } else {
       echo 'CADASTRO NAO REALIZADO!';
    }
?>

Obviously you can only test under real conditions, so if you have any problems that you have not noticed, just leave a comment that we review.

1

If you are using mysqli_ to connect to the database, forget any method that starts with the prefix mysql_, because they are different methods to deal with BD.

Try to do it this way:

<?php
    /* configuração da conexão */
    $conexao = mysqli_connect("localhost", "root", "senha", "nome_do_bd");

    /* checar se a conexão foi estabelecida com sucesso */
    if (mysqli_connect_errno()) {
        exit();
    }

    /* inserindo dados em tabela */
    mysqli_query( $conexao, "INSERT INTO CONTATO(nome, telefone, email) VALUES ('Santiago','558899338844','[email protected]')");
?>

-2

Hello a way to make a successful connection could be done using PDO. http://php.net/manual/en/intro.pdo.php

<?php
    class PDOUtil 
    {
        private static $conexao = null;
        public static function getStance() 
        {
            try 
            {
                if (self::$conexao == null) 
                {
                    self::$conexao = new PDO ('mysql:host=127.0.0.1;dbname=BASE_DE_DADOS','USUARIO','SENHA');
                }
            } catch (PDOException $excecao) 
            {
                if ($excecao->getCode () == "2002") 
                {
                    echo 'Oi infelizmente seu Host nao foi encontrado, verifique isso com o web-master.';
                }
                if ($excecao->getCode () == "1049") 
                {
                    echo 'Oi infelizmente seu banco nao foi encontrado, verifique isso com o web-master.';
                }
                if ($excecao->getCode () == "1044") 
                {
                    echo 'Oi infelizmente seu usuario nao foi encontrado, verifique isso com o web-master.';
                }
                if ($excecao->getCode () == "1045") 
                {
                    echo 'Oi infelizmente sua senha nao foi encontrada, verifique isso com o web-master.';
                }
            }
            return self::$conexao;
        }
    }
  • Depreciated was mysql -> http://php.net/manual/en/migration55.deprecated.php

  • 1

    really mistaken, I left only the connection PDO @João

Browser other questions tagged

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