DaveTheMinion
DaveTheMinion

Reputation: 664

Cannot print data from MySQL Query with PHP

I am writing a PHP script that is supposed to interact with a MySQL database. On my local testing server, the code echos out what it is supposed to just fine, but in the live environment, I get an error saying Fatal error: Call to a member function fetch_array() on a non-object in [file path removed for security] on line 42. Here is my code from around line 42.

$query = "SELECT " . $data . " FROM mySchemaTable WHERE incrementId = " . $something;
$result = mysqli_query($conn,$query);
$row = $result->fetch_array(MYSQL_BOTH); // This line is 42.
echo $row['0'];
break;

Upvotes: 0

Views: 112

Answers (2)

DaveTheMinion
DaveTheMinion

Reputation: 664

The problem was solved without my intervention. It turns out that my code was fine as it was, but something was wrong with my host's MySQL. It's fixed now, and everything is working again.

Upvotes: 0

BrotherBallan
BrotherBallan

Reputation: 369

I noticed a few problems with your code:

Firstly, you're mixing OOP and Procedural programming with MySQLi commands. Although PHP allows this, you'll want to make that uniform throughout. If you're using $conn = mysqli_connect(parameters here); you'll want to focus on procedural (change $result->fetch_array(MYSQLI_BOTH) to mysqli_fetch_array($conn, MYSQLI_BOTH); for instance). (I would assume you're doing this, so do this ^ change)

Else, if it's $conn = new mysqli(parameters); then you'll want to make it OOP based; instead of mysqli_query($sql); you'd use $conn->query($sql);, assuming $sql contains the query you want to run.

Secondly, echo $row['0']; should be echo $row[0]; unless the row you're returning is actually named 0, in which case disregard this.

Thirdly, and as a side note, it's a bad idea to directly insert variables into SQL queries, especially if they're user generated. You should look into sanitizing input or prepared statements to protect against SQL injection attacks.

Sanitizing Input Reference: What's the best method for sanitizing user input with PHP?

Prepared Statements: http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

Upvotes: 1

Related Questions