Problems
- You need to use an
if/else
statement to check if rows were returned from the query
- If rows were returned then output the row
- If not then output notification to that effect
- You should be using prepared statements to protect your database from malicious user input
- You don't need to use a while loop to access the returned results
- Unless you're expecting multiple rows returned -- which I doubt
Solution(s)
Notes
I've adjusted your use of ternary logic and incorporated the NULL coalescent operator instead:
$search = $_POST["search"] ?? $_GET["search"] ?? NULL;
// if $_POST["search"] has data then set $search = $_POST["search"]
// elseif $_GET["search"] has data then set $search = $_GET["search"]
// else set $search = NULL
mysqli
// Set database variables
$db_host = "localhost";
$db_user = "root";
$db_pass = "some+password";
$db_name = "sprawdzarka";
// Enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Connect to the database
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
// Set the search parameter to value from $_POST, $_GET, or NULL
$search = ( $_POST["search"] ?? NULL ) ?: ( $_GET["search"] ?? NULL );
// Check to see if the search URL was submitted
if ( $search ){
$sql = "SELECT * FROM domeny WHERE domena = ?"; // Prepare query string
$query = $mysqli->prepare($sql); // Prep the query
$query->bind_param("s", $search); // Bind the URL
$query->execute(); // Execute the query
$query->store_result(); // Store the returned records
$query->bind_result($domena, $handlowiec); // Bind returned columns to variables
// Check to see if a result was returned
if( $query->fetch() ){
// Print out the table row
echo "
<tr>
<td>Domain: {$domena} </td>
<td>Belongs to: {$handlowiec}</td>
</tr>
";
}
else{
// Print out if no results were returned
echo "This domain doesn't exist: <a href=\"{$search}\">{$search}</a>";
}
}
PDO
// Set database variables
$db_host = "localhost";
$db_user = "root";
$db_pass = "some+password";
$db_name = "sprawdzarka";
// Connect to the database
$pdo = new pdo(
"mysql:host={$db_host};dbname={$db_name}",
$db_user,
$db_pass,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE
]
);
// Set the search parameter to value from $_POST, $_GET, or NULL
$search = ( $_POST["search"] ?? NULL ) ?: ( $_GET["search"] ?? NULL );
// Check to see if the search URL was submitted
if ( $search ){
$sql = "SELECT * FROM domeny WHERE domena = ?"; // Prepare query string
$query = $pdo->prepare($sql); // Prepare query
$query->execute([$search]); // Execute query and bind parameters
// Check to see if a result was returned
if( $row = $query->fetchObject() ){
// Print out the table row
echo "
<tr>
<td>Domain: {$row->domena} </td>
<td>Belongs to: {$row->handlowiec}</td>
</tr>
";
}
else{
// Print out if no results were returned
echo "This domain doesn't exist: <a href=\"{$search}\">{$search}</a>";
}
}