not returning sufficient rows - php

What I'm trying to figure out here is how to access the different array values that I need. I have the following query and it returns this for an array when the print_r() is applied. For some reason it only does the first row from the db table. It should return a whole another row.
<?php
session_start();
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
//Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = "no";
if((empty($_POST['answer1'])) || (trim($_POST['answer1'])=="") || ($_POST['answer1'] == NULL) || (!isset($_POST['answer1']))){$errors = "yes";}
if((empty($_POST['answer2'])) || (trim($_POST['answer2'])=="") || ($_POST['answer2'] == NULL) || (!isset($_POST['answer2']))){$errors = "yes";}
// Error checking, make sure all form fields have input
if ($errors == "yes") {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => true, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc,$_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc,$_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc,$_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc,$_POST['question1']);
$question2 = mysqli_real_escape_string($dbc,$_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if ($answer == $answerPost) {
} else {
$errors = "yes";
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => true, 'message' => $message);
}
}
} else {
$errors = "yes";
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => true, 'message' => $message);
}
}
}
//Output the result
$output = json_encode($output);
echo $output;
?>

Because you just fetch the first one, where you should loop on the result set instead:
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '$userID'";
$result = mysqli_query($dbc,$query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
print_r($row);
}
}
By the way, you should be using prepared statements to avoid SQL injection.

You need to wrap your fetch in a loop. e.g.
if (mysqli_num_rows($result) > 0)
{
while (($row = mysqli_fetch_array($result)) !== false)
{
if ($row['answer'] == $answerPost)
{
// $row matches what we're looking for
}
else
{
$errors = "yes";
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => true, 'message' => $message);
}
print_r($row);
}
}

Related

PHP API returning wrong response for android app

I am creating a API for android developer in PHP in which he want to delete some values from database and want to show a message after that.
Now the problem is this data is deleting successfully but this API always shows else part message after complete the process. If I remove the else part its return the null which crash the android app. So I just want to give a proper json message to the android developer
Here is the code which I am trying
if($clear_my_property == "yes" && $clear_my_requirement == "yes" && $all_of_these == "yes" && $user_name_id == $user_name_id1)
{
$tables_count = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_count as $table_count)
{
$user_count = mysql_query("select * from $table_count where user_name = '$user_name'");
$total_user_count = mysql_num_rows($user_count);
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
if($user_sql)
{
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}
}
}
else
{
$response['success'] = 0;
$response['user']['error_msg'] = 'Record Not Found!';
}
}
}
I know there is something wrong with this logic. But I need expert advise where my logic is wrong and what I have to do make it success
Problem with your original code, is that you are setting success/failure inside the loop. One of the four table may/may not contain the username. And if the last table don't have that, then as per your logic you are getting "record not found" even if previous iteration of the loop deleted data from the tables where username exists.
<?php
$conn = mysqli_connect(.....);
if($clear_my_property == "yes" && $clear_my_requirement == "yes" && $all_of_these == "yes" && $user_name_id == $user_name_id1) {
$tables_count = array("property_for_sale","property_for_rent","cpo_post_requirements");
$userHistoryDeleted = 0;
foreach($tables_count as $table_count) {
//if history is found, then it will be deleted otherwise not
mysql_query("delete from $table_count where user_name = '$user_name'");
if(mysqli_affected_rows($conn)) {
$userHistoryDeleted = 1;
}
}
$msg = 'Record Not Found!';
if($userHistoryDeleted) {
$msg = 'Clear Successfully All History!';
}
$response['success'] = $userHistoryDeleted;
$response['user']['error_msg'] = $msg;
}
Change your code :
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
if($user_sql)
{
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}
}
}
else
{
$response['success'] = 0;
$response['user']['error_msg'] = 'Record Not Found!';
}
to this one
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
}
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}

else statement content wont show?

Currently, my problem continues to persist as I want to display errors for existing accounts or a success message if the user creates a non-already existing account. For some odd reason, even if the sign-up is successful, it still display the errors? Is there something that I am doing wrong? The two if statements still run even if they are false??? I am not understanding...
if ($db_found) {
$uSQL = "SELECT * FROM login WHERE username = '$username'";
$uresult = mysql_query($uSQL);
$unum_rows = mysql_num_rows($uresult);
$eSQL = "SELECT * FROM login WHERE email = '$email'";
$eresult = mysql_query($eSQL);
$enum_rows = mysql_num_rows($eresult);
if ($unum_rows > 0) {
echo '<div class="error-message"><li>Username Already Exists</li></div>';
}
if ($enum_rows > 0) {
echo '<div class="error-message"><li>Email Already Exists</li></div>';
}
else {
echo '<div class="success-message">successfully</div>';
}
}
Personally I would combine the queries - and simplify the logic ( and escape your input )
if ($db_found) {
$sql = "SELECT * FROM login WHERE username = '{mysql_real_escape_string($username)}' OR email = '{mysql_real_escape_string($email)}'";
$result = mysql_query($sql);
if( mysql_num_rows($result) ){
while(false !== ($row = mysql_fetch_assoc($result))) {
if($row['username'] == $username ){
echo '<div class="error-message"><li>Username Already Exists</li></div>';
}
if($row['email'] == $email) {
echo '<div class="error-message"><li>Email Already Exists</li></div>';
}
}
}else{
echo '<div class="success-message">successfully</div>';
}
}
This might help you
$enum_rows = mysql_num_rows($eresult);
if($unum_rows < 1)
{
echo "Username is available";
}
else
{
echo '<div class="error-message"><li>Username Already Exists</li></div>';
}
if($enum_rows < 1)
{
echo '<div class="success-message">successfully</div>';
}
else
{
echo '<div class="error-message"><li>Email Already Exists</li></div>';
}

trying to convert mysql select statement to PDO

I'm trying to convert from an old MySQL library to PDO.
In order to read the data with my old MySQL code I use:
$assoc = mysql_fetch_assoc($exeqr);
With PDO I'm trying to do that with a foreach like I have on my code using PDO, but its not working...
Can you see something wrong here??
My OLD ode using MySQL:
<?php
if(isset($_POST['sendLogin']))
{
$f['email'] = mysql_real_escape_string($_POST['email']);
$f['pass'] = mysql_real_escape_string($_POST['password']);
if(!$f['email'] || !valMail($f['email']))
{
echo 'Email empty or invalid';
}
else if(strlen($f['pass']) <8 || strlen($f['pass'])>12)
{
echo 'pass must have between 8 and 12 chars!';
}
else
{
$autEmail = $f['email'];
$autpass = $f['pass'];
$query = "SELECT * FROM users where email= '$autEmail'";
$exeqr = mysql_query($query) or die(mysql_error());
$assoc = mysql_fetch_assoc($exeqr);
if(mysql_num_rows($exeqr) == 1 )
{
if($autEmail == $assoc['email'] && $autpass == $assoc['pass'])
{
$_SESSION['assoc'] = $assoc;
header('Location:'.$_SERVER['PHP_SELF']);
}
else
{
echo ' wrong password';
}
}
else
{
echo 'email does no exist';
}
}
}
And the new code I am trying to convert using PDO:
<?php
if(isset($_POST['sendLogin']))
{
$f['email'] = mysql_real_escape_string($_POST['email']);
$f['pass'] = mysql_real_escape_string($_POST['password']);
if(!$f['email'] || !valMail($f['email']))
{
echo 'Email empty or invalid';
}
else if(strlen($f['pass']) <8 || strlen($f['pass'])>12)
{
echo 'pass must have between 8 and 12 chars!';
}
else
{
$autEmail = $f['email'];
$autpass = $f['pass'];
$searchEmail = $pdo->prepare("SELECT * FROM users where email=:email");
$searchEmail->bindValue(":email,$autEmail");
$searchEmail->execute;
$num_rows = $searchEmail->fetchColumn();
$result = $searchEmail->fetch(PDO::FETCH_OBJ);
if($num_rows == 1)
{
if($autEmail == $result['email'] && $autpass == $result['pass'])
{
$_SESSION['result'] = $result;
header('Location:'.$_SERVER['PHP_SELF']);
}
else
{
echo ' wrong password';
}
}
else
{
echo 'email does no exist';
}
}
}
Warning: PDOStatement::bindValue() expects at least 2 parameters, 1 given in $searchEmail->bindValue(":email,$autEmail");
You need to move your ", currently it's including the variable as well as the parameter name resulting in you not passing in the variable to bind to said parameter (which is why you are getting the error telling you you haven't passed in enough arguments).
$searchEmail = $pdo->prepare("SELECT * FROM users where email = :email");
$searchEmail->bindValue(":email", $autEmail);
Notice: Undefined property: PDOStatement::$execute in $searchEmail->execute;
You've forgotten the () brackets from execute(), so PHP is looking for the property of the PDO class called execute instead of the function call.
$searchEmail->execute();
(thanks Prix)
Edit
Your question is now about how to replace this:
$assoc = mysql_fetch_assoc($exeqr);
... with a PDO equivalent. In the manual, there is an example:
$assoc = $searchEmail->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
Note: fetchAll() is for fetching multiple results. If you're expecting only one result (which you might be, but you aren't limiting your query so it's feasible to return multiple results), you should just use fetch():
$assoc = $searchEmail->fetch(PDO::FETCH_ASSOC);

PHP Comparing variables returns false every time

I have this script that checks a submitted form. It checks if all fields are all filled out, and checks if the user has submitted the form before. It also checks if the entered data is already in the database or not. When I try to check if the entered data is in the database, it always returns false. My question is: How can I efficiently check if the POST values are the same?
Code:
<?php
error_reporting(E_NOTICE ^ E_ALL);
$Name = $_POST['name'];
$ID = $_POST['id'];
$Topic_1 = $_POST['1'];
$Topic_2 = $_POST['2'];
$Topic_3 = $_POST['3'];
$Topic_4 = $_POST['4'];
$Topic_5 = $_POST['5'];
$Topic_6 = $_POST['6'];
$Topic_7 = $_POST['7'];
$Topic_8 = $_POST['8'];
$Topic_9 = $_POST['9'];
$Topic_10 = $_POST['10'];
$Topic_11 = $_POST['11'];
$Topic_12 = $_POST['12'];
$Topic_13 = $_POST['13'];
$Topic_14 = $_POST['14'];
$Topic_15 = $_POST['15'];
$IP = $_SERVER['REMOTE_ADDR'];
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Check = 'SELECT * FROM Submissions WHERE School_ID = "'.$ID.'" AND IP = "'.$IP.'"';
$Insert = 'INSERT INTO Submissions (Name, School_ID, Topic_1, Topic_2, Topic_3, Topic_4, Topic_5, Topic_6, Topic_7, Topic_8, Topic_9, Topic_10, Topic_11, Topic_12, Topic_13, Topic_14, Topic_15, IP) VALUES ("'.$Name.'", "'.$ID.'", "'.$Topic_1.'", "'.$Topic_2.'", "'.$Topic_3.'", "'.$Topic_4.'", "'.$Topic_5.'", "'.$Topic_6.'", "'.$Topic_7.'", "'.$Topic_8.'", "'.$Topic_9.'", "'.$Topic_10.'", "'.$Topic_11.'", "'.$Topic_12.'", "'.$Topic_13.'", "'.$Topic_14.'", "'.$Topic_15.'", "'.$IP.'")';
if($Name && $ID != "")
{
if($Result = $Connect->query($Check))
{
$Rows = $Result->num_rows;
if($Rows == 0)
{
if($_POST != $_POST)
{
if($Go = $Connect->prepare($Insert))
{
if($Go->execute())
{
echo 'Thanks';
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'No Two Values Can Match.';
}
}
else
{
echo 'You Cant Vote Twice.';
}
$Result->close();
}
else
{
echo 'There Was An Error.';
}
}
else
{
echo 'Please Fill Out All Fields';
}
$Connect->close();
Your if statement should look like
if($name != "" && $check != "")
Here's the error:
if($_POST != $_POST)
You do probably want to compare the result from the db with the $_POST instead.
$Row = $Result->fetch_assoc();
if($Row != $_POST)
Prior to doing a comparison use var_dump() on the variables to check what they actually contain.
var_dump($Name);
var_dump($ID);
exit();
Then check for a negative or positive match.
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
You can even spoof that in a separate file.
<?php
$Name = 'Bob';
$ID = ''; // or use 0 or any test you want
var_dump($Name);
var_dump($ID);
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
Isolating problems like this will help you develop incrementally, get something working, then add more lines till you arrive at your destination.
To check if not two POST values are the same:
array_diff($_POST, array_unique($_POST));
What you looking for is following
$_POST['1'] = 'a';
$_POST['2'] = 'b';
$_POST['3'] = 'c';
$_POST['4'] = 'a';
$_POST['5'] = 'd';
$results = array_unique($_POST);
var_dump($results);
returns:
array
1 => string 'a' (length=1)
2 => string 'b' (length=1)
3 => string 'c' (length=1)
5 => string 'd' (length=1)
You can't really so easily check if a person did submit a form before.
One way is to add one more hidden field to form if the request came with POST.
Something like that:
<form method="POST" action="">
<?php
if(isset($_POST['submit'])) {
echo '<input type="hidden" name="second_post" value="1">';
} ?>
<!-- Other form items -->
<input type="submit" name="submit" value="1">
</form>
Then you can check is it a second time with:
if(isset($_POST['second_post'])) {
// Second time of form post;
} else {
// First (or zero) time post.
}

Looping correctly though array

Okay so I'm looping through the results that contains two question IDs and two answers and I'm trying to match the two answers with the two answers from the form submission.
I'm not sure what I'm doing wrong.
<?php
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
//Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = false;
if (trim($_POST['answer1']) == '') { $errors = true; }
if (trim($_POST['answer2']) == '') { $errors = true; }
// Error checking, make sure all form fields have input
if ($errors) {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => $errors, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc,$_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc,$_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc,$_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc,$_POST['question1']);
$question2 = mysqli_real_escape_string($dbc,$_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if (($answer == $answer1Post) && ($answer == $answer2Post)) {
} else {
$errors = true;
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => $errors, 'message' => $message);
}
}
} else {
$errors = true;
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => $true, 'message' => $message);
}
}
}
//Output the result
$output = json_encode($output);
echo $output;
?>
Since your question is not clear in the first place, so I'm assuming that the question you are asking is "why you're not getting any matching results, when you've the correct answers in the database?". Please correct me, if this is wrong.
The logic can be like this:-
<?php
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
// Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = false;
if (trim($_POST['answer1']) == '') { $errors = true; }
if (trim($_POST['answer2']) == '') { $errors = true; }
// Error checking, make sure all form fields have input
if ($errors) {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => $errors, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc, $_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc, $_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc, $_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc, $_POST['question1']);
$question2 = mysqli_real_escape_string($dbc, $_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc, $query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if ($answer == $answer1Post) {
// The first answer is correct
$errors = false;
$message = "Your first answer is correct!";
} else if ($answer == $answer2Post) {
// The second answer is correct
$errors = false;
$message = "Your second answer is correct!";
} else {
$errors = true;
$message = "Your answers did not match the answers inside the
}
$output = array('errorsExist' => $errors, 'message' => $message);
}
} else {
$errors = true;
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => $true, 'message' => $message);
}
}
}
// Output the result
$output = json_encode($output);
echo $output;
?>
It's better to have more segregation of logical conditions. In this case, it's your two answers to check for.
Hope it helps.

Categories