Skip to content
Advertisement

mysql query in procedural php isn’t returning single field

Trying to retrieve a single field from a mysql table. Here’s the PHP:

if ($signatureDAT) {
    mysqli_query($dragonden, "INSERT INTO Signatures(signature) VALUES('$signatureDAT')");
    $sigID = mysqli_insert_id($dragonden);
    
    
    // RETRIEVE DATA FROM DB, TO VERIFY IT WAS SAVED PROPERLY
    $sigDAT = mysqli_query($dragonden, "SELECT signature FROM Signatures WHERE id = '$sigID'");
    
    
    // SEND RESULTS BACK TO AJAX
    $data = array();
    array_push($data, $signatureDAT, $sigDAT);
    print json_encode($data);
}

I then use ajax to retrieve $sigDAT

Ajax returns the following result for $sigDAT: [object Object]
Ajax returns $signatureDAT (the original data) correctly.

$sigDAT and $signatureDAT should have identical value, so I suspect the problem is in the “RETRIEVE” section of code.

Advertisement

Answer

To answer your question, you need to use mysqli_fetch_assoc() to retrieve the results – $sigDAT in your code is an object of the class mysqli_result. However, your query is vulnerable to SQL injection attacks, and you should therefor use a prepared statement to execute your queries. See the code below.

Also, if you set mysqli_report() to throw exceptions on error, you don’t have to perform your subsequent select to verify that the query completed – because if an error occurs, an exception is thrown, and you don’t reach the part where it adds the values into $data.

// Make MySQL throw exceptions on error
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

if ($signatureDAT) {
    $data = [];

    try {
        $stmt = $dragonden->prepare('INSERT INTO Signatures(signature) VALUES (?)');
        $stmt->bind_param("s", $signatureDAT);
        $stmt->execute();

        $data[] = $signatureDAT;
        $data[] = $stmt->insert_id;
        $stmt->close();
    } catch(Exception $e) {
        // An error occurred, handle that here 
    }
    print json_encode($data);
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement