mysql_fetch_array returns nothing - php

i was creating some script , but mysql_fetch_array returns nothing the time i have data in my database .. mysql_error(); also returns no error but i don't know what's the problem here everything is right ..
if($_POST['submit'])
{
include("connect.php");
$query=mysql_query("select * from admins where id = '$userid'");
$fetch=mysql_fetch_array($query);
$qs=$fetch['security_question'];
$an=$fetch['security_answer'];
if($qs==$question)
{
if($an==$answer)
{
header("location:panel.php");
}
}

Make sure that mysql_fetch_array return some value
Means $userid maybe do not match with any userid in your database
Use mysql_num_rows to find how may row it return

You have to check following case.
Your Form data is Posted Proper or Not ?
Your database connection is all right ?
Have you got proper userid in $userid variable ?
You have to put static userid in place of $userid variable for testing purpose.
You have to check tableName spelling and connection file spelling is correct or not?
Might above case will help you to solve your problems.

Related

MySQL query from PHP executes only first query only

I have a problem in following code:
<?php
session_start();
$user_id = $_SESSION['user_id'];
?>
<?php #insert new tweets
if($user_id){
if($_POST['post_id']!=""){
include 'connect.php';
mysqli_query($conn,"Delete from post where id=".$_POST['post_id']."");
mysqli_query($conn, "UPDATE users
SET post = post - 1
WHERE username=$user_id");
}
}
header("Location: .");
?>
The first query Delete works, but the second Update doesn't, what's wrong in my code?
It redirects to header fine.
First of all, your code is vulnerable to SQL Injections. I would advise sanitizing your input first before transmitting it to that database.
I think you have a typo in your second query
UPDATE users SET post = post - 1 WHERE username=$user_id;
username should probably be user_id. Because the query can not find a matching record, it appears as if nothing is executed.
You can always verify this by checking the return value of mysqli_query.
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

sql in php not returning anything

How do I see what is returned from a sql statement in php? I have the following function to get user name from mysql database and I use echo in another php to see the result but nothing shown.
function get_user_name($id_user) {
return mysql_result(mysql_query("SELECT username FROM user WHERE id_user = '$id_user'"));
}
echo $id_user;
$a = get_user_name($id_user);
echo $a;
Can anyone help? Thanks.
Are you echoing the get_user_name(); function?? OR are you even connected to your database? these are two things you need to check before, (if the problem remains) including an error handling method i.e. or die(mysql_error()) at the end of your query to find out the problem.
return mysql_result(mysql_query("SELECT id_user FROM user WHERE id_user = '$id_user'")or die (mysql_error()));
The error handling construct?? in mysql mysql_error() should output the problem in fairly understandable way, as to what is preventing your query not to be shown

PHP login, getting wrong count value from query / fetch array

EDITThanks to the comments below it has been figured out that the problem lies with the md5, without everything works as it should.
But how do i implent the md5 then?
I am having some troubles with the following code below to login.
The database and register system are already working.
The problem lies that it does not find any result at all in the query.
IF the count is > 0 it should redirect the user to a secured page.
But this only works if i write count >= 0, but this should be > 0 , only if the user name and password is found he should be directed to the secure (startpage) of the site after login.
For example root (username) root (password) already exists but i cannot seem to properly login with it.
<?php
session_start();
if (!empty($_POST["send"]))
{
$username = ($_POST["username"]);
$password = (md5($_POST["password"]));
$count = 0;
$con = mysql_connect("localhost" , "root", "");
mysql_select_db("testdb", $con);
$result = mysql_query("SELECT name, password FROM user WHERE name = '".$username."' AND password = '".$password."' ")
or die("Error select statement");
$count = mysql_num_rows($result);
if($count > 0) // always goes the to else, only works with >=0 but then the data is not found in the database, hence incorrect
{
$row = mysql_fetch_array($result);
$_SESSION["username"] = $row["name"];
header("Location: StartPage.php");
}
else
{
echo "Wrong login data, please try again";
}
mysql_close($con);
}
?>
The best thing you can do in such situations is trying to find out where the problem lies.
So, you could proceed by steps and do the following:
1) start your script with a print_r($_POST), to see what variables are passed by post (by absurd, the problem might even be related to the 'send' guard parameter you have ..IE a form being sent through get)
2) Assign your query to a variable (...and don't forget to escape parameters!) and print it to screen; and then exec it on mysql (or phpmyadmin) to see what results they give.
As a side note, as someone already pointed out, this code might be subject to SQL-injection, so you might consider using prepared statements; see here: quick intro
Your login code is good.
But you also need to use md5() function BEFORE storing the password in the database. So when you are inserting the user record in the DB , apply the md5() to the password , save in the DB. Now when you will try to find the record on login, it will match correctly.
You should rewrite this with mysqli or PDO and using a newer hash function as well as a salt. MD5 is very widely used and is a target for crackers.

php login script - remember me

Can anyone see anything wrong with this login script:
public function login($username, $pass, $remember) {
// check username and password with db
// else throw exception
$connect = new connect();
$conn = $connect->login_connect();
// check username and password
$result = $conn->query("select * from login where
username='".$username."' and
password=sha1('".$pass."')");
if (!$result) {
throw new depException('Incorrect username and password combination. Please try again.');
} else {
echo $username, $pass;
}
To explain:
At the moment the script is allowing anything through. In other words the query is returning true for any username and password that are passed to it.
I've put the echo statement just as a check - obviously the script would continue in normal circumstances!
I know that the connect class and login_connect method are working because I use them in a register script that is working fine. depException is just an extension of the Exception class.
The function login() is part of the same class that contains register() that is working fine.
I know that the two variables ($username and $pass) are getting to the function because the echo statement is outputting them accurately. (The $remember variable is not needed for this part of the script. It is used later for a remember me process).
I'm stumped. Please help!
UPDATE
Thanks for those responses. I was getting confused with what the query was returning. The complete script does check for how many rows are returned and this is where the checking should have been done. Everything is now working EXCEPT for my remember me function. Perhaps someone could help with that?!?! Here is the full script:
public function login($username, $pass, $remember) {
// check username and password with db
// else throw exception
$connect = new connect();
$conn = $connect->login_connect();
// check username and password
$result = $conn->query("select * from login where
username='".$username."' and
password=sha1('".$pass."')");
if (!$result) {
throw new depException('Incorrect username and password combination. Please try again.');
}
if ($result->num_rows>0) {
$row = $result->fetch_assoc();
//assign id to session
$_SESSION['user_id'] = $row[user_id];
// assign username as a session variable
$_SESSION['username'] = $username;
// start rememberMe
$cookie_name = 'db_auth';
$cookie_time = (3600 * 24 * 30);*/ // 30 days
// check to see if user checked box
if ($remember) {
setcookie ($cookie_name, 'username='.$username, time()+$cookie_time);
}
// If all goes well redirect user to their homepage.
header('Location: http://localhost/v6/home/index.php');
} else {
throw new depException('Could not log you in.);
}
}
Thanks very much for your help.
UPDATE 2!
Thanks to your help I've got the main part of this script working. However, the remember me bit at the end still doesn't want to work.
Could someone give me a hand to sort it out?
$username, $pass and $remember are all short variable names that I assigned before passing them to the function to save writing $_POST['username'] etc. everytime. $remember refers to a checkbox.
What does $conn->query() return, a MySQL resource object like mysql_query() does? If so then it'll always compare "true". mysql_query() only returns FALSE if the query completely fails, like it has a syntax error or a table doesn't exist.
To check if you got any results you need to try to fetch a row from the result set and see if you get anything, via whatever your equivalent of mysql_fetch_row() is.
Important: Your script is vulnerable to SQL injection attacks, or even just odd usernames like o'neil with an apostrophe. You should escape all variables in a query with mysql_real_escape_string() (or equivalent) to make sure your query doesn't get messed up by special characters. Or, even better, use prepared statements which look like
select * from login where username=? and password=sha1(?)
Re: UPDATE
Variables from a form are available via either $_GET or $_POST, depending on which method was used to submit the form. Try if (isset($_POST['remember'])) to see if that check box was checked.
Important: I see that you tried to use a bare $remember to see if the check box was checked. That suggests to me that you are trying to take advantage of the register_globals feature in PHP which makes your GET and POST variables accessible via regular variable names. If that is the case you should heed the warning in the PHP manual!
WARNING
[register_globals] has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.
Use $_GET and $_POST instead. I could tell you how to make if ($remember) work, actually, but given the inherent evil-ness of register_globals I'm not gonna! ;-)
Your query is open for sql-injections...
SELECT * FROM users WHERE
username = '' OR 'a' = 'a'
AND password =
sha1('guessAnyPassword')
I'd also check your result, and base the action on how many records were returned.
if (mysql_num_rows($result) > 0)
In php most queries only return False if there was an error executing them. Your query is returning a value, probably an empty array of values. This is not a false value as far as your if statement is concerned.
Check how many rows are returned. The function to do this will depend on your abstraction layer (connect class etc...)

How do I select mysql database in php?

I have this code:
if(!mysql_connect($host,$user,$passwd)){
die("Hoops, error! ".mysql_error());
}
...no error from here.
if(!mysql_select_db($db,$connect)){
$create_db = "CREATE DATABASE {$db}";
mysql_query($create_db,$connect);
mysql_query("USE DATABASE {$db}",$connect);
}
..."no database selected" error from here.
I would like to select database if it exists and if doesn't then create it and select it.
Why is my code not right?
Thank you in advance
Where are you saving the value returned by mysql_connect()? Don't see it here. I assume $host, $user, $password and $db are properly set ahead of time. But you're passing a param to mysql_select_db that may not be properly set.
$connect = mysql_connect($host,$user,$passwd);
if (!$connect) {
die('Could not connect: ' . mysql_error());
}
if(!mysql_select_db($db,$connect)) ...
Start by checking to see if you can select without the CREATE query first. Try a simple SELECT query to start. If you can connect, select the db, and execute a SELECT query, that's one step. Then try the CREATE query. If that doesn't work, it's almost certainly a matter of permissions.
You might need database create permissions for the user attempting to create the database.
Then you need to operate on a valid connection resource. $connect never looks to be assigned to the connection resource.
Why not simply use the CREATE DATABASE IF NOT EXISTS syntax instead?
Something like this ...
$con = mysql_connect('localhost');
$sql = 'CREATE DATABASE IF NOT EXISTS {$db}';
if (mysql_query($sql, $con)) {
print("success.\n");
} else {
print("Database {$db} creation failed.\n");
}
if(!mysql_select_db($db,$connect)){
print("Database selection failed.\n");
}
You should check the return value of mysql_query() - currently if any of those calls fail you won't know about it:
if(!mysql_select_db($db,$connect)){
if (!mysql_query("CREATE DATABASE $db", $connect)) {
die(mysql_error());
}
if (!mysql_select_db($db, $connect)) {
die(mysql_error());
}
}
Change the line
mysql_query($create_db,$connect);
mysql_query("USE DATABASE {$db}",$connect);
To
mysql_query($create_db,$connect);
mysql_select_db($db);*
and it should work.
you could try w3schools website. They have a very simple and easy to learn tutorial for selecting database. The link is : http://www.w3schools.com/php/php_mysql_select.asp
Hope this help :)
I would like to thank to all of you, however I found fault on my side. This script was in class and one of variables were not defined inside this class. So I'm really sorry.
I don't know how to consider the right answer, but I noticed my mistake after reading Clayton's answer about not properly set parameters, so I guess he is the winner ;)

Categories