I've been wondering how to avoid an error when a page is first loaded, and it holds a form that a function/operation requires.
Problem: I'm getting an error, because the form has not been submitted and the variables inside are needed to run the rest of the script.
Bear with my wording, I'm obv a beginner.
But let's take what I'm working with for example, It's all on the same page.
IF this is the first time my page has been loaded and I do not enter anything into my form, i get an Unidentified Index: "$variable" that I use for my form.
Right now I'm running through a simple strpos tutorial that I basically turned into a search engine bought at walmart.
Index.php
<html>
<head>
<title> Project # </title>
<link href="../css/stylesheet.css" rel="stylesheet" type="text/css">
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<input type="text" placeholder="Search" name="search">
<input type="submit" name="submit" value="search">
</form>
<?php
$article = " Nulla mauris odio, vehicula in, condimentum sit amet, tempus id, metus. Donec at nisi sit amet felis blandit posuere. Aliquam erat volutpat. Cras lobortis orci in quam porttitor cursus. Aenean dignissim. Curabitur facilisis sem at nisi laoreet placerat. Duis sed ipsum ac nibh mattis feugiat. Proin sed purus. Vivamus lectus ipsum, rhoncus sed, scelerisque sit amet, ultrices in, dolor. Aliquam vel magna non nunc ornare bibendum. Sed libero. Maecenas at est. Vivamus ornare, felis et luctus dapibus, lacus leo convallis diam, eget dapibus augue arcu eget arcu.";
echo $article;
$search = $_POST['search'];
if(!isset($_SERVER['submit'])){
if(strpos($article, $search) !== false){
echo "<br> We found what you were looking for.. ";
}
else{
echo " <br> nope, remember we probably need exact matches here.";
}
}
else {
echo "<br> form is not set ";
}
?>
</body>
</html>
$_POST["search"]
will initially not exist, so you need to check if $_POST["search"]
is set.
$article = " Nulla mauris odio, vehicula in, condimentum sit amet, tempus id, metus. Donec at nisi sit amet felis blandit posuere. Aliquam erat volutpat. Cras lobortis orci in quam porttitor cursus. Aenean dignissim. Curabitur facilisis sem at nisi laoreet placerat. Duis sed ipsum ac nibh mattis feugiat. Proin sed purus. Vivamus lectus ipsum, rhoncus sed, scelerisque sit amet, ultrices in, dolor. Aliquam vel magna non nunc ornare bibendum. Sed libero. Maecenas at est. Vivamus ornare, felis et luctus dapibus, lacus leo convallis diam, eget dapibus augue arcu eget arcu.";
echo $article;
if(isset($_POST["search"])) {
$search = $_POST['search'];
if(!isset($_SERVER['submit'])){
if(strpos($article, $search) !== false){
echo "<br> We found what you were looking for.. ";
}else{
echo " nope, remember we probably need exact matches here.";
}
}else {
echo "<br> we couldn't find it ";
}
}