views:

529

answers:

3

Hi, I am trying to get my head around mysql. Can someone tell my why this mysql query is not working? I am getting the following error:

Warning: mysqli_error() expects exactly 1 parameter, 0 given in /home/freebet2/public_html/test.php on line 11

test.php

<?php
        require_once($_SERVER['DOCUMENT_ROOT'].'/includes/db.php');
        $conn = db_connect();
        $result = $conn->query("ALTER TABLE users ADD COLUMN refer_old INT(10) AFTER refer_id");

              if(!$result){
                 echo "Error with MySQL Query: ".mysqli_error();
             }
        ?>

db.php

 <?php

    function db_connect() {
       $result = new mysqli('localhost', 'user', 'password', 'db');
       if (!$result) {
         throw new Exception('Could not connect to database server');
       } else {
         return $result;
       }
    }

    ?>

If I change the alter string to something like : $result = $conn->query("SELECT * FROM users refer_id"); I get no error for some reason.

A: 

Use mysqli_error($result) as mysqli_error expects the connection to be passed as a parameter.

waiwai933
Yep I replaced my code to use mysqli_error, which has helped.
Mike
+1  A: 

You are mixing the object-oriented and the procedural styles of the mysqli API :

You are using object-oriented :

$result = new mysqli('localhost', 'user', 'password', 'db');

And, then, procedural :

echo "Error with MySQL Query: ".mysqli_error();


You should use either OO, or procedural -- but not both ; and if you choose procedural, the functions expect the link identifier passed as a parameter.

For instance, mysqli_error should be called either using the object-oriented API :

$link = new mysqli(...);
echo $link->error();

Or the procedural API :

$link = mysqli_connect(...);
echo mysqli_error($link);


(Of course, it will not change the fact that you are having an error in your SQL query, but it'll allow you to get the error message, which should help finding the cause of that error)

Pascal MARTIN
Hey thanks for your help, yeh I've been picking code out from different PHP books and have missed the two up.
Mike
+1  A: 

As far as the sql error is concerned, does 'user' have permissions to alter the table?

jeroen
As a matter of fact, no ALTER was not a priviledge set for user. I have enabled this and the query does create the table but error message of mysqli_error() expects parameter 1 to be mysqli, boolean still appears
Mike
And the column you try to add does not exist already?
jeroen
Lol, yeh the same error appeared and I assumed the query did not execute but I have just checked the table and it did in fact create it , I just didn't set the 'if' statements up correctly either. Thanks for solving the issue, i've been scratching my head for the past 4 hours!
Mike
You're welcome!
jeroen