-4

I'm working on a project for a buddy of mine and we want to write our database calls in mysqli. I'm new to this and I've only used mysql commands which I know are out of date at this point. I keep getting Call to a member function query() on a non-object on line 30 which is my if ($mysqli->query($sql)) { command. Could anyone please point me in the right direction for this? I've tried looking it up in W3 schools. Here is my entire code:

// If the form is submitted, INSERT into table.
if (isset($_POST["submit"])) {

    // Define $username and $password.
    $username = $_POST['user_username'];
    $password = $_POST['user_password'];

    // Protect them from MySQL injection.
    $username = stripslashes($username);
    $password = stripslashes($password);
    $username = mysqli_real_escape_string($db, $username);
    $password = mysqli_real_escape_string($db, $password);
    $password = md5($password);

    // Run some queries.
        if ($_FILES["user_image"]["error"] > 0) {

            //Bad Output for form results red text
            echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
            echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";

        } else {

            move_uploaded_file($_FILES["user_image"]["tmp_name"],"uploads/" . $_FILES["user_image"]);
            $file="uploads/".$_FILES["user_image"];
            $image_title = addslashes($_REQUEST['user_image']);
            $sql="INSERT INTO users (user_fname, user_lname, user_image, user_phone, user_cell, user_email, user_username, user_password) VALUES ('$_POST[user_fname]', '$_POST[user_lname]', '$_POST[user_image]', '$_POST[user_phone]', '$_POST[user_cell]', '$_POST[user_email]', '$username', '$password')";
            if ($mysqli->query($sql)) {
                die('Error: ' . $mysqli->error);
            }

            //Good Output for form results green text   
            echo '
             <form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer">
                <div style="padding:10px;">
                    <h2 style="font-size: 28px;">Success!</h2>
                    <p style="font-size: 18px;">Your file has been successfully uploaded!</p>
                </div>     
            </form>';
        }
}

Thanks!

Spyder Tech
  • 67
  • 1
  • 2
  • 12
  • `$mysqli` is not defined anywhere in this code –  Jan 24 '16 at 21:05
  • try using $mysqli->real_query($query); – Adarsh Mohan Jan 24 '16 at 21:07
  • Please do not hash passwords using MD5. MD5 is fast and insecure for passwords. Please use the Password Hashing API. If you don't have PHP 5.5, there are compatibility scripts for PHP 5.3+ available. – Charlotte Dunois Jan 24 '16 at 21:08
  • 1
    you need to show us where/how you're connecting here. all answers below so far, are wrong. – Funk Forty Niner Jan 24 '16 at 21:09
  • 1
    @Fred-ii- Well, he does use escaping and pass `$db` as the mysqli instance, so they're not wrong. They are in a state where their answer is either wrong, right or both at the same time. – Charlotte Dunois Jan 24 '16 at 21:11
  • @Fred-ii- he uses *font* too, im guessing hes a 90's guy –  Jan 24 '16 at 21:12
  • @CharlotteDunois `$db` and `$mysqli`, who knows what they're *really* using as far as a connection variable goes. – Funk Forty Niner Jan 24 '16 at 21:13
  • @Dagon I love `` because, well it's a "font" and that term dates back farther than most of us were even born. – Funk Forty Niner Jan 24 '16 at 21:15
  • and here's your non-object `$_POST[user_image]` where you used `$_FILES["user_image"]` everywhere else. – Funk Forty Niner Jan 24 '16 at 21:19
  • @Spyder Tech - I've made a few edits to my answer since its initial post and you will need to reload it in order to see them. Go over it in its entirety. There isn't much else I can add to it, so you will need to iron out the rest of it yourself. – Funk Forty Niner Jan 24 '16 at 22:56
  • @Fred-ii- Thanks, I'll take a look. Since everyone seems to be asking here is where I make the db connect. It's in a file called db-connect.php that is called on in the main template. – Spyder Tech Jan 26 '16 at 04:20
  • `// Define the database credentials. define('DB_SERVER', 'localhost' ); define('DB_USERNAME', 'my db username' ); define('DB_PASSWORD', 'my db password'); define('DB_DATABASE', 'my database name' ); // Establish a connection. $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE); // If the connection fails, display an error. if (!$db) { die("Connection failed: " . mysqli_connect_error()); }` – Spyder Tech Jan 26 '16 at 04:20
  • @SpyderTech You're welcome. Since you're using `$db` then you need to change all instances of `$mysqli` to `$db`, as outlined in my answer. As I also said above here in comments, besides all that's been said, there isn't much else I can do to help. – Funk Forty Niner Jan 26 '16 at 12:05
  • If an answer solved your problem, consider accepting the answer. Here's how http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work then return here and do the same with the tick/checkmark till it turns green. This informs the community, that a solution was found. Otherwise, others may think the question is still open and may want to post (more) answers. *Welcome to Stack!* – Jay Blanchard Jan 29 '16 at 18:04

2 Answers2

3

Here's your non-object $_POST[user_image] in your VALUES, where you used $_FILES["user_image"] everywhere else but there's no input for it anywhere in what you posted for code. We're dealing with a file here and not an text input.

I.e.: <input type="file" name="user_image">

  • Only YOU know that.

Plus, you need to use the connection variable you're really using, if it's $db, or $mysqli and if you successfully connected to your database, or chose the right database and table.

  • Again, only YOU know that.

Then this:

$image_title = addslashes($_REQUEST['user_image']);

You should use $_FILES and not $_REQUEST, since this implies that you may be using a GET method in your unshown "other" form.

Reference:

References:

And use the error handling that fits your connection. Consult my Edit below.

Also make sure that folder you're wanting to upload to, has the right permissions to write to it.

Add error reporting to the top of your file(s) which will help find errors.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Then the rest of your code

Sidenote: Displaying errors should only be done in staging, and never production.

Also use var_dump();, echo and viewing your HTML source are additional tools that will help you during the debugging process.


Additional notes:

If you're wanting to upload that data as binary data in your table, then make sure that you're using the correct type.

Such as TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB.

Another "only YOU know that".

Reference:


As stated by Matt in comments:

And $file="uploads/".$_FILES["user_image"]; should be changed to $file="uploads/".$_FILES["user_image"]['name'];

Changing both instances of "uploads/" . $_FILES["user_image"] to "uploads/".$_FILES["user_image"]['name']

Consult the manual on move_uploaded_file():


Passwords.

I noticed you are using MD5 as a password hashing function. This function is no longer considered safe to use.

Use one of the following:

Other links:

Important sidenote about column length:

If and when you do decide to use password_hash() or crypt, it is important to note that if your present password column's length is anything lower than 60, it will need to be changed to that (or higher). The manual suggests a length of 255.

You will need to ALTER your column's length and start over with a new hash in order for it to take effect. Otherwise, MySQL will fail silently.


Edit:

Seeing another one of your questions:

I noticed PDO syntax $row = $stmt->fetch(PDO::FETCH_ASSOC); and where you are mixing with mysql_ functions $image = mysql_query....

This tells me that you may still be mixing MySQL APIs. If your connection is PDO, then you cannot intermix those different APIs. You must use the same one from connecting to query.

Consult the following on Stack:

PDO with mysql_ - invalid
PDO with mysqli_ - invalid
mysql_ with mysqli_ - invalid

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • This is not what the error is from, but you are correct about the `$_FILES` issue. – Matt Jan 24 '16 at 21:30
  • @Matt from what they posted for code, is the only deduction I've come up with. If the OP cares to show us their full code, I'll be glad to edit as per ;-) – Funk Forty Niner Jan 24 '16 at 21:31
  • That error arises when you're trying to use a function on a variable which is not an object e.g. If I were to do `$fghghd->query("A WORKING QUERY HERE");` the same error would occur. The error will appear the same. – Matt Jan 24 '16 at 21:32
  • @Matt I just made another edit in regards to `$image_title = addslashes($_REQUEST['user_image']);` they're using `$_REQUEST` for files which should be `$_FILES`. – Funk Forty Niner Jan 24 '16 at 21:33
  • Yeah, heaps of errors in the code, not just the one he is getting :/ – Matt Jan 24 '16 at 21:36
  • @Matt I think I've given him enough to further debug his code. There isn't much else I can here really, not until I know exactly which *animal* I'm dealing with, other than the one I see before me ;-) such as what they posted for code. Code is like an old VCR; too many (moving) parts where too many things can go wrong. – Funk Forty Niner Jan 24 '16 at 21:39
  • Pretty sure `move_uploaded_file($_FILES["user_image"]["tmp_name"],"uploads/" . $_FILES["user_image"]);` should be `move_uploaded_file($_FILES["user_image"]["tmp_name"],"uploads/" . $_FILES["user_image"]['name']);` – Matt Jan 24 '16 at 21:41
  • And `$file="uploads/".$_FILES["user_image"];` to `$file="uploads/".$_FILES["user_image"]['name'];` – Matt Jan 24 '16 at 21:41
  • @Matt ah thanks Matt. good catch. I'll add that (kudos to you). give me a sec. (which I did include a link for file uploads) but will clarify it. – Funk Forty Niner Jan 24 '16 at 21:45
0

Your code should either be all object-oriented or all functional. You can either do it the object-oriented way:

$mysqli = new mysqli('dbhost', 'username', 'password', 'dbname');
// ...
$username = $mysqli->escape_string($username);
$password = $mysqli->escape_string($password);
// ...
$mysqli->query($sql);

Or the functional way:

$mysqli = mysqli_connect('dbhost', 'username', 'password', 'dbname');
// ...
$username = mysqli_escape_string($mysqli, $username);
$password = mysqli_escape_string($mysqli, $password);
// ...
mysqli_query($mysqli, $sql);

Please note that the functional syntax has now been deprecated as of PHP 7 (I think, can't find the exact version). See the documentation for mysqli::_construct for proper usage.

As well, mysqli_escape_string()/$mysqli->escape_string() are now aliases for
$mysqli->real_escape_string(), so it's no longer necessary to use the longer form as it was with the old mysql module.

Finally, ensure that you've actually instantiated the $mysqli variable in your code. There's no reason you should get that particular error, even if the connection failed.

Mikkel
  • 1,192
  • 9
  • 22
  • This is more of question/comment to the OP, wouldn't you agree? – Funk Forty Niner Jan 24 '16 at 21:48
  • You may be correct, but my response answers the question based on the information provided. While your response was lengthy and well-sourced, it only tangentially addressed the actual question. The other answers attempt to respond and are flat-out wrong. I thought it better to get some accurate information out there. – Mikkel Jan 24 '16 at 21:52
  • Not that your information is incorrect, and I would have raised the same points if you hadn't. But none of it would actually solve the immediate problem, which is a DB connection not being properly instantiated. – Mikkel Jan 24 '16 at 21:53
  • I've updated my response with more detail, since the mix of OOP and functional code is definitely an issue. – Mikkel Jan 24 '16 at 22:08