Ok so the problem is very simple, basically when you put for example "W" it should output hotel names and guest's surnames that contain that character. It doesn't that hotel names however it never gives me an output for guest's no matter what I put. There are several matching for guest's that should appear however I get nothing. I can't see any mistakes with my code... Help.
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<link href="style.css" rel="stylesheet" type="text/css"> <!-- This is linking style sheet (css)into this HTML page-->
<link href='https://fonts.googleapis.com/css?family=PT+Serif:400italic' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="navigation">
<form action="index.php" method="get">
<input type="submit" name="mainpage" value="Main Page" class="submitbut" id="but1" />
</form>
</div>
<form action="index.php" method="post">
<input type="text" name="search" id="searching" />
<input type="submit" name="data_submit" value="Search" id="scan" />
</form>
<?php
if( isset( $_GET['mainpage'] ) ) exit( header( "Location: mainpage.php" ) );
if ( isset( $_POST["data_submit"] ) ){
$search_term = strip_tags( trim( $_POST['search'] ) );
$conn = new PDO( 'mysql:host=localhost;dbname=u1358595', 'root' );
$stmt = $conn->prepare("SELECT * FROM `hotel` h
INNER JOIN `booking` b ON h.`hotel_id`=b.`hotel_id`
INNER JOIN `guest` g ON g.`guest_id`=b.`guest_id`
WHERE `name` LIKE :search_term;");
$stmt->bindValue(':search_term','%' . $search_term . '%');
$stmt->execute();
echo "
<table>
<tr>
<th>Hotels Matched</th>
</tr>";
while($hotel = $stmt->fetch()) {
echo "
<tr>
<td><a href='details.php?name=".$hotel['name']."'>".$hotel['name']."</a></td>
</tr>";
}
echo "</table>";
$stmt = $conn->prepare("SELECT * FROM `guest` g
INNER JOIN `booking` b ON g.`guest_id`=b.`guest_id`
INNER JOIN hotel ON b.`hotel_id`=h.`hotel_id`
WHERE g.`last_name` LIKE :search_term;");
$stmt->bindValue(':search_term', '%' . $search_term . '%');
$stmt->execute();
echo "
<table>
<tr>
<th>Guests Matched</th>
</tr>";
while($hotel = $stmt->fetch()) {
echo "
<tr>
<td><a href='details.php?name=".$hotel['first_name']."'>".$hotel['last_name']."</a></td>
</tr>";
}
echo "</table>";
$conn = NULL;
}
?>
</body>
</html>
With PDO Prepared statements with LIKE prepare FULL literal first.See PDO Wiki
ie.
$name = "%$name%";
I have simplified your code using one query. I have tested it on 2 tables, you will need to JOIN other table
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" id="searching" />
<input type="submit" name="data_submit" value="Search" id="scan" />
</form>
<?php
$host= "localhost";
$username="XXXX";
$password="XXXX";
$database="XXXX";
function writeTable($host,$database, $username, $password,$search_term) {
//Create query
$sql = "SELECT hotel.name AS hotel, guest.name AS guest
FROM `hotel`
LEFT JOIN `guest` ON hotel.guest = guest.id
WHERE hotel.name LIKE ?
OR guest.name LIKE ?
";
$html = '<table cellpadding="1" cellspacing="1">'. "\n";
//array for column names
$columnNames = array("hotel","guest");
//table header
$html .= '<tr>';
foreach ($columnNames as $value){
$html .= '<th>' . $value . '</th>';
}
$html .= '</tr>'. "\n";
// connect to the database
$db = new PDO("mysql:host=$host;dbname=$database", $hotelname, $password);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Prepare and execute query
$stmt = $db->prepare($sql);
$stmt->execute(array($search_term,$search_term));
// setting the fetch mode
$stmt->setFetchMode(PDO::FETCH_ASSOC);
//Add content
while($row = $stmt->fetch()) {
$html .= '<tr>';
$html .= '<td>' . $row['hotel'] . '</td>';
$html .= '<td>' . $row['guest'] . '</td>';
$html .= '</tr>'. "\n";
}
$html .= '</table>';
echo $html;
// close the connection
$dbh = null;
}
$search = strip_tags(trim($_POST['search'] ) );
if(isset($search) ){
if ($search != ''){
$search_term = '%'.$search.'%';
}else{
$search_term ='';
}
}
writeTable($host,$database, $hotelname, $password,$search_term);
?>
You should be able to modify to suit.
Related
Can I know what's mistake in here?
I have two tables in my database.
it is this
I have written the code as search player thing. I'll put the name or userid in the form and it'll process the information of user.
Here is my code
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="term" />
<input type="submit" value="Submit" />
</form>
<?php
include('config.php');
if (!empty($_REQUEST['term']))
{
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = " select u.* from users u inner join ranks r ON (u.UserID = r.UserID) where u.UserID = '%" . $term . "%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query))
{
echo 'Name: ' . $row['Name'];
echo '<br /> Cash: ' . $row['Cash'];
echo '<br /> Score: ' . $row['Score'];
echo '<br /> Race: ' . $row['Race'];
echo '<br /> Horseshoe: ' . $row['Horseshoe'];
}
}
?>
</body>
</html>
First of all you should update your config.php to mysqli_ functions.
and the mysqli_real_escape_string() and mysqli_query() functions need 2 Parameters. First $conn, second: the variable
finally your code should look like this:
<html lang="en">
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<form method="POST">
Search: <input title="searchfield" required type="text" name="term"/>
<input type="submit" name="submit" value="Submit"/>
</form>
<?php
include('config.php');
if (isset($_POST["submit"]) && !empty($_POST["submit"])) {
$term = mysqli_real_escape_string($conn, $_REQUEST["term"]); //make sure the $conn isset
$sql = "SELECT u.* FROM users u INNER JOIN ranks r ON (u.UserID = r.UserID) WHERE u.UserID LIKE '%" . $term . "%'"; // change = to LIKE
$r_query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($r_query)) {
echo 'Name: ' . $row['Name'];
echo '<br /> Cash: ' . $row['Cash'];
echo '<br /> Score: ' . $row['Score'];
echo '<br /> Race: ' . $row['Race'];
echo '<br /> Horseshoe: ' . $row['Horseshoe'];
}
}
?>
</body>
</html>
your config.php should look like this:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "idkw0t";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
you should use like in query as follows
$sql = " select u.* from users u inner join ranks r ON (u.UserID = r.UserID) where u.UserID like '%" . $term . "%'";
I'm looking for help with my products list.
My Code:
<!DOCTYPE html>
<html>
<head>
<title> Produktliste </title>
</head>
<body>
<iframe name="dir" style="display:none;"></iframe>
<form action="shop.php" method="post">
<p> <h2> Produkt hinzufügen </h2> </p>
<p> Produktname: <input type="text" name="Produktname"/> </p>
<p> Produktbeschreibung: <textarea rows=2 cols=20 name="Produktbeschreibung"></textarea> </p>
<p> Preis: <input type="text" name="Preis"/> </p>
<input type="submit" name="speichern" value="Speichern"/>
</form>
<?php
$connect = new mysqli ('localhost', 'root', '');
$connect->select_db('shop');
if (#$_REQUEST["Produktname"] && #$_REQUEST["Produktbeschreibung"] && #$_REQUEST["Preis"]) {
$produktname = #$_REQUEST["Produktname"];
$beschreibung = #$_REQUEST["Produktbeschreibung"];
$preis = #$_REQUEST["Preis"];
$result = $connect->query("INSERT INTO `shop`.`produkte` (`Produktname`, `Beschreibung`, `Preis`) VALUES ('$produktname', '$beschreibung', '$preis');");
if(!$result) {
echo "SQL Fehler: " . $connect->error;
die;
} else { echo "Letzte ID: " . $connect->insert_id;
}
}
?>
<table border="2" width="30%" style="border:1px solid #000000; border-spacing:inherit; text-align:left;">
<br><br>
<tr>
<td> Produkt </td>
<td> Beschreibung </td>
<td> Preis </td>
<td> Funktionen </td>
<?php
$result = $connect->query("SELECT * FROM produkte");
while($obj = $result->fetch_object()) {
echo '<tr><td>' . $obj->Produktname . '</td><td>' . $obj->Beschreibung . '</td><td>' . $obj->Preis . ' EUR ' . '</td><td> Bearbeiten, Löschen </td></tr>';
}
?>
</tr>
</table>
<?php
if (isset($_REQUEST["delete"])) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlpart = explode('=', $url);
$ProduktID = end($urlpart);
$result = $connect->query("DELETE FROM `shop`.`produkte` WHERE `ProduktID` = $ProduktID;");
header('Location: ./shop.php');
}
if(isset($_REQUEST["id"])) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlpart = explode('=', $url);
$ProduktID = end($urlpart);
// Update SQL Data?
}
if (!$result) {
echo "SQL Fehler: " . $connect->error;
die;
}
?>
</body>
</html>
I'm now looking for a way to retrieve the MySQL Data with the equivalent ID into the existing HTML Form and update it back to the MySQL Database... I'm currently learning PHP at the University and I can't think any further by myself.
It needs to get done withing this PHP File, like everything else is.
Thanks for any help! :)
If I understand you correct, you want to echo inserted row from database. Change the line:
$result = $connect->query("SELECT * FROM produkte");
into:
$result = $connect->query("SELECT * FROM produkte WHERE ID_prod_column = '$insertID'");
Try something like this. Just change "ID_prod_column" to correct name and $insertID to correct variable.
i made a simple web app that can add text to database and also can display it. I have such problem, when i added a text(it is added to database and displayed in browser) and refresh the page, in database previous value of text input is added again even if text input is empty.
after refresh
<?php
include 'config.php';
if(isset($_POST['Submit'])) {
if(strlen(trim($_REQUEST['text'])) > 0) { $conn->query("INSERT INTO Posts (Text_Post,Data) VALUES ('".$_POST['text']."','".date("Y-m-d H:i:s")."')");
$value = '';
}
$result = $conn->query("SELECT * FROM Posts ORDER BY Data DESC");
$ul = '<ul>';
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['ID_Post'];
$text = $row['Text_Post'];
$data = $row['Data'];
$ul .= '<li id="'. $id .'"> '. $text . ' </li>';
}
$ul .= '</ul>';
$lista = $ul;
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>anonim</title>
<link rel="stylesheet" type="text/css" href="style/style.css">
</head>
<body>
<?php
include 'config.php';
$result = $conn->query("SELECT * FROM Posts ORDER BY Data DESC");
$ul = '<ul>';
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['ID_Post'];
$text = $row['Text_Post'];
$data = $row['Data'];
$ul .= '<li id="'. $id .'"> '. $text . ' </li>';
}
$ul .= '</ul>';
$lista = $ul;
?>
<form name="form" action="" method="post">
<input type="text" name="text" id="text" />
<input type="submit" id="Submit" name="Submit" value="Add" />
<div id="lista">
<?php if(isset($lista)){ echo $lista; } ?>
</div>
</form>
</body>
</html>
This question already has answers here:
delete row in my database using php pdo [closed]
(2 answers)
Closed 7 years ago.
I want to delete a selected row from my database, but I don´t know how to accomplish it. I am completly new to this topic, so it would be really nice, when you could explain to me.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> PHP F1 - Datenbank</title>
<style>
button {
margin:5px;
margin-left:-0px;
}
.insert {
position:relative;
margin:0px;
margin-bottom:5px;
margin-top:-25px;
}
</style>
</head>
<body>
<h2> Insert Dokument für deine Datensätze ! </h2>
<form action="F1_PHP.php" method="post">
<input type="text" name="jahr" placeholder="Albert-Park"> <br><br>
<input type="text" name="sieger" placeholder="Australien"> <br><br>
<input type="text" name="schnellster" placeholder="Melbourne"> <br><br>
<input type="text" name="strecke" placeholder="Laenge"><br><br>
<input type="submit" name="formdaten" class="insert" value="Insert"> <br>
</form>
<table border="1">
<tr>
<th></th>
<th>Strecke</th>
<th>Land</th>
<th>Stadt</th>
<th>Länge</th>
</tr>
<?php
try {
$server = 'mysql:dbname=f1;host=localhost';
$user = 'root';
$password = '';
$options = array
(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$pdo = new PDO($server, $user, $password, $options);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($pdo){
if (isset($_POST["formdaten"])) {
$jahr = $_POST["jahr"];
$sieger = $_POST["sieger"];
$schnellster = $_POST["schnellster"];
$strecke = $_POST["strecke"];
$eintrag = $pdo->prepare("INSERT INTO Strecke
(pk_Strecke, Land, Stadt, Laenge) VALUES (?, ?, ?, ?);");
$eintrag->execute(array($jahr, $sieger, $schnellster, $strecke));
if ($eintrag == true) {
echo "Eintrag war erfolgreich";
} else {
echo "Fehler";
}
}
}
}
catch (PDOException $error) {
echo 'Verbindung fehlgeschlagen: ' . $error->getMessage();
}
try {
$query= 'SELECT pk_Strecke, Land, Stadt, Laenge FROM Strecke';
$stmt = $pdo -> query($query);
$deleteString = "";
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
echo '<tr>';
echo ' <td>'."<input type='radio' name='markiert'>".'</td>';
echo ' <td>'. $row["pk_Strecke"].'</td>';
echo ' <td>'. $row["Land"]. '</td>';
echo ' <td>'. $row["Stadt"]. '</td>';
echo ' <td>'. $row["Laenge"]. '</td>';
echo '</tr>';
}
echo '</table>';
}
catch (PDOException $error) {
echo 'Fehler beim Lesen der Daten ' . $error->getMessage();
}
?>
<br>
<input type="submit" name="delete" value="Delete">
<?php
// delete button
?>
<input type="submit" name="update" value="Update">
<?php
//Update button
?>
<br>
<table border="1">
<tr>
<th> </th>
<th> Jahr </th>
<th> Sieger </th>
<th> Schnellste Runde </th>
<th> Strecke </th>
</tr>
<?php
try {
$query= 'SELECT pk_Jahr,Sieger,SchnellsteRunde,pk_fk_Strecke
FROM Rennen join Strecke on pk_fk_Strecke = pk_Strecke
order by pk_Jahr';
$stmt = $pdo -> query($query);
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) )
{
echo '<tr>';
echo ' <td>'."<input type='radio' name='markiert'>".'</td>';
echo ' <td>'. $row["pk_Jahr"].'</td>';
echo ' <td>'. $row["Sieger"]. '</td>';
echo ' <td>'. $row["SchnellsteRunde"]. '</td>';
echo ' <td>'. $row["pk_fk_Strecke"]. '</td>';
echo '</tr>';
}
echo '</table>';
}
catch (PDOException $error) {
echo 'Fehler beim Lesen der Daten ' . $error->getMessage();
}
?>
</body>
</html>
I appreciate every tip from you.
Use the following statements:
$sql = "DELETE FROM `Rennen` WHERE `pk_Jahr` = :id_to_delete";
$query = $db->prepare( $sql );
$query->execute( array( ":id_to_delete" => 'Value of pk_Jahr of the row to delete' ) );
It looks like you have a good idea of how to set up the PHP side of things, so I'll just deal with the SQL part.
The general syntax for a delete using PDO and MySQL would be as follows:
$query = "DELETE FROM TableName WHERE Field = :value";
$stmt = $pdo->prepare($query);
$stmt-> bindParam(':value', $value);
$stmt->execute();
The field you're querying against on that table needs to be unique, unless you're wanting to delete multiple rows (so best to use a primary key for the field and value).
It looks like you're using racing circuits in one of your tables, so your table may look like this (I'll call the table "circuits"):
id (primary key), circuit, country.
You may have the following data in it:
1, Albert Park, Australia
2, Silverstone, Great Britain
3, Adelaide, Australia
To delete Albert Park from the database, you'd run this:
$value = 1;
$query = "DELETE FROM circuits WHERE id = :value";
$stmt = $pdo->prepare($query);
$stmt-> bindParam(':value', $value);
$stmt->execute();
To delete all circuits in Australia (2 of the 3 above records):
$value = "Australia;
$query = "DELETE FROM circuits WHERE country = :value";
$stmt = $pdo->prepare($query);
$stmt-> bindParam(':value', $value);
$stmt->execute();
You could pass the value for $value through a form, and using bindParam() protects against SQL injection.
Long time reader, first time poster. I am a novice PHP enthusiast, and I have a page that I have been working. Right now I have the DB connection working well and my SELECT statement is giving me the info needed. My problems are two fold (maybe more after this post; set your phasers to cringe):
At one point, I had the INSERT working, but it suddenly stopped and no amount of tweaking seems to bring it back. I have verified that the INSERT statement works in a seperate PHP file without variables.
When I did have the INSERT working, every refresh of the page would duplicate the last entry. I have tried tried several ways to clear out the $_POST array, but I think some of my experimenting lead back to problem #1.
<?php
$dbhost = "REDACTED";
$dbuser = "REDACTED";
$dbpass = "REDACTED";
$dbname = "guest_list";
// Create a database connection
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("DB's not here, man: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
// replacement for mysql_real_escape_string()
function html_escape($html_escape) {
$html_escape = htmlspecialchars($html_escape, ENT_QUOTES | ENT_HTML5, 'UTF-8');
return $html_escape;
}
// Posting new data into the DB
if (isset($_POST['submit'])) {
$first = html_escape($_POST['first']);
$last = html_escape($_POST['last']);
$contact = html_escape($_POST['contact']);
$associate = html_escape($_POST['associate']);
$insert = "INSERT INTO g_list (";
$insert .= "g_fname, g_lname, g_phone, g_association) ";
$insert .= "VALUES ('{$first}', '{$last}', '{$contact}', '{$associate}')";
$insert .= "LIMIT 1";
$i_result = mysqli_query($connection, $insert);
// I have verified that the above works by setting the varialble
// in the VALUES area to strings and seeing it update
}
$query = "SELECT * ";
$query .= "FROM g_list ";
$query .= "ORDER BY g_id DESC";
$q_result = mysqli_query($connection, $query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Guest List</title>
<link href="guest.css" media="all" rel="stylesheet" type="text/css" />
</head>
<body>
<header>
<h1>REDACTED</h1>
<h2>Guest Registry</h2>
</header>
<div class="container">
<div class="registry">
<form name="formup" id="main_form" method="post">
<fieldset>
<legend>Please enter your name into the registry</legend>
<p class="first">First Name:
<input type="text" name="first" value="" placeholder="One or more first names" size="64"></p>
<p class="last">Last Name:
<input type="text" name="last" value="" placeholder="Last name" size="64"></p>
<p class="contact">Phone Number or Email:
<input type="text" name="contact" value="" placeholder="" size="32"></p>
<p class="associate">Your relation?
<input type="text" name="associate" value="" placeholder="" size="128"></p>
<p class="submit">
<input type="submit" name="submit" title="add" value="submit" placeholder=""></p>
</fieldset>
</form>
</div>
</div>
<h3>Guest List:</h3>
<table>
<tr>
<th>Firstname(s)</th><th>Lastname</th>
<th>Phone or Email</th><th>Association</th>
</tr>
<?php while($guest = mysqli_fetch_assoc($q_result)) {
echo "<tr>" . "<td>" . $guest["g_fname"] . "</td>"
. "<td>" . $guest["g_lname"] . "</td>"
. "<td>" . $guest["g_phone"] . "</td>"
. "<td>" . $guest["g_association"] . "</td>" . "</tr>";
} ?>
</table>
<footer>
<div>Copyright <?php echo date("Y"); ?>, REDACTED, LLC.</div>
<?php
if (isset($connection)) {
mysqli_close($connection);
}
?>
</footer>
</body>
</html>
These two lines will fail:
$insert .= "VALUES ('{$first}', '{$last}', '{$contact}', '{$associate}')";
$insert .= "LIMIT 1";
Two problems here, all with the second line:
No SPACE between ) and LIMIT: )LIMIT 1 is your code;
LIMIT 1 in an INSERT is not allowed....