Functions PHP + MySQLi

3

I created a function in php for cruid in the database but the function Read is in trouble and I can not understand why, it follows the code:

function DBRead($table,  $params = null, $fields = "*"){
    $table  = DB_PREFIX . '_' . $table;
    $params = ($params) ? " {$params}" : null;

    $query  = "SELECT {$fields} FROM {$table}{$params}";
    $result = DBExecute($query);

    if(!mysqli_num_rows($result))
        return $query;
    else{
        while ($rs = mysqli_fetch_assoc($result)){
            $data[] =$rs;
        }
        return $data;
    }
}

DB_PREFIX is a constant just to help in selecting the table in the database, the line I'm trying to execute is this:

    $chekDouble = DBRead('postagem', "WHERE titulo = '" . $form['titulo'] . "'" );

I debugged with var_dump() and the output is this:

'SELECT * FROM mg_postagem WHERE titulo = 'titulo''

This SELECT checks if the title that the user is entering is already titled some other post in the database, but it always returns true obs: the database is empty ...

if( $chekDouble )
            echo 'Titulo de Post Já cadastrado!';
        else{

            if(DBCreate('postagem',$form))

The title comes from a form and I use the $_POST method, for the insert function are passed by parameters name of the table, and a array of fields and values. this is the array.

$form['titulo'] = strip_tags( trim( $_POST['titulo'] ) );
$form['bloco1'] = strip_tags( trim( $_POST['bloco1'] ) );
$form['bloco2'] = trim( $_POST['bloco2'] );
$form['datapost']= date("Y-m-d");

obs: function works when I use it this way:

$teste = DBRead('postagem', "teste" );

who runs all query is:

function DBExecute($query){
    $link   = DBConnect();
    $result = @mysqli_query($link,$query) or die(mysqli_error($link));

    DBClose($link);
    return $result;
}
    
asked by anonymous 12.07.2015 / 09:12

1 answer

4

The problem seems to be that your query fails because of a syntax error because it has if which is always evaluated as true.

In the assembly of your query make sure to space the clauses

$query  = "SELECT {$fields} FROM {$table}{$params}";
//Adicione um espaço aqui --------------^

if(!mysqli_num_rows($result))
    return $query;// mude por return false;

Instead of returning a string with some text (sql query) that will be evaluated as true in if, return only false , one idea is to create another function that logs queries generated by dbRead() before return false .

With this change, if should work as expected:

$chekDouble = DBRead('postagem', "WHERE titulo = '" . $form['titulo'] . "'" );

if( $chekDouble )
   echo 'Titulo de Post Já cadastrado!';
else{
  if(DBCreate('postagem',$form))
    
12.07.2015 / 17:33