2

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.

This is my table:
my table

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();
?>

2 Answers 2

4

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:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Thanks for your answer it works now :). I see syntax like this $configs = $db->QueryFetchArrayAll("SELECT config_name,config_value FROM site_config"); for example. How can i use this. this look much shorter to use a query and fetch data.
0

Without fetching record you cant print the result

Use

$result = mysqli_query($con, $query);
while ($final = mysqli_fetch_array($result)) {
    echo $final['code'];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.