Query always returns NULL - php

So the problem is the $check variable is always NULL, even though there is already a record in the database that match the SELECT statement I have written, it's still null. I know it's simple enough but i can't find the error. I already tried using empty, isNull, ====, but the problem is the $check is always null. Why it is always null?.
$sql = "SELECT * FROM linkedin_lookup WHERE "
."`given-name`='{$table['given_name']}' && "
."`family-name`='{$table['family_name']}' && "
."`location`='{$table['location']}' && "
."`industry`='{$table['industry']}' && "
."`headline`='{$table['headline']}'";
$results = $db->query($sql);
$check = $results->num_rows;
if ($check):
echo "Record already exist";
else:
$sql = "INSERT INTO linkedin_lookup (`given-name`,`family-name`,`location`,`industry`,`headline`,`date_search`) "
."VALUES "
."('{$table['given_name']}',"
."'{$table['family_name']}',"
."'{$table['location']}',"
."'{$table['industry']}',"
."'{$table['headline']}',"
."'{$now}')";
$db->query($sql);
echo "Succesfully inserted record(s)" . '<br />';
endif;
UPDATE MY CODE TO REFLECT INPUTS, but still it accepts duplicate. Is my SELECT STATEMENT wrong?. I put && right so it;s supposed to scan all fields if the same.

That's because you call num_rows on the result of the query (same for fetch_assoc), NOT the array.
$results = $db->query($sql);
$check = $results->num_rows;
if( $check) {
echo "Record already exists";
}
else {
$sql = "INSERT.....";
}
Note that you could just try to insert it up front and check affected_rows - if it's zero then it faied to insert due to already existing. Note that you'll need a UNIQUE KEY on the table in the right fields.

If $results does infact contain something....and the query is infact working, which I dunno if it is....
You could just try this instead....
$db->query($sql);
$results = $db->fetch_assoc();
if (count($results) > 0):
//echo "Record already exist";
else:

Ok now it works, i think the class $db is not mysqli, because we are using a framework that is developed by the company. So my codes now as follows and It works.
$sql = "SELECT * FROM linkedin_lookup WHERE "
."`given-name`='{$table['given_name']}' && "
."`family-name`='{$table['family_name']}' && "
."`location`='{$table['location']}' && "
."`industry`='{$table['industry']}' && "
."`headline`='{$table['headline']}'";
$db->query($sql);
$check = $db->fetch_array();
if ($check):
echo "Record already exist";
else:
$sql = "INSERT INTO linkedin_lookup (`given-name`,`family-name`,`location`,`industry`,`headline`,`date_search`) "
."VALUES "
."('{$table['given_name']}',"
."'{$table['family_name']}',"
."'{$table['location']}',"
."'{$table['industry']}',"
."'{$table['headline']}',"
."'{$now}')";
$db->query($sql);
echo "Succesfully inserted record(s)" . '<br />';
endif;

Related

Checking if data exists working, but doesn't display what I'm asking it too

Okay, so, I'm checking whether to see if random data selected from a php array already exists within my database.
Here is the code for the snippet that is not working.
$check = "SELECT * FROM contest WHERE Loser = '".$input[$rand_keys[$i]]."' AND Hamantha = '".$input[$rand_keys[$i+30]]."'";
$rs = mysqli_query($con, $check);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if ($data[$i] > 1){
while($data[$i] > 1){
echo'DO NOT USE THIS GUESS';
$rand_keys2 = array_rand($input, 2);
$input[$rand_keys[0]] = $input[$rand_keys[$i]];
$input[$rand_keys[1]] = $input[$rand_keys[$i + 30]];
}
echo $input[$rand_keys2[0]];
echo '-';
echo $input[$rand_keys2[1]];
echo '<br>';
} else {
echo $input[$rand_keys[$i]];
echo '-';
echo $input[$rand_keys[$i + 30]];
echo'<br>';
}
it displays the data that doesn't exist correctly, but when it does exist, the code under the 'if' doesn't run. I put error_reporting on, and all the lines that the data does exist for, it shows an error for all those lines, which is good, it's finding the lines that do exist within the database, yet the stuff under the if don't run why? Like it doesn't display 'DO NOT USE THIS GUESS' ect.
Edit: Here is a picture of the problem i.imgur.com/F35vGzO.png
As you see if found the first guess to be good, while the second guess was already used, but it didn't display the messages i wanted it to.
Ok, changing my above query state to this worked perfectly.
$query = mysqli_query($dbl, "SELECT * FROM `tblUser` WHERE email='".$email."'");
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}....

How can I SELECT field FROM table WHERE id=variable?

I have a variable of the logged in user ($steamid) that I need to use to select and echo specific fields from the database. I am using the following code, but it is working incorrectly. All database info is correct, the tables, columns, and variables are not misspelled. Not sure what I'm doing wrong.
<?php
$con=mysqli_connect("private","private","private","private");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT `bananas` FROM `es_player` WHERE `steamid` = '$steamID'";
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
printf("bananas: %n",$fieldinfo->bananas);
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
No errors are shown, it simply returns "bananas:" with nothing after it. I feel like I didn't to it correctly, does anyone know what I might've done wrong? Here is a screenshot of my database table so you know what it looks like http://puu.sh/gCY3d/983b738458.png.
Try this:
$query = Mysqli_Query($con, "SELECT * FROM `es_player` WHERE `steamid`='$steamID'") or die(mysql_error());
if( ! mysqli_num_rows($query) )
{
echo 'No results found.';
}
else
{
$bananas_array = mysqli_fetch_assoc($query);
$bananas = $bananas_array['bananas'];
echo 'Number of bananas: '. $bananas;
}
If this doesn't work, there is a problem with STEAM_ID format. You could try triming the IDs to be JUST a number, and add the STEAM_x:x: to it later.

Why isn't this query returning an object?

I am learning PHP and MySQL from 'PHP and MySQL web dev'. Currently I am finding difficulties in displaying results from database. Here is the code:
<body>
<?php
$searchtype = $_POST['searchtype'];
$seachterm = trim($_POST['searchterm']);
if(!$searchtype || !$seachterm){
echo "You did not enter all the details. Bye";
exit;
}
if(!get_magic_quotes_gpc()){
$searchtype = addslashes($searchtype);
$seachterm = addslashes($seachterm);
}
# $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');
if(mysqli_connect_errno()){
echo "Sorry Could not connect to db";
exit;
}
$query = "select * from books where".$searchtype."like '%".$seachterm."%'";
$result = $db -> query($query);
$num_of_results = $result->num_rows; // Line 47
echo "Num of books found is ".$num_of_results." ";
for($i = 0; $i < $num_of_results; $i++){
$row = $result -> fetch_assoc();
echo "<p><strong>".($i+1).". Title: ";
echo htmlspecialchars(stripslashes($row['title']));
echo "</strong><br />Author: ";
echo stripslashes($row['author']);
echo "<br />ISBN: ";
echo stripslashes($row['isbn']);
echo "<br />Price: ";
echo stripslashes($row['price']);
echo "</p>";
}
$result->free();
$db -> close();
?>
</body>
When I run the above code, this is the error i get.
Notice: Trying to get property of non-object in /opt/lampp/htdocs/xampp/php/php_crash/phptomysql/connect.php on line 47
Num of books found is
Fatal error: Call to a member function free() on a non-object in /opt/lampp/htdocs/xampp/php/php_crash/phptomysql/connect.php on line 64
What am I doing wrong?
There's probably an error in your SQL query and $result is false instead of the result object.
I think it's probably because you're missing some spaces in the query. This line:
$query = "select * from books where".$searchtype."like '%".$seachterm."%'";
should be something like:
$query = "SELECT * FROM books WHERE '" .$searchtype. "' LIKE '%".$seachterm."%'";
It would help if we knew the values of:
$_POST['searchtype'];
$_POST['searchterm'];
You're not checking to make sure that $result is what you think it is. It's very likely that something went wrong with your query, and the return value of $db->query() is false. It's a good idea to check for that to make sure your query actually worked.
Try using this code:
$result = $db->query($query);
if ($result === false) {
// Query failed - we can't continue
die('My query failed, I want to be a teapot instead.');
}
// Now it's safe to operate on $result, deal with a successful query, but no results
if ($result->num_rows == 0) {
echo 'no results found.';
// display any other output, search again?
exit;
}
// At this point you have results to display
Now, as to why your query is failing, take a look at this part closely:
"select * from books where".$searchtype."like '%"
You need some spaces. If $searchtype was 'foo', your query would actually expand to:
select * from books wherefoolike
Try instead:
"select * from books where ".$searchtype." like '%"
Notice the space after 'where' and before 'like'? That should probably fix it.
I'm not going to harp too much about making sure your query is properly prepared for safety, your book should go into that - but do keep it in mind.

Simple logon script

I'm trying to do a simple logon script. That is, accept form content through a POST action. Check the database for a matching record. Pull other information from that row such as Full Name.
The code I have is;
if ( !isset($_POST['loginsubmit']) ) {
//Show login form
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<p>
Account ID:
<input name="AccountID" type="text" />
</p>
<p>
Username:
<input name="userEmail" type="text" />
</p>
<p>Password:
<input name="userPassword" type="password" />
<p>
<input name="loginsubmit" type="submit" value="Submit" />
</p>
</form>
<?php
}
else {
//Form has been submitted, check for logon details
$sql = "SELECT * FROM users WHERE 'accountID'=". $_POST['AccountID']. " AND 'userEmail'=". $_POST['userEmail'] . " AND 'userPassword'=". $_POST['userPassword']. " LIMIT 1";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if ($count == 1){
echo"Correct Username/Password";
}
else {
echo "Wrong Username or Password";
}
}
I have two issues. Firstly with the above code, I keep getting the following error.
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in ...
Second, how do I get the other details fields out of the databse. I presume
$result=mysql_query($sql);
contains an array for the MySQL row, so could I do something like;
echo $result['fullName'];
First sanitize the fields to prevent SQL injection.
$sanitize_fields = array('AccountID','userEmail','userPassword');
foreach( $sanitize_fields as $k => $v )
{
if( isset( $_POST[ $v ] ) )
$_POST[ $v ] = mysql_real_escape_string( $_POST[ $v ] );
}
Then quote the string fields in your query. Initially there was an error in your query. That's why you were getting a boolean value of false.
$sql = "SELECT * FROM users WHERE accountID='". $_POST['AccountID']. "' AND userEmail='". $_POST['userEmail'] . "' AND userPassword='". $_POST['userPassword']. "' LIMIT 1";
I suggest you do the following after running the query to see the error generated by MySQL, if there is one.
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
The MySQL extension is being phased out and there are newer better extensions such as MySQLi and PDO, have a look at those.
In your SQL statement:
$sql = "SELECT * FROM users WHERE 'accountID'=". $_POST['AccountID']. " AND 'userEmail'=". $_POST['userEmail'] . " AND 'userPassword'=". $_POST['userPassword']. " LIMIT 1";
if in the table, the userEmail and userPassword are strings, please add single qoutes:
$sql = "SELECT * FROM users WHERE accountID=". $_POST['AccountID']. " AND userEmail='". $_POST['userEmail'] . "' AND userPassword='". $_POST['userPassword']. "' LIMIT 1";
To get the results:
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
if(mysql_num_rows($result) > 0)
echo $row['COLUMN_NAME'];
}
}
Your codes are very insecure:
Please use MySQLi or PDO to interact with the database
Escape all input data before sending to the database
Try this:
else {
//Form has been submitted, check for logon details
$conn = mysql_connect("db-host-here","db-user-here","db-pass-here");
$sql = "SELECT * FROM users WHERE accountID=". mysql_real_escape_string($_POST['AccountID']). " AND userEmail='". $_POST['userEmail']=mysql_real_escape_string($_POST['userEmail']); . "' AND userPassword='". $_POST['userPassword']=mysql_real_escape_string($_POST['userPassword']);. "' LIMIT 1";
$result = mysql_query($sql,$conn);
$count = mysql_num_rows($result);
if($count == 1){
echo"Correct Username/Password";
}
else {
echo "Wrong Username or Password";
}
}
// Get other information:
$dbInfo = mysql_fetch_assoc(); //If more than one row can be selected, use a while loop.
//Now play with $dbInfo:
echo $dbInfo['some_other_column'];
You have single quotes in your query where you don't need them, and you're missing them where you do. Try the code above.
Replace db-host-here,db-user-here and db-password-here with the correct database information.
I have done some escaping in your code, to prevent injection attacks. But you should really look into using prepared statements.
The problem here is that Your query fails to select any row therefore a boolean FALSE is returned from mysql_query call.
You should repair Your query and always check if the $result = mysql_query($query); returns false or not, like so:
// ...
$result = mysql_query($query);
if($result !== false) {
$count = mysql_num_rows($result);
// ...
}
But I recommend using PDO or at least mysqli http://php.net/mysqli.

PHP Mysql Data Insert

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 .

Categories