I am a beginner at programming. I am learning PHP. What i am trying to do is write a search script in PHP for my project. When i try searching through MySQL database it gives me an error:
Notice: Undefined variable: output in C:\xampp\htdocs\search.php on line 2
I have checked everything on the script and cant see the problem. Have i coded it wrong?
i have checked all possible questions on the forum that relate to my question and they dont seem to gime me the answer i need. please help.
this is the HTML script with the input:
<form action="search.php" method="post" id="search">
<div id="searchfield_div">
<input name="search" id="searchfield" type="text" placeholder="What you looking for?">
<input id="delete_search_button" name="delete button" type="button" value="X">
<input id="search_button" name="search button" type="submit" value="Search">
</div>
</form>
and this is my PHP script:
<?php
//connection script
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "liquihub";
$output = '';
#mysqli_connect("$db_host","$db_user","$db_pass","$db_name") or die("could not connect");
//collection script
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","", $searchq);
$query = mysql_query("SELECT * FROM beverage_db WHERE name LIKE '%$searchq%' OR price LIKE '%$searchq%' OR type LIKE '%$searchq%'") or die ("could not search" );
$count = mysql_num_rows($query);
if ($count == 0) {
$output = 'We not stocking this particular item at present';
}else{
while($row = mysql_fetch_array($query)) {
$bevname = $row['name'];
$bevprice = $row['price'];
$bevtype = $row['type'];
$bevid = $row['id'];
$output .= '<div>'.$bevname.' '.$bevprice.' '.$bevtype.'</div>';
}
}
}
?>
The output script that's meant to put the results on a different page:
<?php print("$output");?>
You have no problem, what you are getting is a Warning not an Error. Your question is duplicated. Here.
Related
On my website I have a file articles.php and on it I have a search field. When I enter the information it redirects me to my search.php which is correct and in the URL I can see it is outputting my result but it's not showing me my results on the search.php body.
The Localhost URL is outputting after I searched "Can you game on Windows visa"
http://localhost/qaa/search.php?search=Can+you+game+on+widows+vista&submit-search=
There is nothing on this page, just an empty box search.php
Connection
<?php
$server = "localhost";
$username = "root";
$password = "";
$db = "Qaa";
$conn = mysqli_connect($server, $username, $password, $db);
?>
articles.php "Where my search bar is located"
<?php
include 'connect.php';
?>
<h1>Front Page</h1>
<h2>All articles:</h2>
<link rel="stylesheet" type="text/css" href="css/article.css">
<div class="article-container">
<form action="search.php">
<input type="text" name="search" placeholder="Search">
<button type="submit" name="submit-search">Get answers</button>
</form>
<?php
$sql = "SELECT * FROM article";
$result = mysqli_query($conn, $sql);
$queryResults = mysqli_num_rows($result);
if ($queryResults > 0){
while ($row = mysqli_fetch_assoc($result)){
echo "<div class='article-box'>
<h3>".$row['a_title']."</h3>
<p>".$row['a_text']."</p>
<hp>".$row['a_date']."</p>
<p>".$row['a_author']."</p>
</div>";
}
}
?>
Search.php "Where the search information should appear after click on 'Get answers button'"
<?php
include 'connect.php';
?>
<link rel="stylesheet" type="text/css" href="css/article.css">
<h1>Search Page</h1>
<div class="article-container">
<?php
if (isset($_POST['submit-search'])){
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM article WHERE a_title LIKE '%$search%' OR a_text
LIKE '%$search%' OR a_author LIKE '%$search%' OR a_date LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
echo "There are ".$queryResult." results!";
if($queryResult > 0){
while ($row = mysqli_fetch_assoc($result)){
echo "<div class='article-box'>
<h3>".$row['a_title']."</h3>
<p>".$row['a_text']."</p>
<hp>".$row['a_date']."</p>
<p>".$row['a_author']."</p>
</div>";
}
}else{
echo "There are no results matching your search! Contact our support so
we can add this or if you have a result, add it, as a result, using the
GIVE ANSWER button!";
}
}
?>
</div>
You are using $_POST['search'] Which is wrong. Because your search string is submitted in get method. So you must use:-
$_GET['search']
Please try this.
<?php
$con=mysqli_connect("localhost","root","","ok_db")or die(mysqli_connect_error());
$output = 'arslan';
// collect
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($con,"SELECT * FROM user_data WHERE fname LIKE '%$searchq%'") or die("Could not search.");
$count = mysqli_num_rows($query);
if($count == 0) {
$output = 'No results found.';
} else {
while($row = mysqli_fetch_array($query)) {
$itemname = $row['fname'];
$description = $row['lname'];
$image = $row['id'];
$output .= '<div>'.$itemname.' '.$description.'</div>';
}
}
}
else{
echo "no" ;
}
?>
<html>
<head>
<title>searching</title>
</head>
<body>
<form action="search.php" method="POST">
<input type="text" name="search" placeholder="Search">
<input type="submit" value=">>" />
</form>
</body>
<?php
print $output;
?>
</html>
This code works fine on my local host (XAMPP) but does not echo anything out in PhpStorm, the isset function not working there and always shows the output "no".
Is something wrong with my PhpStorm settings because it runs fine on localhost?
PHP STORM is an IDE for writing your code and has no effect on this.
I would suggest doing
print_r($_POST['search']);
and making sure it is actually filled in, possibly a typo.
<?php
//connect to server
$connect = mysql_connect("localhost","name","password");
//connect to db
mysql_select_db("complexm_pondlife", $connect);
//query the db
$query = mysql_query("SELECT * FROM frogs");
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<button onclick="show()">SHOW DATA</button>
<p id="clip"style="visibility: hidden">
<?php
WHILE($rows = mysql_fetch_array($query)):
$name = $rows['name'];
$age = $rows['age'];
$sound = $rows['sound'];
$id = $rows['id'];
?>
<?php
echo $id.") "."Name: ";
?>
<form action = "" method = "post">
<input type="text" id="name" value='<?=$name?>'>
<input type="submit" name="update_db" value="Update">
</form>
<?php
echo "Age: "."$age<br><br>";
echo "Sound: "."$sound<br><br>";
echo "___________<br><br>";
endwhile;
?>
</p>
<?php
function upload(){
mysql_query("UPDATE frogs SET name = '$name' WHERE name = '$name'");
}
if(isset($_POST['update_db'])){
echo upload();
}
?>
<script>
function show(){
document.getElementById('clip').style.visibility="visible";
}
</script>
This code gives me: Notice: Undefined variable: name in /home1/complexm/public_html/projects.php on line 70
I dont know why though. So if anyone can tell me i would like to know. If the syntax is wrong please tell me!
This answer is based on your original post and not marking it as an edit, should anyone wonder.
The reason why your upload() function is failing, is because you haven't included the mysql_query() function, along with a few missing parts. (Parts, being quotes/brackets).
function upload(){
mysql_query("UPDATE frogs SET name = '$name' WHERE name = 'TreeFrog'");
}
A word of advice though:
Your present code is open to SQL injection.
Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
also or die(mysql_error()) to mysql_query().
Edit:
To fire up your function using a PHP method, I recommend you change the
<input type="submit" onclick="update()"> to
<input type="submit" name="update_db" value="Update"> and wrapping an isset() around it.
I.e.:
<?php
function upload(){
mysql_query("UPDATE frogs SET name = '$name' WHERE name = 'TreeFrog'");
}
if(isset($_POST['update_db'])){
echo upload();
}
?>
However, you will need <form></form> tags around your form's element(s) and a post method.
<form action = "" method = "post">
<input type="text" id="name" value='<?=$name?>'>
<input type="submit" name="update_db" value="Update">
</form>
Edit #2:
This is a mysqli_ method, please change the DB credentials to match yours if they do not match.
I had to remove the upload() function, it was giving me too much trouble.
A hidden input has been added in the form, which is essential to doing updates like these.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//connect to server
$DB_HOST = 'localhost';
$DB_USER = 'name';
$DB_PASS = 'password';
$DB_NAME = 'complexm_pondlife';
$link = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($link->connect_errno > 0) {
die('Connection failed [' . $link->connect_error . ']');
}
//query the db
$query = mysqli_query($link,"SELECT * FROM frogs");
?>
<button onclick="show()">SHOW DATA</button>
<p id="clip"style="visibility: hidden">
<?php
WHILE($rows = mysqli_fetch_array($query)):
$name = $rows['name'];
$age = $rows['age'];
$sound = $rows['sound'];
$id = $rows['id'];
?>
<?php
echo $id.") "."Name: ";
?>
<form action = "" method = "post">
<input type="text" id="name" name="thename" value="<?php echo $name; ?>">
<input type="hidden" name="the_id" value="<?php echo $id; ?>">
<input type="submit" name="update_db" value="Update">
<br>
</form>
<?php
echo "Age: "."$age<br><br>";
echo "Sound: "."$sound<br><br>";
echo "___________<br><br>";
endwhile;
?>
</p>
<?php
if(isset($_POST['update_db'])){
$theid = stripslashes($_POST['the_id']);
$theid = mysqli_real_escape_string($link,$_POST['the_id']);
$thename = stripslashes($_POST['thename']);
$thename = mysqli_real_escape_string($link,$_POST['thename']);
$results= mysqli_query($link, "UPDATE frogs SET name = '$thename' WHERE id = '$theid'");
}
?>
<script>
function show(){
document.getElementById('clip').style.visibility="visible";
}
</script>
You can also redirect to the same page by adding this at the top:
<?php
ob_start();
?>
then adding this after your query:
if($results){
header("Location: http://www.yoursite.com/update_frogs.php");
}
I have that people can add team names to my MySQL table. Now I want them to edit it. I have tried several tutorials but i can't figure it out. I like to know what i am doing wrong.
This is my admin.php:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
if(isset($_POST['team'])){
$team = $_POST['team'];
$ID = $_POST['id'];
$query = mysql_query("SELECT * FROM e2teams WHERE Team='$team' and ID='$ID'");
if(mysql_num_rows($query) > 0 ) { //check if there is already an entry for that username
echo "$team bestaat al!";
}
else{
mysql_query("INSERT INTO e2teams (Team) VALUES ('$team')");
header("location:e2admin.php");
}
}
mysql_close();
?>
<html>
<body>
<h1>Add teams</h1>
<form action="e2admin.php" method="POST">
<input type="text" name="team" placeholder="Team naam" /><br>
<input type="submit" value="Toevoegen" />
</form>
<?php
$table = "e2teams";
$sql = "SELECT * FROM e2teams";
$result = mysql_query($sql, $dbhandle);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)) {
echo $row['Team']. "<a href='edit.php?edit=$row[1]'>Bewerk</a><br>";
}
}
?>
</body>
</html>
The add teams works. but the edit button doesn't work yet. If I click on edit I go to the edit.php page; here I want to add the new name and need the Team to change in the MySQL row.
This is my edit.php:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
if( isset($_GET['edit'])) {
$id = $_GET['edit'];
$res = mysql_query("SELECT * FROM e2teams");
$row= mysql_fetch_array($res);
}
if (isset ($_POST['nieuwenaam'])) {
$newname = $_POST['nieuwenaam'];
$id = $_POST['id'];
$sql = "UPDATE e2teams SET Team='$newname' WHERE id='$id'";
$res = mysql_query($sql) or die ("Fout bij updaten".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=edit.php'>";
}
?>
<html>
<body>
<form action="edit.php" method="POST">
<input type="text" name="nieuwenaam" placeholer="test" /><br>
<input type="hidden" name="id" placeholder="idnaam" value"s" /><br>
<input type="submit" value="Update" />
</form>
</body>
</html>
I also like to know how to delete team names but this is maybe for a next question.
This should work:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
$id = intval($_GET['edit']);
if($id > 0) {
$res = mysql_query("SELECT * FROM e2teams WHERE `id` = $id");
$row= mysql_fetch_array($res);
$newname = mysql_real_escape_string($_POST['nieuwenaam']);
if (!empty($newname)) {
$sql = "UPDATE e2teams SET Team='$newname' WHERE id=$id";
$res = mysql_query($sql) or die ("Fout bij updaten".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=edit.php?edit=$id'>";
}
}
?>
<form action="edit.php?edit=<?= $id; ?>" method="POST">
<input type="text" name="nieuwenaam" placeholer="test" /><br>
<input type="submit" value="Update" />
</form>
</body>
</html>
Edit: Also, about the intval() and mysql_real_escape_string(). Since you were using $_GET without any filter, I've added intval() function on it. Without filtering $id you could've been easily attacked by some sort of e.g. SQL Injection. Same with mysql_real_escape_string(). You might read about this filter function in php manual. For further study I recommend changing mysql_ functions to PDO or mysqli prepared statements. Happy coding!
Check your edit form. You have to put the value attribute like this value="s" no like value"". I think thats all.
I assume when they click on the edit link it's passing the id of the team so the edit.php select should be something like:
$id = (int)$_GET['edit'];
if (!empty($id))
{
$sql = "SELECT * FROM e2teams WHERE id='$id'";
$result = mysqli_query($sql);
$row = mysql_fetch_assoc($res);
}
//... keep the rest of code as is
Now you need to change the HTML form to:
<form action="edit.php?edit=<?php echo $row['id'] ?>" method="POST">
<input type="text" name="nieuwenaam" placeholer="test" value="<?php echo $row['Team'] ?>" /><br>
<input type="hidden" name="id" placeholder="idnaam" value"<?php echo $row['id'] ?>" /><br>
<input type="submit" value="Update" />
</form>
So if i type text to my textbox, then I press submit button, wich sends data to update.php and update.php sends data to my database, then update.php redirects back to edit.php and the textbox whole text has gone downwards, any ideas ?
Edit.php
<html>
<head></head>
<body>
<form method="post" action="update.php">
Meist<br>
<textarea style="resize:none" cols="100" rows="10" method="post" type="text" id="meist" name="meist"><?php
include_once("connect.php");
$sql = 'SELECT meist FROM content WHERE id=1';
mysql_select_db('fava');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "{$row['meist']}";
}
mysql_close($conn);
?>
</textarea><br>
<input type="submit" value="salvesta"/>
</form>
</body>
</html>
update.php
<?php
// configuration
$dbhost = "localhost";
$dbname = "fava";
$dbuser = "root";
$dbpass = "";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$meist =$_POST["meist"];
$id = 1;
// query
$sql = "UPDATE content SET meist=? WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($meist,$id));
echo "Edukalt salvestatud";
header('Refresh: 2; URL=http://localhost/php_sandbox/edit.php');
?>
If any questions then shoot, because it is kind of hard to explain.
For starters, get all that PHP code OUT of the content area. Since you are including the connect.php file, it is literally putting the contents of connect.php inside the textarea item. If there are new line characters in connect.php, like at the end of the file, it will create a blank line in the textarea input.
<html>
<head></head>
<body>
<?php
include_once("connect.php");
$sql = 'SELECT meist FROM content WHERE id=1';
$text = '';
mysql_select_db('fava');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$text .= "{$row['meist']}";
}
mysql_close($conn);
?>
<form method="post" action="update.php">
Meist<br>
<textarea style="resize:none" cols="100" rows="10" method="post" type="text" id="meist" name="meist">
<?php echo $text; ?>
</textarea><br>
<input type="submit" value="salvesta"/>
</form>
</body>
</html>
Note that I am created a blank $text variable and filling it with the data you want to have in the field and when all the work is done, we are echoing only that item in the content.
This cleans up the code, makes it clear what you are doing and makes sure stray new line characters are being implanted where you don't want them.