i'm trying to select value from different tables but i face some errors in the result i want to check if there is any values i will echo "Yes" otherwise echo "No"
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$username=$_POST['username'];
require_once('dbConnect.php');
$sql="SELECT donator.national_id, needy_people.national_id".
"FROM donator, needy_people".
" WHERE donator.national_id='$username' OR needy_people.national_id='$username' limit 50";
$result=mysqli_query($con,$sql);
if($check>0){
while($row=mysql_fetch_array($sql)){
$check=mysqli_fetch_array(mysqli_query($con,$sql));
}
}
if(isset($check)){
echo'YES';
}else{
echo'Noooo';
}
mysqli_close($con);
}else{
echo'error';
}
can anybody solve this problem help!
When you put as condition if($check>0), $check is not defined yet, so it won't be processed, hence $check stay unset.
Also you should use the empty() function to test existence of values in it
If you're trying to check if a row exists when you run your query consider using the function mysqli_num_rows
if (mysqli_num_rows($result) > 0) {
echo "Has row";
}
$count=mysqli_num_rows($check);
if($count>0)
echo "yes";
else
echo "no";
Related
Simple Login Form Using PDO .The Output of echos works fine .Enters inside the else case But does not go inside the foreach loop.
The output of var_dump gives this .
echo output
1rows SelectedEntered successfull loop
var_dump output
object(PDOStatement)[3] public 'queryString' => string 'select *
from tour_login where username='admin' and password='admin' and
status=1' (length=81)
if(isset($_POST['login']))
{
$un=$_POST['un'];
$pass=$_POST['pass'];
$res=DB::getInstance()->query("select * from tour_login where username='$un' and password='$pass' and status=1");
$num_rows = $res->fetchColumn();
echo $num_rows."rows Selected";
if($num_rows<=0)
{ echo "Entered error loop";
echo "<script>alert('invalid username and password');document.location='index.php';</script>";
return false;
}
else
{
echo "Entered successfull loop";
foreach ($res as $row) {
echo "Entered successfull for loop";
if($row['type']==0)
{
$_SESSION['admn']=$un;
echo "<script>alert('welcome admin...');document.location='adminhome.php';</script>";
}
else
{
$_SESSION['usr']=$un;
echo "<script>alert('welcome user...');document.location='userhome.php';</script>";
}
}
}
}
What I am not understanding is why foreach is not working with number of rows showing one.New to Php.I found alternative of using mysql_num_rows() in pdo in this StackOVerflow Question
https://stackoverflow.com/questions/11305230/alternative-for-mysql-num-rows-using-pdo
Your first problem is that, being a novice, you just snatched one line from the code you found, having no idea what does it do. This line would never return number of rows found, yet this line is responsible for your confusion, as it fetches all the data you selected, leaving nothing for the foreach loop. Though you don't need the latter as well.
Your second problem is that you are under a very common delusion, thinking you need number of returned rows at all. In fact, you don't actually need it.
Your third problem is that you ought to be using prepared statements but you aren't.
The code you need is
$sql = "select * from tour_login where username=? and password=? and status=1";
$res = DB::getInstance()->query($sql);
$res->execute(array($un, $pass));
$row = $res->fetch();
if(!$row) {
echo "Entered error loop";
echo "<script>alert('invalid username and password');document.location='index.php';</script>";
return false;
}
and so on. Just remove useless foreach loop and you're set.
Here is my code:
$campagin_id = $_SESSION['campagin_id_for_camp'];
$query = "SELECT * FROM survey_result where campagin_id = ".$campagin_id;
$conn=mysql_connect($dbconfig['db_hostname'],$dbconfig['db_username'],$dbconfig['db_password']) or die(mysql_error());
mysql_select_db($dbconfig['db_name'],$conn);
$exec_query =mysql_query($query) or die(mysql_error());
$row=mysql_fetch_array($exec_query);
echo "<br> row = ".$row;
while ($row=mysql_fetch_array($exec_query)){
echo "I am In";
}
The Problem is that I am not getting anything in $row I cant get into the while loop, nothing shows up when I try to echo the value of $row, No error Nothing. Can you help me to find a problem in my code ?
Ps : The database is their. I have checked for the query for the corresponding value of $campagin_id. and also when i tried to echo $exec_query it echoed this : Resource id #8
PPS : The database have more than 7 record for each id so it doesn't matter if I call mysql_fetch_array($exec_query) more than once before going in to the while loop. and for the $campagin_id in the session their are many records present in the database.
You have written $row=mysql_fetch_array($exec_query) and then you are echoing something. and you are using the same in while.
Instead of:
$row=mysql_fetch_array($exec_query);
echo "<br> row = ".$row;
while ($row=mysql_fetch_array($exec_query)){
echo "I am In";
}
Use this (as per my knowledge you should not use $row=mysql_fetch_array() once you have used before while):
while ($row=mysql_fetch_array($exec_query)){
echo "I am In";
}
If the query returns Resource id #8 then that means it was successful - ie there were no errors. There were probably no rows returned by that query, so no rows in your table that match the given campagin_id.
You are also calling mysql_fetch_array() twice separately, you shouldn't do that because your while loop will skip the first row because calling this moves the pointer in the result set forward by one.
Also you can't echo an array as you are trying to, if you want to see the contents of an array use print_r() or var_dump().
I suggest adding some code to handle no rows found:
if($exec_query && mysql_num_rows($exec_query) > 0)
{
while ($row=mysql_fetch_array($exec_query)){
echo "Row: " . print_r($row, true);
}
}
else
{
echo 'None found';
}
Try this code.
<?
$campagin_id = $_SESSION['campagin_id_for_camp'];
$query = "SELECT * FROM survey_result where campagin_id = ".$campagin_id;
mysql_connect($dbconfig['db_hostname'],$dbconfig['db_username'],$dbconfig['db_password']) or die(mysql_error());
mysql_select_db($dbconfig['db_name']);
$exec_query =mysql_query($query) or die(mysql_error());
while ($row=mysql_fetch_assoc($exec_query)) {
echo "<br/> row = <pre>".print_r($row)."</pre><br/>";
}
?>
I'm learning PHP from reading the php manual and studying different tutorials. I hit a snag with the mysql_query. I'm trying to insert user data into a database from a form using PHP. The mysql_query should return false because the username doesn't exist in the database yet but according to the result I am getting it is returning true and nothing is being entered into the database. Am I using mysql_query wrong or is using !result incorrect?
$sql = "SELECT * FROM users WHERE username='".$_POST["name"]."'";
$result = mysql_query($sql)
if (!$result) {
$sql = "INSERT INTO USERS (username, email, password) VALUES
('".$_POST["name"]."', '".$_POST["email"]."', '".$passwords[0]."')";
$result = mysql_query($sql);
if ($result) {
echo "It's entered!";
} else {
echo "There's been a problem: " . mysql_error();
}
} else {
echo "There's already a user with that name: <br />";
$sqlAll = "SELECT * FROM users";
$resultsAll = mysql_query($sqlAll);
$row = mysql_fetch_array($resultsAll);
while ($row) {
echo $row["username"]." -- ".$row["email"]."<br />";
$row = mysql_fetch_array($result);
}
}
Jason, you're checking to see if the query has failed or not - not whether it has returned the value 'false' or 'true'. You need to call mysql_fetch_row or similar, then compare the result.
Alternatively you could use the following:
if (mysql_num_rows($result) == 0) {
/* User doesn't exist */
} else {
/* User exists */
}
This will detect if any users have been chosen by your query and - if they have - your user exists already.
Also, you should learn about input sanitisation and SQL Injection. It's a very critical security issue and your script is vulnerable to it. More info here.
A select query which has no result rows STILL returns a result handle. msyql_query() will ONLY return a 'false' value if the query fails due to a syntax error, constraint violation, etc...
Your code should be
$sql = "...";
$result = mysql_query($sql);
if ($result === false) {
die("QUery failed: " . mysql_error());
}
if (mysql_num_rows($result) == 0) {
... user does not exist ...
}
And please please please read up about SQL injection vulnerabilities. Your code has holes wide enough for a truck to drive through.
In this case, $result will be a resource. You should check the number of results with mysql_num_rows().
Never, really, NEVER, use $_POST or any direct user input in a query. Always escape the input, BEFORE using it in a query, with mysql_real_escape_string(), or you'll have opened a serious security issue with SQL Injection.
Ex:
$safe_name = mysql_real_escape_string($_POST["name"]);
$sql = "SELECT * FROM users WHERE username='$safe_name'";
It's not exact.
mysql_query() will also fail and return FALSE if the user does not
have permission to access the table(s) referenced by the query.
In your case you have the permission but the user doesn't exist. So it will return true but the result set returned is empty.
mysql_query will return an empty set if the query returns no data. The query will however not fail.
i solve my problem :
like this
<?php
$username = $_POST['username'];
include('config.php');
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
while($row = mysqli_fetch_array($result)){
echo $row['username'];
echo "</br>";
echo "</br>";
echo "<p><b>Secret Question</b></p>";
echo $row['secret'];
}
?>
</br>
</br>
<form action="forgetaction.php" method="POST">
<p><b>Answer is :</b><p>
<input type="hidden" name="username" value="<?php echo $username; ?>">
<input type="text" name="answer">
</br>
</br>
<input type="Submit" value="Submit">
</form>
and forget action.php like this :
<?php
include('config.php');
$username = $_POST['username'];
echo $username;
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
$row = mysqli_fetch_array($result);
if($row['answer'] == $_POST['answer']) {
echo $row['password'];
} else {
echo 'wrong!';
}
?>
thank you all for help .
I have an a href which looks like that: Delete
And file delete-news.php is as follow:
<?php
if(isset($_GET["?deleteID='.$id."]))
{
$result = mysql_query("DELETE FROM 'news' WHERE id='$id'");
echo mysql_error();
if($result)
echo "succces";
}
else { echo "GET NOT SET"; }
?>
But it is returning GET NOT SET. What I'm doing wrong?
Use this, and for god's sake escape your inputs.
if(isset($_GET['deleteID'])) {
$result = mysql_query("DELETE FROM `news` WHERE id='".mysql_real_escape_string($_GET['deleteID']). "'");
echo mysql_error();
if($result)
echo "succces";
} else {
echo 'GET NOT SET';
}
$_GET will have each element of the GET variables already broken down, so no need to include the URL data. So, in your example, the link ?deleteID=123 would produce $_GET['deleteID'].
Try using that, but also remember to sanitize the values you receive in from URLs. If it's going to be a numeric value, I suggest casting it:
$deleteID = (int)$_GET['deleteID'];
Please also note that changes to the system should only happen via POST, and never GET. Otherwise (for example), you might get a spidering bot that deletes your whole site. See this post for more references:
https://stackoverflow.com/questions/679013/get-vs-post-best-practices
You need to check $_GET for just deleteID. Later, reference it as $_GET['deleteID']. Also, call mysql_real_escape_string() on $_GET['deleteID'] to retrieve your query parameter $id.
if(isset($_GET["deleteID"]))
{
$id = mysql_real_escape_string($_GET['deleteID']);
$result = mysql_query("DELETE FROM `news` WHERE id='$id'");
echo mysql_error();
if($result)
echo "succces";
}
else { echo "GET NOT SET"; }
Try this instead:
<?php
if(isset($_GET['deleteID']))
{
$id = intval($_GET['deleteID']);
$result = mysql_query("DELETE FROM `news` WHERE id='$id'");
echo mysql_error();
if($result) echo "succces";
} else {
echo "GET NOT SET";
}
?>
Note that I'm making the given deleteID into an int, meaning that values other than some form of number will become 0.
Also, you can't wrap a table- and/or column name with ' - backticks are the way to go!
<?php
if(isset($_GET["deleteID"]))
{
$id = ($_GET['deleteID']);
$result = mysql_query("DELETE FROM news WHERE id='".mysql_real_escape_string($id)."'");
echo mysql_error();
if($result)
echo "succces";
}
else { echo "GET NOT SET"; }
?>
is correct one
You obtain GET NO SET, because the $_GET associative array does not contain ?deleteID='.$id.
In order for you to obtain the id, you need to so something like this:
$id = $_GET['deleteID'];
Also
$result = mysql_query("DELETE FROM 'news' WHERE id='$id'");
That is very unsafe as it allows SQL injections. Instead, do:
$query = sprintf("DELETE * FROM news WHERE id=%d",
mysql_real_escape_string($id),
$result = mysql_query($query);
I hope this helped.
I have a PHP search script which queries a MySQL database. Currently, when no results are displayed the script shows and error. How can I make it display a message like "No Results were found" when nothing is returned?
My PHP script is:
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database");
if(!empty($_GET['q'])){
$query=mysql_real_escape_string(trim($_GET['q']));
$searchSQL="SELECT * FROM links WHERE `title` LIKE '%{$query}%' LIMIT 8";
$searchResult=mysql_query($searchSQL);
while ($row=mysql_fetch_assoc($searchResult)){
$results[]="<div class='webresult'><div class='title'><a href='{$row['url']}'>{$row['title']}</a></div><div class='desc'>{$row['description']}</div><div class='url'>{$row['url']}</div></div>";
}
echo implode($results);
}
?>
if (empty($results)) {
echo 'No results found';
} else {
echo implode($results);
}
Create a MYSQL Connection and paste this code below
$sql="SELECT * FROM tablename WHERE columnname LIKE your variable or constant ";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count>=1){if result was found}
else {if result was not found}
?>
You could count the number of elements in the array, and either continue with your implode or display the message you mentioned.
<?php
if(count($results) > 0){
echo implode($results);
}
else {
echo "No results were found.";
}
?>
You also really should not be using the mysql_* functions. Use either the improved version (mysqli_*) or PDO.
Try the following:
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database");
if(!empty($_GET['q'])){
$query=mysql_real_escape_string(trim($_GET['q']));
$searchSQL="SELECT * FROM links WHERE `title` LIKE '%{$query}%' LIMIT 8";
$searchResult=mysql_query($searchSQL);
if(mysql_num_rows($searchResult) <= 0)
{
echo "No results";
} else {
while ($row=mysql_fetch_assoc($searchResult)){
$results[]="<div class='webresult'><div class='title'><a href='{$row['url']}'>{$row['title']}</a></div><div class='desc'>{$row['description']}</div><div class='url'>{$row['url']}</div></div>";
}
echo implode($results);
}
}
?>
Also please either use MySQLi or PDO as it is safer and better to use, some information can be found below. Personally I prefer MySQLi but prepared statements in PDO is really good and saves some lines of code every time you query ;)
MySQLi and PHP
PDO and PHP
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database");
if(!empty($_GET['q'])){
$query = mysql_real_escape_string(trim($_GET['q']));
$searchSQL = "SELECT * FROM links WHERE `title` LIKE '%{$query}%' LIMIT 8";
$searchResult = mysql_query($searchSQL);
// the query was run successfully
// and it returned at least a result
if(is_resource($searchResult) && mysql_num_rows($result) > 0){
while ($row=mysql_fetch_assoc($searchResult)){
$results[]="<div class='webresult'><div class='title'><a href='{$row['url']}'>{$row['title']}</a></div><div class='desc'>{$row['description']}</div><div class='url'>{$row['url']}</div></div>";
}
echo implode($results);
} else{
echo 'No Results were found';
}
}
?>
You could also use the function mysql_num_rows, which will tell you the number of rows returned by your query.
$rows = mysql_num_rows($searchResult);
if($rows <= 0){
/* Code if there are no rows */
}
else{
/* At least one row has been found */
}
if (mysql_num_rows($searchResult) == 0) {
echo "some error message";
} else {
... process data
}
How about a simple counter in the while statement:
$i = 0;
while (condition) {
$i++;
do stuff;
}
if ($i ==0) {echo 'No results found';}