I am doing a project and need some help please :) (full code at bottom)
The project needs to be accessed with PDO.
I need search results to appear on the same page as the search was entered.
This below doesnt seem right to me using GET instead of POST.. is this correct?
This works but I need to remove/hide this bit of code that appears when my page (index.php) first loads.
if(!isset($_GET['search']))
{ echo "Error, Please go back."; exit;}
How do i do that?
Also my second problem is I can not get the search form to search more than one field in a table. It just wont let me. I cant use this bit of code either
%'.$searchterm.'%
as it wont give me any feedback from the search. So i am using the
:searchterm
in
$searchterm = $_GET['search'];
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :searchterm OR nationality ");
$stmt->bindValue(':searchterm','%'.$searchterm.'%');
$stmt->execute();
Here is my full code:
<?php
$servername = 'localhost';
$username = "root";
$password = "";
$dbname = "u1360138";
<?php
if(isset($_POST['search'])){
echo 'Search';
}
?>
<!-- Search facility 1 -->
<form action="index.php" method="get">
<label for="search">Enter a weight class. Need to be more than one searchs which wont work</label>
<input type="text" name="search" id="search">
<input type="submit" value="Search">
</form>
<?php
// DB Connection
try {$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);}
catch(PDOException $e)
{echo "Error conntecting to the DB: " . $e->getMessage();}
if(!isset($_GET['search']))
{ echo "Error, Please go back."; exit;}
// DB Connection
$searchterm = $_GET['search'];
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :searchterm");
$stmt->bindValue(':searchterm','%'.$searchterm.'%');
$stmt->execute();
// loop displays loop
while ($boxer = $stmt->fetch(PDO::FETCH_OBJ))
{ echo "<ul>";
echo "<a href='details.php?idboxer=".$boxer->idboxer."'>";
echo "<li>".$boxer->firstname." ".$boxer->lastname."</li>";
echo "</a>";
echo "</ul>"; }
$conn=NULL;
?>
In good practices, use POST to send params when user SEND something to the server that will change data on the server (store in db for exemple or send an email). Use GET when user RETRIEVE something from the server, to read data (query a db). So prefer GET here.
To solve your issue, simply enclose the whole code that process the research in a "if(isset($_GET['search'])){}" section as below:
<?php
$servername = 'localhost';
$username = "root";
$password = "";
$dbname = "u1360138";
<?php
if(isset($_GET['search'])){
echo 'Search';
}
?>
<!-- Search facility 1 -->
<form action="index.php" method="get">
<label for="search">Enter a weight class. Need to be more than one searchs which wont work</label>
<input type="text" name="search" id="search">
<input type="submit" value="Search">
</form>
<?php
if(isset($_GET['search'])){
// DB Connection
try {$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);}
catch(PDOException $e)
{echo "Error conntecting to the DB: " . $e->getMessage();}
// DB Connection
$searchterm = $_GET['search'];
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :searchterm");
$stmt->bindValue(':searchterm','%'.$searchterm.'%');
$stmt->execute();
// loop displays loop
while ($boxer = $stmt->fetch(PDO::FETCH_OBJ))
{
echo "<ul>";
echo "<a href='details.php?idboxer=".$boxer->idboxer."'>";
echo "<li>".$boxer->firstname." ".$boxer->lastname."</li>";
echo "</a>";
echo "</ul>";
}
$conn=NULL;
}
?>
This below doesnt seem right to me using GET instead of POST.. is this correct? This works but I need to remove/hide this bit of code that appears when my page (index.php) first loads.
It depends on whenever you want to use GET or POST. POST is more secure, so for submitting a form I'm always using POST. In that case you can leave this code:
if(isset($_POST['search'])){
echo 'Search';
}
You do need to change the form's action type to POST:
<form action="index.php" method="post">
....
Then add the end you need to get the search value from the POST instead of GET, because we changed the action type.
$searchterm = $_POST['search'];
So i figured this out and
<!-- HTML FORM SEARCH BAR -->
<form action="index.php" method="post">
<label for="enteredterm">Enter a Weight-class or a Nationality:</label>
<input type="text" name="enteredterm">
<input type="submit" name="search">
</form>
<!-- HTML FORM SEARCH BAR -->
if(isset($_POST['search'])){
$enteredterm = $_POST['enteredterm'];
if ($enteredterm ===""){
echo "error, enter something.";
} else {
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :enteredterm OR nationality LIKE :enteredterm or lastname LIKE :enteredterm ORDER BY year");
$stmt->bindValue(':enteredterm','%'.$enteredterm.'%');
$stmt->execute();
$count= $stmt->rowCount();
echo "You entered ".$enteredterm." and returned ";
if($count <= 1){
echo $count." result.";
}else{
echo $count." results.";
}
// loop displays loop
while ($boxer = $stmt->fetch(PDO::FETCH_OBJ))
{ echo "<ul>";
echo "<a href='details.php?idboxer=".$boxer->idboxer."'>";
echo "<li>".$boxer->firstname." ".$boxer->lastname."</li>";
echo "</a>";
echo "</ul>"; }
Related
I've created a mysql table with two columns. One is ID and other is Heading. I have a textarea on which I run UPDATE code and whenever someone submits a form its being updated in the datebase column under heading. And that works fine but I want to show the last inputted submit inside my textarea.
My code is showing the last inputted value but when I reset the page it all turns out blank and its not showing anymore. I looked out in datebase and the heading is still there so I don't know why its dissapearing from the front end.
My page:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
So for example if I type Aleksa, after submit it will get url like edit.php?heading=Aleksa&submit=Submit. And then when I delete url just to edit.php, the value is missing.
You can test the page here: https://www.easybewussterschaffen.com/admin/edit.php
This is happening, because it's always trying to insert the heading when you refresh the page. You should check to see if the request is GET or the request is POST, and only insert it if they're submitting the form.
Update your form method, specify it to POST, and specifically check the method or check for the existance of $_POST['submit'] as shown below:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
// Use one of the 2 if statements:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Trying to insert a new heading
if (isset($_POST['submit'])) { // Alternative
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="POST">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
Alternatively, if you still wish to make a GET request, you should check to make sure that the heading is set:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
if (isset($_GET['submit'])) {
$heading = mysqli_real_escape_string($link, $_GET['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="GET">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
I did it like this, is this good tho? Its working
<?php
$sql = "SELECT * FROM content";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '';
while($row = mysqli_fetch_array($result)){
echo $row['heading'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
How can I loop through results of a MySQL query and display them in option values in the html form in my script.
I have tried putting the values manually into the option tags and values, but I want to do it depending on whats already inside the database. Do I need another connection to the database to run in the same part as the form element itself?
<title>Add a unit</title>
</head>
<body>
<div class= "container">
<h1>Add a unit</h1>
<?php // Script 12.4 - add_size.php
// This script adds a blog size to the database.
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form.
// Connect and select:
$connection = mysqli_connect('localhost', $user, $password, $database);
mysqli_set_charset($connection, 'utf8');
// Validate the form data:
$problem = false;
if (!empty($_POST['unit']) && !empty($_POST['size']) && !empty($_POST['price'] && isset($_POST['building'])) {
$unit = mysqli_real_escape_string($connection, trim(strip_tags($_POST['unit'])));
$size = mysqli_real_escape_string($connection, trim(strip_tags($_POST['size'])));
$price = mysqli_real_escape_string($connection, trim(strip_tags($_POST['price'])));
$building = mysqli_real_escape_string($connection, trim(strip_tags($_POST['building'])));
} else {
echo '<p style="color: red;">Please submit a unit and an size and price.</p>';
}
if (!$problem) {
// Define the query:
$query = "INSERT INTO individualspecs (Space, Size, Price, fk_Id, Id) VALUES ('${unit}', '${size}', '${price}', '${building}', 0)";
// Execute the query:
if (#mysqli_query($connection, $query)) {
echo '<p>The unit has been added!</p>';
// why doesnt print "$msg"; work when using $i
} else {
echo '<p style="color: red;">Could not add the unit because:<br>'.mysqli_error($connection).'.</p><p>The query being run was: '.$query.'</p>';
echo $msg;
}
mysqli_close($connection); // Close the connection.
} // No problem!
} // End of form submission IF.
// Display the form:
?>
<form action="add_units.php" method="post" enctype="multipart/form-data">
<p>Select Building: <select name="building">
<option value="<?php echo ?>"><?php echo ?></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
</p>
<p>Enter Unit: <input type="text" name="unit" size="40" maxsize="100"></p>
<p>Enter Size in Sq Feet: <input type="number" name="size" size="40" maxsize="100"></p>
<p>Enter Price: <input type="text" name="price" size="40" maxsize="100"></p>
<!-- removed upload photos -->
<input type="submit" name="submit" value="Add indiviual Space!">
</form>
</div>
</body>
</html>
I would like the select dropdown menu to show a list of all buildings currently in the database so that the user can select a building to add his unit to.
If no buildings exist in database handle situation i.e. echo 'No buildings found in database, you need to
add a building record before attempting to add individual units';
Here is my buildings table:
https://imgur.com/a/2KMOUBD
Here is my units table:
https://imgur.com/a/w24IFuy
Here's a simple code to do what you need
Your code is so messed up, try to clean it :-)
We connect to mysql DB Using PDO class because it's more powerful and secure
you can change root with your db username
pass with your db password
db with your db name
read more about PDO here
// connect to db
$dbh = new \PDO('mysql:host=127.0.0.1;dbname=db', "root", "pass");
// query to select from db
$q = 'SELECT * FROM users';
// prepare and execute the query
$buildsq = $dbh->prepare($q);
$buildsq->execute();
// fetch the results and save them to $build var
$builds = $buildsq->fetchAll();
// check if their is results and print them
if($buildsq->rowCount()) {
foreach ($builds as $build) {
echo '<option value="">' . $build['name'] . '</option>';
}
} else {
echo "<option>No results </option>";
}
It's not the best, but it does what you need.
Try to put connection part in a function to clean up your code.
I have two tables in db, input table nd output table. input table got two columns $ID (autoincreament), $question. table 2 got two columns $Q_ID, Answer.
i made a php page (1) where i printed out the table 1 content (QUESTION) and i added a text area to get answers from visitors, along with it i also added a echo "hidden" field for ID from table one.
Now this php page 1 redirects to php page 2, where i POST the text area input into the answer column in table 2. But unfortunately, the ID is not able to get posted in q_id column of table 2...
I tried a lot but no hope..
My PHP script #1 as follows::
<div class="name">
<?php
$sql = "SELECT * FROM input";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$index = 0;
while($row = $result->fetch_assoc()) {
$index++; // stuff inside foreach goes here
?>
<div id="q">
<B><big><font color= #ba4a00> Q:</font></big> <?php echo $row["question"]; ?>
<?php
echo '<button class="add" id="add_'.$index.'"><B>Add Answer</B></button>';
echo '<form style="display:none;" name="answer_'.$index.'" method="post" action="output.php">';
echo '<input type="hidden" name="questionid" value="<?php echo $row[id]?>"/>';
echo '<textarea type="text" class="addtext" name="addtext" required id="addtext_'.$index.'" placeholder="Please type your answer here.." ></textarea>';
echo '<button onClick="addsubmit('.$index.');" type="submit" id="addsubmit_'.$index.'" class="addsubmit"><B>Submit</B></button>';
echo '</form>';
?>
</div>
<?php
}
} else {
echo "0 results";
}
$conn->close();
?>
</div>
My PHP script #2 as follows::
<?php include('1.php'); ?>
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "*******";
$dbname = "the_database";
$addtext = $_POST['addtext'];
$questionid = $_POST['questionid'];
$date = date_default_timezone_set('Asia/Kolkata');
$date = date('M-d,Y H:i:s');
$conn = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO output (question_id, answer, date)
VALUES ('$questionid', '$addtext', '$date')";
if ($conn->query($sql) === TRUE) {
echo '<script language="javascript">';
echo 'alert("Your Answer has been Succesfully posted")';
echo '</script>';
echo '';
}
else {
echo "ERROR" . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
i want the respective question id to be passed to table 2 along with its answer.
Any help is greatly appreciated..
Give single-quote in $row['id']. Change this <?php echo $row[id] >? to <?php echo $row['id'] >?
echo '<input type="hidden" name="questionid" value="'. $row['id'].'"/>';
Already you are echoing the form using the ECHO Attribute in the PHP but after that also you have echoed it and that is wrong.
You have to make the code like this.
echo '<input type="hidden" name="questionid" value="'. $row['id'].'"/>';
Try this and share the thought about the code..
try enclosing id in double quotes in php 1:
echo '<input type="hidden" name="questionid" value="'.$row['id'].'"/>';
yip... looking a this a bit more closely you've got a bit of a problem with mixing single and double quotes in PHP #1.
for example, on this line the echo command ends after the second single quote after add_
echo '<button class="add" id="add_'.$index.'"><B>Add Answer</B></button>';
You need to use either single or double quotes consistently.
I am a new PHP programmer. I created a user login page where can i see list of user who is logged in. I am using PDO for connecting database. The Problem is if I want to delete user from the list it only delete the last inserted user. What i am doing wrong ? Can someone please help me...
Here is my HTML code:
<form action="" method="post">
<?php
foreach($rows as $row){
$time = $row['time_out'];
echo "
<input type='text' value='$row[user_name]' name='user_name'>
<input type='text' value=' $row[course]' name='course'>
<input type='text' value=' $time'>
<input type='submit' value='submit' name='submit'>
<br>";
}
?>
</form>
if(isset($_POST['submit'])){
//get course
$course = $_POST['course'];
//get user_name
$user_name = $_POST['user_name'];
//deleting user from the database
$database->delete($user_name);
//Redirect to current page
header('Location: tutor.php');
exit;
}
Here is my method for getting logged in user:
public function selectFromOnline()
{
$sql = $this->connection()->prepare("SELECT * FROM online");
$sql->execute();
return $sql->fetchAll();
}
Here is my method for deleting user:
public function delete($user_name)
{
$sql = $this->connection()->prepare("DELETE FROM online WHERE user_name = :user_name");
$sql->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$sql->execute();
return $sql;
}
Sorry But I didn't understand your code but I understood your problem and here it is my solution with "mysqli_query"....
<?php
//Please set these veriables according to your values....
$host_name = "YOUR_DB_HOST_NAME"; //Normally 'localhost'
$password = "YOUR_PASSWORD_FOR_MYSQL"; //your password
$username = "YOUR_USERNAME_FOR_MYSQL"; //Normally Root
$database_name = "NAME_OF_YOUR_DATABASE";
$connect = mysqli_connect($host_name, $username, $password, $database_name);
if(!$connect){
echo "Something is Wrong Please Check your host name, user name, password or database name";
}
?>
<!--YOUR FORM STARTS----------------------------------------------------->
<!--DON'T FORGET TO SET ACTION TO #(ON THE SAME PAGE)------------------------------------>
<form action="#" method="post">
<?php
foreach($rows as $row){
$time = $row['time_out'];
//Any Two Input Fields Cant have same Name So...
echo "
<input type='text' value='$row[user_name]' name='user_name_display'>
<input type='text' value=' $row[course]' name='course'>
<input type='text' value=' $time'>
<input type='hidden' value='$row[user_name]' name='user_name'>
<input type='submit' value='submit' name='submit'>
<br>";
}
?>
</form>
<!--YOUR FORM ENDS----------------------------------------------------->
<?PHP
if(isset($_POST['submit'])){
//get course
$course = $_POST['course'];
//get user_name
$user_name = $_POST['user_name'];
//Creating and running mysqli query
$delete = "DELETE FROM online WHERE user_name='$user_name'";
$query = mysqli_query($connect, $delete);
if($query){
//Code to run when user is deleted
header("Location: tutor.php")
}else{
//Error to show when can't delete user
echo "Sorry Can't delete the user";
}
}
?>
Just forget about some semicolons and some minor errors (if there is any), It'll Defiantly Work....
Please Don't Forget to Vote if it works....
The problem is that every input has the same name so you get nothing when you try to obtain POST values. Try a different approach. Maybe you can add a new field (hyperlink) that performs the redirect action and send the parameters of deleting action with GET.
Example:
echo "
<input type='text' value='$row[user_name]' name='user_name'>
<input type='text' value=' $row[course]' name='course'>
<input type='text' value=' $time'>
<a href='Test.php?username=$row[user_name]&course=$row[course]'>delete</a>
<br>";
}
Test.php is the name of your php page.
Then you can query the database by using the the GET value:
$_GET["username"]
I'm trying to do something simple to learn how to do a query and then put the answer into a box. I have a HTML file that looks like this:
<html>
<head>
<title>Test</title>
</head>
<body>
<form action="results.php" method="post">Search: <input name="term" type="text" /><br />
<input name="submit" value="Submit" type="submit" />
<p>Answer: <input name="answer" type="text" /></p>
</form>
</body>
</html>
And the php code is:
<?php
$hostname = 'host.com';
$username = 'ratetable';
$password = 'mypassword';
$term = (int) $_GET['term'];
try
{
$db = new PDO("mysql:host=$hostname;dbname=ratetable", $username, $password);
//echo 'Connected to database<br />';
foreach($db->query('SELECT * FROM rates WHERE mileage<= ' . $term . ' ORDER BY mileage DESC LIMIT 1') as $row) {
echo "<input type='text' name='answer' value='" . $row['ratepermile'] . "'>";
}
}
catch (PDOException $e) {
echo $e->getMessage();
throw($e);
}
?>
So I'm trying to put ratepermile, a field in the database, into the 'answer' text box. What I get is the screen clears, but no form and no result, even after I comment out the 'connected to database' echo line and use something that I know exists in the database.
How can I keep the form on screen and echo to the text box?
Thanks for looking.
Your form is POSTing the data (method="post"), but your PHP script is looking in the $_GET aray.
You need to get the data from $_POST instead.
$term = (int) $_POST['term'];
As well as the above POST issue. If you wish to keep the form on the page and not reload the page you need to look into AJAX.
You can use $_REQUEST in order to avoid these confusions. Whether you use method="post" or method="get", you can fetch the value through this.