It seems ampersand symbol is causing problem for me some where in my flow of PHP, HTML, and MySql.
With the following database and table:
DROP DATABASE IF EXISTS testamp;
CREATE DATABASE testamp;
USE testamp;
DROP TABLE IF EXISTS acronym;
CREATE TABLE acronym(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
terminology VARCHAR(255) NOT NULL UNIQUE,
acronym VARCHAR(255) NOT NULL,
index (terminology),
index (acronym)
);
INSERT INTO acronym
(terminology, acronym)
values
( "United States", "US" )
,( "Humanitarian and compassionate", "H&C" )
;
It can be verified that "H&C" is in the database by select * from acronym where acronym like 'h%c';
Now with a .php, I give the user an input box for searching an acronym:
<input type="text" name="acronym" size="50"
placeholder="Enter an acronym"
autofocus
onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"
>
In case of POST, the user input is retrieved by calling a function, $acronym = test_input($_POST["acronym"]);
, which sanitilizes the input
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Then, the input is used to retrieve data from database:
$link = create_link() or die("create_link");
$stmt = $link->prepare(
'SELECT acronym, terminology FROM acronym WHERE acronym like ? ORDER BY acronym'
);
$like_value="%$acronym%";
$stmt->bind_param("s", $like_value) or die("bind_param");
$stmt->execute() or die("execute");
$stmt->store_result();
echo "<p>num_rows: " .$stmt->num_rows .PHP_EOL;
Now, if what's inside the input box is "H&C" without qutes, no record is retrieved, Even though "US" gives me one record as expected.