0

I have not made the change from MySQL_ to PDO until today. Needless to say, the migration is more than a simple headache. So, I need a bit of help. I tried all the search terms I could before registering and asking this question.

My Problem

  • User types a numeric code into the search box, translates it to .php?code=term
  • Script selects all columns from the database where the code is the
    code term searched for.
  • PHP will Echo the results

My Code

if (isset($_GET["code"])) {
        //IF USER SEARCHES FOR CODE, RUN THIS. ELSE SKIP.
        $crimecode = $_GET["code"];

        $crcode = $link->prepare("SELECT * FROM crimecodes WHERE code = :code");
        $crcode->bindParam(':code', $crimecode);
        $crcode->execute();

        $coderesult = $crcode->fetchAll();


        echo "<h4>CODE:</h4>";
        echo $crimecode;
        echo "<br /><h4>DEFINITION:</h4>";
        echo $coderesult;

        die();      

    }

Before, it was simple. All I had to do was:

$qcode = mysql_query("SELECT * FROM crimecodes WHERE code = $crimecode");
$fcode = mysql_fetch_assoc($qcode);

echo $fcode['definition'];

But, the ever evolving world has decided to fix something that wasn't broken so now the whole prior code is pointless and you gotta learn something new. Any help is appreciated to get this to work.

Right now, the above PDO code returns definition: ARRAY.

Like literally, the $coderesult prints Array.

Kappa
  • 987
  • 1
  • 14
  • 30
  • `PDO` and `Mysqli` are two different drives. It looks like you are using `PDO`. – chris85 Sep 03 '15 at 21:11
  • Before it was simple, but you had a nice SQL Injection vulnerability right there (assuming you weren't castting `$code` as integer) ;D – Loïc Sep 03 '15 at 21:13

1 Answers1

0

The fetchAll() option returns an array containing all of the result set rows (http://php.net/manual/pt_BR/pdostatement.fetchall.php).

$coderesult prints Array because it's actually an array. If you do var_dump($coderesult) you'll see it.

I suppose that you are trying to get one row only. If that's the case, add this line after $coderesult = $crcode->fetchAll();:

$coderesult = $coderesult[0];

Then you can

echo $coderesult['definition'];

If you're trying to get more than one row, you need to use foreach to loop through the array.


I suggest you read the php manual for PDO Class or mysqli, wherever you prefer. There's a lot more options than mysql_.

Also, I think it's worth to mention that your previous code

$qcode = mysql_query("SELECT * FROM crimecodes WHERE code = $crimecode");
$fcode = mysql_fetch_assoc($qcode);

echo $fcode['definition'];

it's vulnerable to SQL Injection.

Community
  • 1
  • 1
Henrique Arthur
  • 608
  • 6
  • 16