I am not an expert of php and PDO, but I managed to create a script to search a word in a table. I have two files:
the first, citazioni-search.2.php, has this content:
<?php
// (1) DATABASE CONFIG
// ! CHANGE THESE TO YOUR OWN !
define('DB_HOST', 'localhost');
define('DB_NAME', 'bibliografia');
define('DB_CHARSET', 'utf8');
define('DB_USER', 'myuser');
define('DB_PASSWORD', 'mypsw');
// (2) CONNECT TO DATABASE
try {
$pdo = new PDO(
"mysql:host=" . DB_HOST . ";charset=" . DB_CHARSET . ";dbname=" . DB_NAME,
DB_USER, DB_PASSWORD, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false ]
);
} catch (Exception $ex) {
die($ex->getMessage());
}
// (3) SEARCH
$stmt = $pdo->prepare("SELECT * FROM `citazioni__olon` WHERE `autore` LIKE ? OR `titolo` LIKE ? OR `keywords_dottorato` LIKE ?");
$stmt->execute(["%" . $_POST['search'] . "%", "%" . $_POST['search'] . "%", "%" . $_POST['search'] . "%"]);
$results = $stmt->fetchAll();
if (isset($_POST['ajax'])) { echo json_encode($results); }
?>
The second, citazioni-search.php, has this content:
<?php
/* [SEARCH FOR USERS] */
if (isset($_POST['search'])) {
require "citazioni-search.2.php";
}
/* [DISPLAY HTML] */ ?>
<!-- [SEARCH FORM] -->
<form method="post" arction="citazioni-search.2.php">
<input type="text" name="search" required/>
<input type="submit" value="cerca"/>
</form>
<!-- [SEARCH RESULTS] -->
<?php
if (isset($_POST['search'])) {
if (count($results) > 0) {
foreach ($results as $r) {
$key = explode(',', $r['keywords']);
printf("<div><h2>%s</h2> <blockquote><p>%s</p></blockquote><p><b>%s</b>, <i>%s</i>, <span>%s</span></p><p><a href=\"hashtag.php?tag=$key\">%s</a></p></div>", $r['titolo'], $r['testo'], $r['autore'], $r['fonte'], $r['fonte_spec'], $r['keywords']);
}
} else {
echo "No results found";
}
}
?>
It works, but I don’t manage to explode the keywords (values), as I can do in other (not PDO) php files.
The rows (strings) I have created recently, unsuccessfully are:
$key = explode(',', $r['keywords']);
and
<a href=\"hashtag.php?tag=$key\">%s</a>
As example of keywords values: philosophy, space, Earth.
I like to have an hyperlink for each of them (with the matching value).
Could you help me?