-2
require("inc/connection.php");
if ($link->connect_error)
    die('Connect Error: '.$link->connect_errno.': '.$link->connect_error);
$insertedcode = $_POST['code'];
$results = $link->query("SELECT code FROM code WHERE code = :code");
$query_params = array( 
    ':code' => $_POST['code']
);

$stmt = $link->prepare($results);
$result = $stmt->execute($query_params);
$row = $stmt->fetch();
if($row) {
    $number = mt_rand(0,3999);
    echo $number;
}

This is what I have I think I have the random number part down. But for some reason it gives me this error:

Fatal error: Call to a member function execute() on a non-object in C:\wamp\www\RoLuck\dashboard.php on line 21

It wont execute and Im not sure why.

TGrif
  • 5,725
  • 9
  • 31
  • 52

2 Answers2

0

You're doing it in wrong order on the code that uses mysqli, right? If you query without actual params assigned to code, it's the reason. Prepare the query before querying, not after.

 require("inc/connection.php");
    if ($link->connect_error)
        die('Connect Error: '.$link->connect_errno.': '.$link->connect_error);
    $insertedcode = $_POST['code'];
    //$results = $link->query("SELECT code FROM code WHERE code = :code");
    $query_string = "SELECT code FROM code WHERE code = :code";
    $query_params = array( 
        ':code' => $_POST['code']
    );

    $stmt = $link->prepare($query_string);
    $stmt->bind_param('s', $query_params[':code']);
    $result = $stmt->execute(); //$query_params is only in procedural, read the manual
    $row = $stmt->fetch();
    if($row) {
        $number = mt_rand(0,3999);
        echo $number;
    }
Kondziutek
  • 143
  • 1
  • 6
  • it gives me this error: Fatal error: Call to a member function execute() on a non-object – Robert Wills Dec 12 '15 at 22:10
  • try to replace the lines starting with $stmt = ... with $stmt = $link->prepare("SELECT code FROM code WHERE code = 'some test code' "); $stmt->execute(); and tell me what happened – Kondziutek Dec 12 '15 at 22:17
0

You should pass the SQL string to prepare, and therefore it is useless to do the query call:

// skip next line
//$results = $link->query("SELECT code FROM code WHERE code = :code");
$query_params = array( 
    ':code' => $_POST['code']
);

// Use SQL as argument here, not $results
$stmt = $link->prepare("SELECT code FROM code WHERE code = :code");
trincot
  • 317,000
  • 35
  • 244
  • 286