1

This is driving me crazy...

I'm simply trying to pull an INT value from my database (MySQL), but for some reason i get this error:

Notice: Array to string conversion in C:\xampp\htdocs\ajax\myjobs.php on line 33

this points my html where I try to echo $deptnum:
<h1><?php echo $deptnum; ?></h1>

Here's some of my PHP code:

<?php

  require ("config.php");
  include ("menu.php"); 

  /* config.php CONTAINS CODE TO CONNECT TO DATABASE AND IT WORKS FINE */

  /* Check if a value for user_name exists */
  if (isset($_SESSION['user_name'])) {

      $the_user_name = $_SESSION['user_name'];
       /* FYI, THIS DOES PULL THE CORRECT USERNAME, IN THIS CASE: "ussatjodo" */

      /* pull value from database */
      $result = $db->prepare("SELECT `dept` from `users` WHERE `username` = :uname");
      $result->execute(array(':uname' => $the_user_name));
      $deptnum=$result->fetch();


  } else {  
    $the_user_name = '';
  }

?>

<h1><?php echo $deptnum; ?></h1>

And here is the table "users"

enter image description here

TO SUM IT UP:

  • $_SESSION['user_name'] correctly pulls a username (example: 'ussatjodo');
  • All I'm trying to do is get the correct value for column 'dept' which in the case of username "ussatjodo", the 'dept' would be 1
  • Currently the error is telling me there is an error that I'm trying to convert an array to string.
1
  • Just because your result only contains one field doesn't mean that fetch() will not return an array. Commented Mar 10, 2014 at 21:04

2 Answers 2

4

fetch() returns an array indexed by the table column names. Try:

echo $deptnum['dept'];

PHP >= 5.4.0:

$deptnum = $result->fetch()['dept'];
Sign up to request clarification or add additional context in comments.

2 Comments

You would use a prepared statement and bind_result().
Edited with another option.
2

Comment. Not relevant to the question.

From what it looks like, you are storing passwords as plain text.

Rule of thumb, NEVER STORE PLAIN TEXT PASSWORDS

Always store encrypted passwords. Use default encryption techniques ie http://www.php.net/manual/en/function.password-hash.php , available in PHP > 5.5

If you are using PHP < 5.5, https://github.com/ircmaxell/password_compat provides a compatibility library for using password_hash

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.