smarttechy
smarttechy

Reputation: 902

Mysql syntax error in select statement

I have a table main_tag with structure as

1   id int(100) 
2   name varchar(100)   
3   description varchar(1000)
4   added_on timestamp  

and have function of php that is as follows

function all_data_of_main_tag_table(){

        include_once 'db.php';
        $conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
        $json = array();
        $nameQuery ='SELECT * FROM `main_tag` WHERE 1';
        echo '<br>'.$nameQuery.'<br>';
        $rsnameQuery = $conn->query($nameQuery);      
        if($rsnameQuery === false){
            echo 'hi'.'<br>';
            trigger_error('Wrong SQL: '.$nameQuery.' Error: '.$conn->error, E_USER_ERROR);
        }
        else{
           $rows_returned = $rsnameQuery->num_rows;
        }
        while($row = $rsnameQuery->fetch_assoc()){
            $json =$row;
        }
        $conn->close();
        return $json;
    }

On running this function it is giving error:

{
  "description": null,
  "name": null,
  "id": null
}
MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1

Upvotes: 0

Views: 1373

Answers (2)

smarttechy
smarttechy

Reputation: 902

my bad my query was ok the error was of other query. however

while ($row = mysqli_fetch_assoc($rsnameQuery)) {
   $json[] = $row;
}

this was to be written instead of

while($row = $rsnameQuery->fetch_assoc()){
     $json =$row;
}

This was not returning the data.

Upvotes: 0

smartnet
smartnet

Reputation: 87

In your query, you didn't specify where to look

Where 1

It does not specify any column

// it should be something like this 
Where id = 1

So your query be like this

$nameQuery ='SELECT * FROM `main_tag` WHERE id = 1

Upvotes: 2

Related Questions