简体   繁体   中英

MySQLi Select to PHP variable

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:
我的桌子

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

You need to fetch the results.

$query = "SELECT code FROM code_ever WHERE code = 'XKBKNABJK'";

    if ($result = mysqli_query($conn, $query)) {

        /* fetch associative array */
        while ($row = mysqli_fetch_assoc($result)) {
            echo $row["code"];
        }

        /* free result set */
        mysqli_free_result($result);
    }

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:

在此处输入图片说明

Without fetching record you cant print the result

Use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM