I am sending data to a PHP script using an android app. The following is the PHP script.
telejoke.php:
<?php
include 'JokeValidation.php';
include 'DBConnect.php';
$username = $_POST['username'];
$joke = $_POST['joke'];
$dbname = 'Telejoke';
mysql_select_db($dbname);
if (validate()){
$query = "INSERT INTO jokes (username, joke) VALUES ('$username','$joke')";
mysql_query($query) or die('Error, insert query failed');
}
mysql_close($conn);
?>
jokevalidation.php:
<?php
include 'DBConnect.php';
$dbname = 'telejoke';
mysql_select_db($dbname);
function validate(){
if ($joke == null) return false;
else if($username == null) return false;
return true;
}
?>
For some reason, the PHP script will put the data into the database when I take out if ($joke == null) return false; and else if($username == null) return false;. But when I put these statements into the PHP code, it seems that validate returns false. This is weird because $username and $joke will go to my database when I take out these statements meaning they cannot be null!.
Help is appreciated. Thanks.
Your validate function needs to have access to the $joke and $username objects.
You can also get access to these variables by using the following inside your validate method:
However, it is better to declare what you’re validating rather than relying on those variables being declared and set elsewhere in your code. Using global might fail silently for other reasons.