I wrote a PHP script with a database connection, which appears to work properly.
The problem I’m having is in using a SELECT
statement to fetch values from my database and assign those values to PHP variables.
If I copy the SQL into PHPMyAdmin, I get the right result, so I trust the query itself.
I get an error, if I write:
echo $result;
What do I do wrong?
This is my full code:
<?php $servername = "XXXXXX"; $username = "XXXXXX"; $password = "XXXXX"; $dbname = "XXXXXX"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $test_code = $_GET['code']; $product_name = $_GET['product']; // sql to create table $sql = "CREATE TABLE IF NOT EXISTS code_ever ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, produkt VARCHAR(50) NOT NULL, code VARCHAR(30) NOT NULL )"; if ($conn->query($sql) === TRUE) { } else { } // sql to create table $sql = "CREATE TABLE IF NOT EXISTS code_scanned ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, produkt VARCHAR(50) NOT NULL, code VARCHAR(30) NOT NULL )"; if ($conn->query($sql) === TRUE) { } else { } $query = "SELECT code FROM code_ever WHERE code = 'XKBKNABJK'"; $result = mysqli_query($conn, $query); if($result) { echo $result; } else { echo("Sorry:".mysqli_error($conn)); } $conn->close(); ?>
Advertisement
Answer
You need to fetch the results.
$query = "SELECT code FROM code_ever WHERE code = 'XKBKNABJK'"; $result = mysqli_query($conn, $query); /* fetch associative array */ while ($row = mysqli_fetch_assoc($result)) { echo $row["code"]; }
http://php.net/manual/en/mysqli-result.fetch-assoc.php
Aside from fetching the results you should redesign the table. You shouldn’t have more than one value per ‘table cell’. For instance you have comma separated values for the size/color etc of the product. You should have those as separate attributes in the table or maybe even a separate table.
Example: