Replacing PHP "undefined variable" error? - php

so basically I want to make an online dictionary, the word to be searched for is introduced by an input, and I want to make so that if it can't find the word+definition in db to say a message like "We couldn't find any definition" or something like that, in my code because it can't find it , it ways "undefined variable"
<?php
include ("header.php");
$search = $_POST['se'];
include ("connect.php");
$dictionary=mysqli_query($con,"SELECT * FROM `dictionary` WHERE word = '$search'");
while($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
}
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
include ("footer.php");
?>
P.S.: I know my code is vulnerable to SQLi , but I'll fix that later.

try wrapping the undefined vars in isset
if (isset($word) && isset($description)) {
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
}
else {
echo "Nothing found";
}
Same goes for $search = $_POST['se'];
if(!isset($_POST['se'])) {
echo "Nothing found";
exit;
}

if($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
} else {
echo "$search not found";
}

while($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
}
if(!empty($word) && !empty($description)){
echo '<div class=\"webResult\">';
echo '<h2>$word</h2>';
echo '<p>$description</p>';
echo '</div>";
}else{
echo 'could not find your word';
}
include ("footer.php");
?>
You have to validate your variables if its have value or not

The variables $word and $description are first created inside the while loop. This means that they do not have any scope outside it. This should be the most probable cause, since you are getting a variable not defined error.
There are a couple of options here.
One, you could create these variables outside the while loop, and then assign them new values as you are doing now. Here is what your code might look like, if you choose to do it this way:
$search = $con->escape_string($_POST['se']);
$dictionary = $con->query("SELECT * FROM `dictionary` WHERE word = '$search'");
$word = "";
$description = "";
while($row = $dictionary->fetch_assoc())
{
$word = $row['word'];
$description = $row['definition'];
}
if (!empty($word) && !empty($description))
{
echo '<div class="webResult"><h2>' . $word . '</h2><p>' . $description . '</p></div>';
}
else
{
echo "We couldn't find any definition";
}
This will work for you if you have multiple results in the returned mysqli_resource, and want to use the last in the list.
Two, if you are likely to get only one result returned, or if you just want to use the first result in the list, you can have the echo statement inside an if statement that checks if a valid result is returned. For example:
$search = $con->escape_string($_POST['se']);
$dictionary = $con->query("SELECT * FROM `dictionary` WHERE word = '$search'");
$word = "";
$description = "";
$row = $dictionary->fetch_assoc();
if($row)
{
$word = $row['word'];
$description = $row['definition'];
if (!empty($word) && !empty($description))
{
echo '<div class="webResult"><h2>' . $word . '</h2><p>' . $description . '</p></div>';
}
else
{
echo "We couldn't find any definition";
}
}
Note:
In the above examples, we use !empty() to check the variables. This is because isset() is pointless here, since we have already created (set) the variables ourselves.
Things to read up:
Scope of variables - http://php.net/manual/en/language.variables.scope.php
empty() function - http://php.net/manual/en/function.empty.php
Object oriented mysqli - http://php.net/manual/en/mysqli.quickstart.dual-interface.php

Try this:
include ("header.php");
$search = $_POST['se'];
include ("connect.php");
$dictionary=mysqli_query($con,"SELECT * FROM `dictionary` WHERE word = '$search'");
while($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
}
if(isset($word)){
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
}
else{
echo "We couldn't find any definition";
}
include ("footer.php");

Related

Variables inside while loop

I have following code, I try to style output with CSS, but I have small problem, my code show all database entries, which is OK, but when I remove comment from WHILE loop, and comment echo, its showing only first row of entries from database.how can I do same thing and show multiple results from database by use variables in While Loop?:
<?php
error_reporting(0);
require 'connect.php';
$search = $_POST['search'];
//$checkout = $_POST['checkout'];
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM area where destination='{$search}'";
$result = mysqli_query($conn, $sql);
if($count = $result->num_rows) {
echo '<p>', $count, '</p><br><br>';
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row['destination'],' ',$row['place'], $row['tosee'], '<br>';
/$destination =$row["destination"];
//$place =$row["place"];
/$destination =$row["destination"];
//$place =$row["place"];
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
and inside my HTML file:
location: <?php echo $destination; ?>
places: <?php echo $place ; ?>
views: <?php echo $tosee; ?>
Do this...
$out .= $row['destination'].' '.$row['place'].' '.$row['tosee']. '<br>';
Then you can use the $out variable anywhere else...
Even for these...
$destination .= $row["destination"];
$place .= $row["place"];
Since well....are in the while loop
I found a few small errors, you had a ',' instead of a '.' to concatenate a variable.
if($count = $result->num_rows) {
echo '<p>' . $count . '</p><br><br>';
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row['destination'].' '.$row['place'].' '.$row['tosee']. '<br>';
//$destination =$row["destination"];
//$place =$row["place"];
//$destination =$row["destination"];
//$place =$row["place"];
}
}
and for php comments it is: //

Echo from function php

hello i want to echo a result from functions
code
function AboutUser()
{
global $Connection;
$GetUsers = mysqli_query($Connection, "SELECT * FROM users WHERE username='GentritAbazi'");
while($Show_Users = mysqli_fetch_array($GetUsers))
{
return $SignupDate = $Show_Users['signup_date'];
$Email = $Show_Users['email'];
$Gender = $Show_Users['gender'];
$Country = $Show_Users['country'];
}
}
Now my code not work
AboutUser()
how to do this ?
function AboutUser()
{
global $Connection;
$GetUsers = mysqli_query($Connection, "SELECT * FROM users WHERE username='GentritAbazi'");
while($Show_Users = mysqli_fetch_array($GetUsers))
{
echo $Show_Users['signup_date'];
echo $Show_Users['email'];
echo $Show_Users['gender'];
echo $Show_Users['country'];
}
}
Because you return $SignupDate = $Show_Users['signup_date'];
You want to echo, not return.
Let's use this in the while loop.
echo $Show_Users['signup_date'] ."<br>";
echo $Show_Users['email'] ."<br>";
echo $Show_Users['gender'] ."<br>";
echo $Show_Users['country'] ."<br>";
echo '<hr>'
But that is most elegant, if you collect all the data into a big array, and loop through that array.
return mysqli_fetch_all($GetUsers);
Based on the comments, and after I realized, you probably want to get one users data, here is the updated code:
function AboutUser($userName) {
global $Connection;
$res = mysqli_query($Connection, "SELECT * FROM users WHERE username='". mysqli_real_escape_string($Connection, $userName)."'");
return mysqli_fetch_row($res);
}
$userData = AboutUser('GentritAbazi');
if (!empty($userData)) {
echo $userData['signup_date'] ."<br>";
echo $userData['email'] ."<br>";
echo $userData['gender'] ."<br>";
echo $userData['country'] ."<br>";
}
You can have the function echo the value instead of returning it, like mentioned above.
Or you can use special tags e.g.
<?=
AboutUser();
?>
Hopefully this works

PHP and mysqli to modify CSS

I was experimenting if I could use a mySQL database to store CSS settings. I set up a simple database "colors" with one table "color" that had simple structure tag and color columns. In that, one row is h1 => red.
<?php
//function to dynamically change CSS
$tag = 'h1';
$q = "SELECT * FROM `colors` WHERE `tag`='" . $tag . "'" ;
echo $q . "<br>";
$query = mysqli_query($link, $q);
if ($row = mysqli_fetch_assoc($query))
{
echo $row['color'];
} else
{
echo "error - no such tag";
}
?>
When I tried to convert to a function, the code does not work at all.
<?php
//function to dynamically change CSS
function getCSS($tag)
{
$tag = 'h1';
$q = "SELECT * FROM `colors` WHERE `tag`='" . $tag . "'" ;
echo $q . "<br>";
$query = mysqli_query($link, $q);
if ($row = mysqli_fetch_assoc($query))
{
echo $row['color'];
} else
{
echo "error - no such tag";
}
}
getCSS('h1');
?>
Help please?
My guess is that in
$query = mysqli_query($link, $q);
$link goes out of scope and is empty. You should pass it to the function as well.
For the record: using $tag without escaping could be an sql injection attack possibility.
in function, there is no $link, you shoud define it as a global variable.
At the start of your function add a reference to your global DB link:
function getCSS($tag) {
global $link;
...
This should work:
<?php
$link = mysqli_connect('server_host', 'user', 'password', 'database') OR die('Could not connect because: '.mysqli_connect_error());
//function to dynamically change CSS
function getCSS($link, $tag){
$q = 'SELECT * FROM colors WHERE tag = "' . $tag . '"' ;
$r = mysqli_query($link, $q);
if(mysqli_num_rows($r)>0){ // check if there are results
while($row = mysqli_fetch_assoc($r)){
//echo '<pre>';
//print_r($row); // print the result array for debugging
//echo '</pre>';
echo $row['color'] . '<br />';
}
return $row;
} else { // if no result is found
echo 'No such tag';
}
}
// test it:
echo '<br />if tag is h1<br />';
getCSS($link, 'h1');
echo '<br />if tag is h2<br />';
getCSS($link, 'h2');
?>

MySQL, while Loop & comparison with in_array

here is the code:
$sql = "SELECT * FROM example";
$query = mysql_query($sql);
while ($array = mysql_fetch_array($query)) {
if (in_array($array['ipsum'], $page1)) {echo "<h2>correct</h2>"; break;}
else {echo "<h2>not correct</h2>";} }
echo "<div id=\"nucleo\"><h3>lorem ipsum</h3><h1>";
echo $page1;
echo "</h1>";
I have a table with 2 rows in the database: first one is lorem the second one is ipsum (both are INT).
The table is manually compiled when it is needed.
What I want to do is to get the second row (ipsum) and create an array. I don't need to echo values of the array, but I need to compare it with a variable ($page1. this variable is a integer number and it changes continuously).
How could I fix it?
I think this should do what you are after. You should look into switching from the mysql functions/driver to the mysqli or PDO drivers.
<?php
$page1 = (int)$page1;//force $page1 to be an int to avoid SQL injections
$sql = "SELECT * FROM example where ipsum = " . $page1;
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0) {
echo "<h2>correct</h2>";
} else {
echo "<h2>not correct</h2>";}
}
echo '<div id="nucleo">
<h3>lorem ipsum</h3>
<h1>' . $page1 . '</h1>';
http://php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated
http://php.net/manual/en/function.mysql-num-rows.php
You are using in_array() to compare two integer values. you should simply use the === operator like so:
$sql = "SELECT * FROM example";
$query = mysql_query($sql);
while ($array = mysql_fetch_array($query)) {
if ($array['ipsum'] === $page1) {
echo "<h2>correct</h2>";
break;
} else {
echo "<h2>not correct</h2>";
}
}
echo "<div id=\"nucleo\"><h3>lorem ipsum</h3><h1>";
echo $page1;
echo "</h1>";
I fixed it this way:
$array = array();
while ($row = mysql_fetch_array($query)) {
array_push($array, $row["ipsum"]);
}
if (in_array($page1, $array)) {echo "correct";}
else {echo "not correct"; }
I realized by using print_r that the array was not really how I though it was. This way above use all the row of a colums to compose the array... array([0] => row1 [1] => row2 and so on.
Thanks everyone for the help...I apologize for not being very clear about my problem.

creating a page that displays ID info on a template

Updated with suggestion by others but still seem to be stuck.
I'm using this php code here to display info from my database using the ID. I created a link on my main page that looks like this.
<h1><?php echo $row_getDisplay['title']; ?></a></h1>
I have so when they click on the title of the article that it takes them to my php fiel which I named fetch.php and the code below is what is in there. I have built this around someone else's work. For some reason I can't get passed the first "else" statement. so I keep getting "you must select a valid location" I'm fairly new to php so I don't really understand why the code is failing.
<?php require_once('Connections/XXXXXX.php'); ?>
<?php
if (isset($_GET['id']) == false) // check if id has been set
{
echo "You must select a location"; // if not, display this error
exit;
} else {
$id = (int) $_GET['id'];
if (is_numeric($id) == false)
**{
echo "You must select a valid location.";
} else {**
mysql_select_db($database_XXXXXX, $XXXXXX);
$query = MYSQL_QUERY("SELECT * FROM news WHERE post_id ");
if (MYSQL_NUM_ROWS($query) == "1")
{
$fetch = MYSQL_FETCH_ARRAY($query); // set $fetch to have the values from the table
echo "Title: " . $fetch['title'] . "<BR>"; // output the info
echo "Blog: " . $fetch['blog_entry'] . "<BR>"; // etc...
echo "Author: " . $fetch['author'] . "<BR>"; // etc...
} else {
echo "No match in database found."; // if no match is found, display this error
}
}
}
Any help is appreciated. If you are able to find a better solution for me that would be great.
You shouldnt use $HTTP_GET_VARS its deprecated and unless its turned on it wont be populated. use $_GET instead.
if (isset($_GET['id']) == false)
Use $_GET for your if statement:
if (isset($_GET['id']) == false)
Also, you need to convert your $_GET value to an integer, because it is currently a string.
Right after that if statement above, in the else, put this:
$id = (int) $_GET['id'];
That way your is_numeric() will work properly.
Try this;
<?php
require_once('Connections/XXXXXX.php');
if (isset($_GET['id'])) // check if id has been set
{
$id = $_GET['id'];
if (is_numeric($id) == false)
{
echo "You must select a valid location.";
} else {
mysql_select_db($database_XXXXXX, $XXXXXX);
$query = MYSQL_QUERY("SELECT * FROM news WHERE locationid = 'news.post_id' ");
if (MYSQL_NUM_ROWS($query) == "1")
{
$fetch = MYSQL_FETCH_ARRAY($query); // set $fetch to have the values from the table
echo "Title: " . $fetch['title'] . "<BR>"; // output the info
echo "Blog: " . $fetch['blog_entry'] . "<BR>"; // etc...
echo "Author: " . $fetch['author'] . "<BR>"; // etc...
} else {
echo "No match in database found."; // if no match is found, display this error
}
}
}
else{
echo "You must select a location"; // if not, display this error
exit;
}
?>
Also, I need a clarification about news.post_id, from where are you grabbing this?

Categories