php if statement always returns false - php

I know this is a really basic question but I am completely at my wits end. I have been working on this for two days. The if statement always returns false. I have tried === and == and copy to an $array and process outside the fetch $result loop. I have compared to a direct "name". I have outputed the ascii value of each letter of the returned string and compared that way to make sure I wasn't putting a space or something in somewhere. I've tried mysql and mysqli ways. I've tried OO style and Procedural style but here's the rub, This code was copy and pasted from my own site where it's working just fine in three other programs in my site.
<?php
SESSION_START();
if(!isset($_SESSION["uname"])){
require ('redirect.html');
die();
}// session is set close
$uname = $_SESSION["uname"];
$user_name = "xxxxxx";
$password = "xxxxxxx";
$database = "usersdata";
$server = "xxxxxxxxxx.ipagemysql.com";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM messages";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
//echo out values for visual comparison
echo $db_field['recipient']." ".$uname." ";
if($db_field['recipient'] === $uname){echo " match ";} else {echo " no match ";}
}// while loop db_field close
}// if db_found loop close
mysql_close($db_handle);
?>
As I stated this code works just fine in three other programs running on this very site. All I did was copy paste and change the db and fields. I even tried retyping it all from scratch just to make sure. Help me I'm melting....

Why would you return all the messages and then compare with every single message if the name matches. You can simply add a where clause to your query
SELECT * FROM messages WHERE recipient='uname value here'
Then you can check for the number of rows returned. If 0 rows are returned, there was no match.

Related

UPDATE to current date (PHP)

im trying to update date on the table. YYYY-MM-DD HH-MM-SS.
There is the code i have.
It takes information from table and after that I want it to set date in that table to current time
<?php
$username = "root";
$password = "sawasq";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
$code = $_POST['kodas'];
$code = stripslashes($code);
$sql = mysql_query("SELECT * FROM dviraciai WHERE ID='$code'");
$Pavadinimas = 'Pavadinimas';
$Metai = 'Metai';
$Status = 'Status';
$rows = mysql_fetch_assoc($sql);
echo 'Pavadinimas: ' . $rows[$Pavadinimas] . '<br>';
echo 'Metai: ' . $rows[$Metai] . '<br>';
echo 'Status: ' . $rows[$Status] . '<br>';
$sql2 = mysql_query("UPDATE Dviraciai WHERE ID='$code' SET date=CONCAT(CURDATE(),' ',time(mytime))");
mysql_close();
?>
I get $code from input.
Dviraciai is my table.
I dont get any error. But when i enter my $code it shows the info but doesnt change time in table after I restart phpMyAdmin
Your query is totally wrong, and since you never bother checking for errors and simply ASSUME nothing could ever go wrong...
Update syntax is
UPDATE ... SET ... WHERE...
You have the set/where reversed. And note that restarting phpmyadmin is beyond pointless. It's a MANAGEMENT INTERFACE. It's not the database itself. It's like trying to change the outcome of a tv show by turning your tv on/off.... the show's going to end up broadcasting the same ending no matter what you to do with your TV.
Never assume success with DB operations. Even if your SQL is 100% syntactically perfect (and yours definitely isn't), there's far too many OTHER reasons for a query to fail. Assuming success is, frankly, just plain stupid. Always assume failure, check for failure, and treat success as a pleasant surprise. At bare minimum, have something like this:
$result = mysql_query(...) or die(mysql_error());

Connection is made to the database with php script but no values are returned

I have a successful connection to the database through this php script but it is not returning any values even though it is connected. I am checking for the results on my web browser and it just returns a blank screen. I have used the same script (different queries) to access two other tables in the database and they are both working fine. Here is my code:
<?php
$username = "xx";
$password = "xxx";
$host = "xxxxx";
$database="xxxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "SELECT `AUTHOR`, `In_order` from `authors`";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
It is probably some silly mistake that I have over looked but I have been stuck on it for longer than I should! thanks in advance for any feedback
Tried you code locally on some data and it returns everything ok.
I needed to change the select to match my data
So I am 95% sure the problem is in your query / db settings.
I would first check if your columns in database is really called AUTHOR and 'In_order' with the exact capital letters.
MySql names can be case sensitive depending on your db server settings, and this could be the problem
Sidenote: if you can research mysqli and pdo for connecting to DB instead of mysql that is deprecated.
Try this:
$myquery = "SELECT `AUTHOR`, `In_order` from `authors`";
$query = mysql_query($myquery);
$num = mysql_num_rows($query);
var_dump($query);
var_dump($num);
echo mysql_error();
and tell us what it all says.
Edit: okay, so it's 231 rows in your table, as the var_dump($num) says. Now let's try and get them at last, but in a slightly more efficient way:
while ($row = mysql_fetch_assoc($query)) {
$data[] = $row;
}
echo json_encode($data);
I have a feeling that your "for" loop and mysql_fetch_assoc() inside is what plays tricks with you, because both of them use different internal counters.

Select Number of Values in Database Column

I have a mySQL table called palettes, and I want to return the number of links in the table. Basically, I want to return the number of values in the link column. (In this case, 6).
I tried using this code, but it didn't work. I'm a front-end dev, with NO knowledge of php or anything..
include "mysql.php";
$select_rows = $mysqli->query("SELECT COUNT(link) FROM palettes");
$rows = mysqli_fetch_array($select_rows);
$total = $rows[0];
echo $total;
The above code should or echoed 6, right? Selecting from column link
This is what my table looks like:
Use the WHERE clause with LIKE 'http%' and change your query to count id's that fit:
First, I'll assume your file 'mysql.php' has a connection to the database somewhere in the file like this:
<?php
if (session_status() !== PHP_SESSION_ACTIVE) {session_start();}
$hostname = 'localhost';
$dbname = 'myDatabaseName';
$username = 'admin';
$password = 'myPassword';
$cxn = mysqli_connect($hostname, $username, $password, $dbname) or DIE('Connection to host is failed, perhaps the service is down!');
?>//End connect.php
Now you can try this:
include 'mysql.php';
$select_rows = mysqli_num_rows(mysqli_query($cxn, "SELECT id FROM palettes WHERE link LIKE 'http%'"));
echo $select_rows; //Should = 6
I would say place NULL in case you don't have the link available:
You can do it by making the Link column to allow NULL as default. You can make use of the COUNT(Link) in that case. This is recommended.
If you have to have empty string instead of NULLs.
select sum(if(Link != "",1,0)) counting from palettes;
Or if you can make sure all the links start with http/https
select sum(if(Link like "http%",1,0)) counting from palettes;

Jquery/PHP ajax login system

I'm setting up a blog type page for my business. Brand new to MySQL and PHP. Set up this login system. For some reason have no idea why the login is dropping. Suppose to check for errors then return 'good' through php if the email and password is right. If php returns good then it's suppose to redirect to the blog page.
Been dealing with this for a few months need desperate help please. Thank you.
Here is the php code that goes along with the jquery.
Link to test site is here.
test.toddprod.com/login
Would really appreciated the help.
Thanks
<?php
#fake mysql connection first
DEFINE ('DB_USER','usernamegoeshere');
DEFINE ('DB_PASSWORD','passwordhere');
DEFINE ('DB_HOST','hostnamehere');
DEFINE ('DB_NAME','andtheotherthinghere');
$dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL');
$db = mysql_select_db(DB_NAME, $dbc) or die('Could not select database.'.mysql_error());
$e = $_POST['email'];
$pass = $_POST['pass'];
$q = 'SELECT user_id from toddprod where email="'.$e.'" and pass= SHA1("'.$pass.'")';
$r = mysql_query($db, $q);
if( mysql_num_rows($r)==1 ){
setcookie ( 'user_id', $r);
setcookie ( 'email', '$e');
setcookie ( 'logged-in', 'true');
echo 'good';
}
else if (mysql_num_rows($r)==0) {
echo 'Your '.$e.' with password '.$pass;
};
mysql_close ($db);
?>
Umm there's a number of things I see wrong here...
First of all your query should be sanitized...
$email = mysql_real_escape_string ($_POST['email']); // escape the email
$pass = SHA1(mysql_real_escape_string ($_POST['pass'])); // escape and encrypt the pass
// now you can put it into the query safely
$query = "SELECT user_id from toddprod where email = '$email' and pass = '$pass' ";
Next you're executing the query wrong, the mysql_query function takes two arguments, the query and the database connection. You're passing the wrong arguments, you're passing the query and the result of the mysql_select_db function which is just a boolean value. So you have to $dbc not $db into that query, and even then you're passing the arguments in the wrong order. The query goes first, than the connection. So it should be...
$result = mysql_query($query, $dbc);
Next you're trying to set the return value from the mysql_query function as your cookie but that value is a resource, not the userid that you need. You have to actually read the value from the resource like this.
$row = mysql_fetch_array($result);
$userid = $row["user_id"];
setcookie('user_id', $userid);
Moving on... when you're setting the email cookie, you have the variable in single quotes, so the cookie will actually contain $e and not the actual email because single quotes store strings litterly (without parsing the variables). So you should either use double quotes, or no quotes at all. So either one of the following is fine...
setcookie('email', "$e");
setcookie('email', $e);
Last but not least, you should not have the semicolon at the end of your if-statement, and you again you need to pass the connection not the database-selection result into the mysql_close function, so it should be
mysql_close($dbc);
There, hope this gets you somewhere, try out these changes and if the problem persists i'd be happy to help you further.
Here are links that will help you out:
http://www.php.net/manual/en/function.mysql-query.php
http://www.php.net/manual/en/function.mysql-fetch-array.php
http://www.php.net/manual/en/function.mysql-real-escape-string.php
Edit:
Here, I have fixed the code according to the problems I found. Try it out, I could not test it so it might have some small syntax errors here and there, but it should give you something to compare with. Also for the future, I would suggest that you name your variables semantically/properly so it's easier for others to pickup and it will also keep you from getting confused like you were passing $db instead of $dbc into a few of your functions.
<?php
// keep the function names in lowercase, no reason, just looks better to me
define('DB_USER', 'usernamegoeshere');
define('DB_PASSWORD', 'passwordhere');
define('DB_HOST', 'hostnamehere');
define('DB_NAME', 'andtheotherthinghere');
// connect to the mysql server
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL');
// select the database, you don't need to store the result, it just returns true or false
mysql_select_db(DB_NAME, $conn) or die('Could not select database.' .mysql_error());
// escape the input
$email = mysql_real_escape_string($_POST['email']);
$pass = sha1(mysql_real_escape_string($_POST['pass']));
// create the query
$query = "SELECT user_id FROM toddprod WHERE email = '$email' AND pass = '$pass'";
// execute the query
$result = mysql_query($query, $conn);
$usercount = mysql_num_rows($result);
if($usercount == 1){
// read the results and get the user_id
$row = mysql_fetch_array($result);
$userid = $row['user_id'];
// set the cookies
setcookie('user_id', $userid);
setcookie('email', $email);
setcookie('logged-in', 'true');
// echo success message
echo 'good';
}elseif($usercount == 0) {
echo "You're $email with password $pass";
}
mysql_close($conn);
?>
First things first, you MUST sanitise user input with mysql_real_escape_string():
$e = mysql_real_escape_string ($_POST['email']);
$pass = mysql_real_escape_string ($_POST['pass']);
Read up a bit on SQL injection, you'll be very glad you did.
As for the main problem, could you provide a bit more context? How are you checking to see if the user is logged in?

Create a random string, check against table, if already exists, create new and try again, if it doesn't, insert - script not working?

What I'm trying to do, is create a random string, check it against a table, if it already exists, create a new random string and try again, if it doesn't insert it into said table.
My script is based on a script that I was given yesterday, it's all working as planned aside from if(mysql_num_rows($result) == 0), which will automatically return false and execute the else statement. I've tried to change the value to 1 instead of 0, which executes the if statement, regardless of whether it's true or false (e.g. I swap out $authcode = dechex($num1).$dechex($num2); for a string such as $authcode ="eey7y764"; which doesn't exist in the table, yet it still executes the if statement).
Here's my script:
function authCode() {
$num1 = mt_rand(1, 2147483647);
$num2 = mt_rand(1, 2147483647);
$authcode = dechex($num1).dechex($num2);
include("../db/71cfde725dc86.php");
$conn = mysql_connect($db_host, $db_uname, $db_pword) or die("Couldn't connect because ".mysql_error()); mysql_select_db($db_name);
$query = "SELECT COUNT(*) FROM records WHERE valcode='$authcode'";
$result = mysql_query($query) or die("SELECT query failed due to ".mysql_error());
if(mysql_num_rows($result) == 0)
{
$authCode = authCode();
}
else
{
$query2 = "INSERT INTO records (valcode) VALUES ('$authcode')";
$result2 = mysql_query($query2) or die("INSERT query failed due to ".mysql_error());
}
mysql_close($conn);
return $authcode;
}
authCode();
Could you please tell me what changes need to be made to have it function as I'd like?
Any comments or advice will be greatly appreciated :)!
You don't want to compare the number of rows. It's always 1, because you're selecting COUNT(*). It will always give you a single number (hopefully 0 or 1). You have to compare 0 and 1 to the VALUE of that number, not how many of that number there are (which will always be 1).
$row = mysql_fetch_array($result);
if($row['COUNT(*)']==1) ...
Also, you don't want to recursively call authCode(), not like that. You'll possibly make a big stack of open DB connections (not to mention that they'll be opened and closed quickly, which is expensive). You'll probably want to pass along the connection.
function authCode($conn){
...
$authCode = authCode($conn);
}
$conn = mysql_connect( ... );
authCode($conn);
mysql_close($conn);

Categories