0

What am I messing up in this code here?

I keep getting:

My call function

<?php
    function generateRandomNumber($length = 10) {
    $number = '1234567890';
    $numberLength = strlen($number);
    $randomNumber = '';
    for ($i = 0; $i < $length; $i++) {
        $randomNumber .= $number[rand(0, $numberLength - 1)];
    }
    return $randomNumber;
}?>

My body code:

<html>
    <body>
        *** database setting
        <?php $conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
            // Check connection
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            }
            $ddd = generateRandomNumber();
            $hashed = hash('sha512', $ddd);

            echo $hashed."<br>";
            $sql = "INSERT INTO temp (quote) VALUES ($hashed)";

            if ($conn->query($sql) === TRUE) {
               echo "New record created successfully";
            }
            else {
               echo "Error: " . $sql . "<br>" . $conn->error;
            }
            $conn->close();
        ?>
    </body>
</html>

Error: INSERT INTO temp (quote) VALUES (8c7a5763327c6551e03994c9ee2c34226d2c4dc17b0f0a51de24af1bdc32258b11549c2e8722a386167917b8913ff8a1acb33c91fbd1dc9bd40ac7715f45099c) Unknown column '8c7a5763327c6551e03994c9ee2c34226d2c4dc17b0f0a51de24af1bdc32258b11549c2e8722a386167917b8913ff8a1acb33c91fbd1dc9bd40ac7715f45099c' in 'field list'

I have my MySQL table as quote=varchar(255).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Isn't `` `` required for the HTML to validate? – Peter Mortensen Mar 06 '17 at 19:10
  • I am sorry but I just don't see why you marked this question as duplicated. My question is direct to the point which I couldn't figure out on my own. I was not looking for a lecture about the how to use single quotes, double quotes, and backticks in MySQL. Shakti Phartiyal help me exactly the way I was looking for! Please advise! – Robert Barros Mar 07 '17 at 04:40

1 Answers1

1

You need to quote any varchar value that you insert to the DB.

Change your query from

$sql = "INSERT INTO temp (quote) VALUES ($hashed)";

To:

$sql = "INSERT INTO temp (quote) VALUES ('$hashed')";

Notice the single quotes of $hashed

Shakti Phartiyal
  • 6,156
  • 3
  • 25
  • 46
  • You did it! Thanks. Just wondering why? and where should I go to read the reason for it? i though the 1st quotes was doing that! – Robert Barros Mar 06 '17 at 16:17
  • You see the query that is created should be `INSERT INTO temp (quote) VALUES ('khfieufy78wytiufhwgweg')` and not `INSERT INTO temp (quote) VALUES (hfew98w73hfr97w)` – Shakti Phartiyal Mar 06 '17 at 16:18