Error fetching from DB, but not sure what's wrong

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 1026 Views - Last Post: 09 February 2013 - 05:22 AM Rate Topic: -----

#1 Sapper187  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 08-February 13

Error fetching from DB, but not sure what's wrong

Posted 08 February 2013 - 02:01 AM

I'm getting an error trying to fetch data from my database, but I'm not sure where. There error comes from the 2nd line, I think. As the code is, I get a blank page, and if I remove the 2nd or die it displays the page but won't echo anything from the DB. It's connected to the DB no problem. I've tried both mysql_fetch_array and mysql_fetch_assoc.

If it matters, PHP version is 5.2 and MYSQL is 5.5.23

Any help, or at least a point in the right direction, would be greatly appreciated.

$stats_get = mysql_query("SELECT * FROM stats WHERE id ='.#_SESSION[uid].'") or die(mysql_error());
$stats = mysql_fetch_array($stats_get) or die(mysql_error());


Is This A Good Question/Topic? 0
  • +

Replies To: Error fetching from DB, but not sure what's wrong

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3569
  • View blog
  • Posts: 10,402
  • Joined: 08-June 10

Re: Error fetching from DB, but not sure what's wrong

Posted 08 February 2013 - 02:33 AM

general advice: the old mysql_* extension is outdated and deprecated. use MySQLi or PDO instead.

regarding the code, there are some errors:
- itís $_SESSION, not #_SESSION
- the dots (that PHP uses as concatenation operators) are put literally into your query. I doubt that your DB data have dots appended/prepended.
- depending what datatype id (in the DB) is, you may have to remove the quotes (INT values ainít quoted in SQL).
Was This Post Helpful? 0
  • +
  • -

#3 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3730
  • View blog
  • Posts: 6,017
  • Joined: 08-June 10

Re: Error fetching from DB, but not sure what's wrong

Posted 08 February 2013 - 02:00 PM

Like Dormilich says, your concat operators are being used incorrectly. Consider this:
// Assuming that...
$_SESSION["value"] = "Hello!";

// This prints: 
// - Value: '.$_SESSION[value].'
echo "Value: '.$_SESSION[value].'";

// But all of these print: 
// - Value: 'Hello!'
echo "Value: '" . $_SESSION["value"] . "'";
echo "Value: '$_SESSION[value]'";
echo "Value: '{$_SESSION["value"]}'";


The last three are basically equivalent. One thing to pay special attention to is the second of the last three lines. In that line the "value" key is not quoted. This is ONLY allowed for array element keys when it's done directly inside a string. String keys should always be quoted outside of strings. (There they are just normal strings, after all.)

Also, the final line there is a special case. In some cases it's impossible to inject a variable directly into a string, when the surrounding string would mess up the variable name. For those cases, you can surround the variable in curly-brackets to separate it from it's surroundings.
$var = "efg";

// Invalid!
echo "Abcd$varhijklmn";

// Valid
echo "Abcd{$var}hijklmn";


This also allows you to do things like call object methods inside a string. I much prefer to do this in all cases, just to make it more obvious that a variable was injected, but that's just personal preference.
Was This Post Helpful? 0
  • +
  • -

#4 Sapper187  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 08-February 13

Re: Error fetching from DB, but not sure what's wrong

Posted 08 February 2013 - 02:55 PM

Thank you for the replies, definitely clear some stuff up, but also brought about new problems.

What I'm trying to do is use query to set variables from my DB so that I can use them in the correct place on my UI. I'm doing this inside of an include, not on the pages themselves.

First, instead of setting the variable to the entire table with SELECT * FROM whatever, should I set each row in the table to it's own? In the example I used above, I was trying to echo it by doing $stats[attack] for example. I'm trying to modify the example they have on php.net, but with my learn as I go knowledge, I'm getting nothing but errors.

Second, I was trying to use the code below for what I'm trying to do, but it's not right. Problem is, I have no idea why it isn't right. Everything I have is from a almost 3 year old tutorial, so I'm going to be starting over fresh since I know all the DB related code is out of date, but before I did I wanted to use what I have to figure out how to make it do what I want.

$results = $db->query("SELECT * FROM stats WHERE id = $_SESSION[uid]");


The error I'm getting is "Fatal error: Call to a member function query() on a non-object"
Was This Post Helpful? 0
  • +
  • -

#5 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3730
  • View blog
  • Posts: 6,017
  • Joined: 08-June 10

Re: Error fetching from DB, but not sure what's wrong

Posted 08 February 2013 - 03:11 PM

View PostSapper187, on 08 February 2013 - 09:55 PM, said:

The error I'm getting is "Fatal error: Call to a member function query() on a non-object"

This error is happening because your $db variable is not an object, and thus does not have a query() function. What is $db in that line, exactly?

It seems you are trying to use PDO or MySQLi, but that you haven't properly initialized the connection. Could you show us the code where you connect to the database? That might explain why this is happening.

View PostSapper187, on 08 February 2013 - 09:55 PM, said:

First, instead of setting the variable to the entire table with SELECT * FROM whatever, should I set each row in the table to it's own? In the example I used above, I was trying to echo it by doing $stats[attack] for example. I'm trying to modify the example they have on php.net, but with my learn as I go knowledge, I'm getting nothing but errors.

I think there may be some misunderstanding going on here. Either me not understanding you, or you not understanding how those functions work.

Either way, this is how MySQL querying works: When you do mysql_query with a SELECT command, the function returns a pointer to a result set. This result set lets contains all the data your SELECT command returns. Using functions like mysql_fetch_array and mysql_fetch_assoc you can retrieve rows from the result set, one row at a time. Consider:
$sql = "SELECT myField FROM myTable";
$result = mysql_query($sql) or trigger_error(mysql_error(), E_USER_ERROR);

$row1 = mysql_fetch_array($result);
$row2 = mysql_fetch_array($result);
$row3 = mysql_fetch_array($result);
// etc...


Now, those three $rowX variables will contain the "myField" element from the first three rows that query returns.

Most of the time, though, you'll want to do this in a loop instead.
$sql = "SELECT myField FROM myTable";
$result = mysql_query($sql) or trigger_error(mysql_error(), E_USER_ERROR);
while ($row = mysql_fetch_array($result)) {
    // Do stuff here for each of the rows.
}


Hope that makes things clearer.
Was This Post Helpful? 0
  • +
  • -

#6 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3721
  • View blog
  • Posts: 12,957
  • Joined: 12-December 12

Re: Error fetching from DB, but not sure what's wrong

Posted 08 February 2013 - 03:15 PM

I always use curly brackets with array elements in expressions like this:

$results = $db->query("SELECT * FROM stats WHERE id = $_SESSION[uid]");
// so..
$results = $db->query("SELECT * FROM stats WHERE id = {$_SESSION[uid]}");

I don't trust it to work otherwise :)

Added: As per Atlis reminder (below):

$results = $db->query("SELECT * FROM stats WHERE id = {$_SESSION['uid']}");

This post has been edited by andrewsw: 08 February 2013 - 03:45 PM

Was This Post Helpful? 0
  • +
  • -

#7 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3730
  • View blog
  • Posts: 6,017
  • Joined: 08-June 10

Re: Error fetching from DB, but not sure what's wrong

Posted 08 February 2013 - 03:35 PM

andrewsw, keep in mind, though, that if you do that you should quote the element key. When in curly brackets, the variable reference acts just as if it's normal PHP code and the exception that allows unquoted keys to be used on array elements inside strings is not in effect. You'd get the "Undefined constant ... assumed 'string'" notice on the code you posted.
Was This Post Helpful? 1
  • +
  • -

#8 Sapper187  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 08-February 13

Re: Error fetching from DB, but not sure what's wrong

Posted 08 February 2013 - 03:38 PM

$db = new mysqli("localhost", "sapper_sapper", "*******", "sapper_game");
 if ($db->connect_errno > 0 ){
    die('Unable to connect to database [' . $db->connect_error . ']'); 
}


That is what I'm using to connect, except with the actual password in there of course.

The original code I had was all done in mysql, but as I rewrite stuff I'm changing it to mysqli. Unfortunately, my testing phase of this is done, I got logged out and since my login page is half mysql and half mysqli, I can't log back in. So I now get to do a bunch of reading, then some rewriting to hopefully get past my current problems so I can find some new ones.
Was This Post Helpful? 0
  • +
  • -

#9 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3730
  • View blog
  • Posts: 6,017
  • Joined: 08-June 10

Re: Error fetching from DB, but not sure what's wrong

Posted 08 February 2013 - 03:47 PM

OK, so you seem to be initializing the connection correctly. Then my next question would be: Where is the line of code causing the error? Is it inside a function, perhaps? If so, then it's likely you are having scoping issues.

Unlike in many languages (Javascript comes to mind), PHP's global variables are not automatically accessible inside functions. So you'd get an error if you do this:
<?php
$db = new mysqli(...);

function doStuff() {
    $result = $db->query("...");
}



You'd either have to import, or pass, the $db variable into the function to use it.
$db = new mysqli(...);

function doStuffImported() {
    // This imports the global $db variable into
    // the scope of this function, making it usable.
    global $db;

    $result = $db->query("...");
}

function doStuffPassed($db) {
    // This code is using the $db parameter
    // to execute the query. Whatever code calls
    // the function is meant to pass it he $db global.

    $result = $db->query("...");
}


For the second function, the calling code would be responsible for passing the $db into the function.
doStuffPassed($db);


Of course, this is a little more inconvenient, so for a simple use case like this, you may be better of with the global version. In other cases, though, such as complex OOP setups, it can be beneficial to use the parameter version.

Another popular option is to use a Singleton to handle the connection, but I'll not go deep into that now. Just something you may want to look into later :)
Was This Post Helpful? 0
  • +
  • -

#10 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3721
  • View blog
  • Posts: 12,957
  • Joined: 12-December 12

Re: Error fetching from DB, but not sure what's wrong

Posted 08 February 2013 - 03:53 PM

BTW (a small point) the docs suggest the following approach, rather than using > 0

<?php
$mysqli = @new mysqli('localhost', 'fake_user', 'my_password', 'my_db');

if ($mysqli->connect_errno) {
    die('Connect Error: ' . $mysqli->connect_errno);
}
?>

but, as I say it's a small point.
Was This Post Helpful? 0
  • +
  • -

#11 Sapper187  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 08-February 13

Re: Error fetching from DB, but not sure what's wrong

Posted 08 February 2013 - 03:56 PM

$results = $db->query("SELECT * FROM stats WHERE id = $_SESSION[uid]");


That was the line getting the error. The above code is in a file safe.php, the connect was a function called connect and in a file functions.php and in my header.php file is this:

<?php
include("functions.php");
connect();
include("safe.php");
?>

Was This Post Helpful? 0
  • +
  • -

#12 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3730
  • View blog
  • Posts: 6,017
  • Joined: 08-June 10

Re: Error fetching from DB, but not sure what's wrong

Posted 08 February 2013 - 04:32 PM

Ok, so how does the connect function get the $db object to the rest of the code? In your header code, you don't assign the return value of the connect() call to anything, so returning it wouldn't have any effect. Are you setting a global variable?

You may want to read up on Variable Scope in the manual. I explained the global issue in my last post, but it pays of to know everything about how a language you are using handles scopes. That seems to be the root of this particular issue you are having.
Was This Post Helpful? 0
  • +
  • -

#13 Sapper187  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 08-February 13

Re: Error fetching from DB, but not sure what's wrong

Posted 08 February 2013 - 04:46 PM

I had kinda figured that was where my problem was. Thank you for the link, I'll add that to my list of things I need to read before I start coding again. I'm planning on having everything I have done now re-done, but correctly, by the end of the weekend.

I do have one more quick, somewhat unrelated question. Is there a difference between using echo for html code vs. closing php tags? As in this:

echo "<div id=/"header/">


Is one better than the other, or is it just personal preference?
Was This Post Helpful? 0
  • +
  • -

#14 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3730
  • View blog
  • Posts: 6,017
  • Joined: 08-June 10

Re: Error fetching from DB, but not sure what's wrong

Posted 08 February 2013 - 05:00 PM

I'd say it would depend on the situation. As far as performance goes, the difference is negligible, and it doesn't really matter as far as behavior goes. If you are echoing large sections of HTML, then it's probably better to close the PHP block, or use the heredoc syntax.

However, the ideal way is to not directly echo HTML at all. In the ideal project your PHP and HTML will be completely separated. Mixing HTML and PHP (and typically SQL, CSS and Javascript as well) is going to make the code less easily readable, and thus hard to both write and (especially) to maintain. You should add Code Separation to your reading list as well. It'll make your coding easier in the long run.
Was This Post Helpful? 0
  • +
  • -

#15 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3569
  • View blog
  • Posts: 10,402
  • Joined: 08-June 10

Re: Error fetching from DB, but not sure what's wrong

Posted 08 February 2013 - 05:34 PM

View Postandrewsw, on 08 February 2013 - 11:53 PM, said:

BTW (a small point) the docs suggest the following approach, rather than using > 0

<?php
$mysqli = @new mysqli('localhost', 'fake_user', 'my_password', 'my_db');

if ($mysqli->connect_errno) {
    die('Connect Error: ' . $mysqli->connect_errno);
}
?>

the @ is not necessary here (seems like the Manual needs to be updated there), the new mysqli() expression always returns a MySQLi object, even if the connection fails. (http://www.php.net/manual/en/mysqli.construct.php, second Note)
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2