I created a mysql query to check if user is banned or not and if he's the system give him return false. But it wont get the information.
public static function checkban($username)
{
if(LOGINCHECKBAN == false)
{
$vusername = engine::securyt($username);
$getIdBYname = "SELECT id FROM players WHERE username='".$vusername."' LIMIT 1";
$getNOW = mysql_query($getIdBYname);
$IDbyNAME = mysql_free_result($getIdBYname);
$queryforban = mysql_query("SELECT * FROM bans WHERE data = '".$IDbyNAME."' LIMIT 1");
$query = mysql_num_rows($queryforban);
if($query == 0) {
return true;
} else {
return false;
}
}
}
Note: engine::securyt($username) is the form type to get his username when he try to login.
What can be wrong on my code?
edit: I belive that "mysql_free_result" can be the problem, but im not sure what i need to put on replace of it.
mysql_free_result() frees a mysql result set. It does not actually retrieve data from the result.
You will want something like:
$getIdBYname = "SELECT id FROM players WHERE username='".$vusername."' LIMIT 1";
$result = mysql_query($getIdBYname);
$row = mysql_fetch_assoc($result);
if($row) { //a user was found
//$row['id'] is the found user
$result = mysql_query("SELECT COUNT(*) cnt FROM bans WHERE data = '". $row['id'] ."' LIMIT 1");
$row = mysql_fetch_assoc($result);
return ($row && $row['cnt'] == 0);
} else {
// no user; return something appropriate
}
However, if all you need is to determine is whether a particular user name is banned (and not actually get their user id), you can do that directly in the database with one query:
SELECT COUNT(*)
FROM players p
INNER JOIN bans b ON b.data = p.id
WHERE p.username = $username;
WARNING: Note that using mysql_* functions is strongly discouraged for new code (since mysql_* has been removed in PHP 7), and directly including variables in your query strings is a pretty major security vulnerability. You should look into using prepared statements/parameterized queries with mysqli or PDO.
Related
I have this php code:
$query = $database->query("SELECT EXISTS(SELECT * FROM contacts WHERE contact_id = '$contactID')";
if($query == 0){
echo "not registered";
}elseif($query == 1){
echo "registered"
}
If I'm not wrong, the query is suppose to return 0 or 1 and it works in my SQLite manager. What is the correct way on getting that value in Php and use it in IF ELSE statement?
If you only need a single value, you can use querySingle:
$result = $database->querySingle("SELECT EXISTS(SELECT * FROM contacts WHERE contact_id = '$contactID'");
Otherwise, with normal queries, the result returned by ->query isn't actually the data itself, but an identifier you would use to get data from the database:
$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
var_dump($row);
}
I'm creating a mobile library app, and for one function of the app I am trying to receive the bookID for all books checked out by a certain user. I would like to be able to echo back the results from the query in a string format (preferably with spaces in between each separate book id) so I can deal with the data later on within the app.
Many of the answers I have found online have simply shown how to execute the query, but not how to use the data afterwards. Sorry if this is a simple question to answer, I am a huge novice.
<?php
require "conn.php";
$email = $_POST["email"];
$mysql_qry = "SELECT * FROM user_data WHERE email like '$email'";
$mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out
WHERE userID LIKE $user_id ORDER BY bookID DESC";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];
$result2 = mysqli_query($conn, $mysqlqry2);
}
else
{
echo "Error, user name not found";
}
$conn->close;
?>
You could append your results into an array and display values using implode():
<?php
require "conn.php";
$email = $_POST["email"]; // You may test here : if (isset($_POST['email']))
$mysql_qry = "SELECT * FROM user_data WHERE email = '$email'";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];
$mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out
WHERE userID = $user_id ORDER BY bookID DESC";
$result2 = mysqli_query($conn, $mysql_qry2);
if(mysqli_num_rows($result2) > 0)
{
$ids = [];
while ($row = mysqli_fetch_assoc($result2)) {
$ids[] = $row['bookID'] ;
}
echo implode(" ", $ids) ; // print list of ID
}
else
{
echo "No books checked out!";
}
}
else
{
echo "Error, user name not found";
}
$conn->close;
NB: I used your code here, but, you should have to look to parameterized queries to prevent SQL injections.
Your query $mysql_qry2 should be defined after to get $user_id.
Your LIKE $user_id could be replaced by =.
First thing first, always sanitize your data:
$email = filter_var( $_POST['email'], FILTER_SANITIZE_EMAIL );
$user_id = preg_replace( "#[0-9]#", '', $row['user_id'] );
Use
DISTINCT bookID instead of DISTINCT(bookID)
From your query: $mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY bookID DESC";
If you're not getting any result or the returned result is empty but the user_id does exist, then I think the query format is wrong.
What you should do instead
Change the ORDER BY: The query may be correct but mysql returned an empty result because the result order does not match.
Try this
"SELECT DISTINCT bookID AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY userID DESC";
"SELECT DISTINCT bookID AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY `primary_key_here` DESC";
Replace <strong>`primary_key_here`</strong> with the primary key name.
Run the query without conditionals and inspect the result
$query = mysqli_query( $conn, "SELECT bookID FROM books_checked_out DESC" );
var_dump( $query );
Use the result to inspect the rest of the query.
Rather than using your own protocol/format use something like JSON or xml in your response to the request.
This will give you better maintainability in the long run and allow you to easily handle the response in the browser with javascript, and most browsers will give you a nice display of JSON objects in the dev console.
You'll have to extract the user id from the result of the first query or you could do a joined query instead.
$email = validate($POST['email']); //where validate() will try to prevent sql injection
//joined query
$query =
" SELECT bookID FROM user_data
INNER JOIN books_checked_out on user_data.user_id = books_checked_out.userID
WHERE user_data.email='$email'
";
//not sure whether that should be user_id or userID looks like you have mixed conventions
//books_checked_out.userID vs user_data.user_id ... check your database column names
//loop through results
// may be empty if user email doesn't exist or has nothing checked out
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
$response[] = ['bookID'=>$row['bookID']];
}
echo json_encode($response);
When receiving the result in php you can use json_decode() or in javascript/ajax it will automatically be available in your result variable.
if things aren't working as expected it can be a good idea to echo the actual sql. In this case
echo 'SQL IS: '.$query;
and test it against your database directly (phpmyadmin/MySQL-Workbench) to see if you get any results or errors.
I am fairly new to PHP.
What I want is not much. I just want to place a check on my page which goes to database and check for value 1 or 0. 1 means "enable" so page continues ; and 0 means "disable" and page dies.
someone suggested the following but it didn't work
$sql = mysql_query("SELECT * FROM members WHERE access= '1'");
$user = mysql_query($sql);
echo $user;
if ($user !=="1") {
echo "You are not the proper user type to view this page";
die();
}
Thank you so much for your time.
Firstly, you're using mysql_query() twice and that alone will cause a syntax error.
You're also not looping over results, so use the following to achieve what you want to do.
$sql = "SELECT * FROM members WHERE access= '1'";
$user = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($user)){
if ($row['access'] !=="1") {
echo "You are not the proper user type to view this page";
die();
}
else {
echo "You are the right type.";
}
}
If your query requires a db connection to the query, you will need to do:
$user = mysql_query($sql, $connection);
This assuming a mysql_ successful connection. However, that API is deprecated as of PHP 5.5 and deleted as of PHP 7.0 and note that different MySQL APIs do not intermix.
It's time to step into the 21st century and use either the MySQLi_ or PDO API.
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/book.pdo.php
You may also have to select an actual row (or rows) instead of SELECT * FROM members
I.e.:
SELECT column_1, column_2 FROM members
Consult these following links http://php.net/manual/en/function.mysql-error.php and http://php.net/manual/en/function.error-reporting.php
and apply that to your code.
You can also achieve this with mysql_num_rows():
$result = mysql_query("SELECT * FROM members WHERE access= '1'");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
// do something
}
else {
// do something else
}
You might also want to add to the WHERE clause:
$result = mysql_query("SELECT * FROM members WHERE access= '1' AND column='x' ");
So what I'm trying to do is create a live friends search. To do this I need an array of names for AJAX to search through.
Heres my while loop.
if($_REQUEST['D'] == 'viewfriends') {
$FREINDS = array();
$FRIENDS_QUERY = "SELECT * FROM `FRIENDS` WHERE `USER` = '{$Modules['User']->Username}' AND `STATUS` = 'accepted' ORDER BY `ID` Limit 10 ;";
$FRIENDS_RESULT = mysql_query($FRIENDS_QUERY);
if(mysql_num_rows($FRIENDS_RESULT) > 0) {
while($FRIENDS_ROW = mysql_fetch_assoc($FRIENDS_RESULT)) {
$sql = "SELECT * FROM `USERS` WHERE `USERNAME` = '{$FRIENDS_ROW['FRIEND']}' ;";
$REQUEST_ROW = mysql_fetch_assoc(mysql_query($sql));
$FRIENDS = $REQUEST_ROW['USERNAME'];
}
echo json_encode($FRIENDS);
} else {
echo'<div class="update status">Sorry, You have no friends at this time. sadface.</div>';
}
}
I put the echo $FRIENDS in there as a test, right now it doesn't display anything. Where did I derp?
You can't echo an array. You can use either print_r($friends) to display the whole row of fields requested in the query (you request *)
or you can echo $friends['name'] (depending on how you declared name in your database)
try this:
if($_REQUEST['D'] == 'viewfriends') {
$FRIENDS = array();
$USERNAME = $Modules['User']->Username;
$SQL_QUERY = "SELECT F.*, U.* FROM FRIENDS AS F LEFT JOIN USER AS U ON F.USER = U.USERNAME WHERE F.USERNAME = '{$USERNAME}' AND STATUS = 'accepted' ORDER BY F.ID LIMIT 10";
$RESULTS = mysql_query($SQL_QUERY);
if(mysql_num_rows($RESULTS) > 0) {
while($ROW = mysql_fetch_assoc($RESULTS)) {
$FRIENDS[] = $ROW['USERNAME'];
}
echo json_encode($FRIENDS);
} else {
echo'<div class="update status">Sorry, You have no friends at this time. sadface.</div>';
}
}
$FRIENDS[] = $REQUEST_ROW['USERNAME'];
then print_r($FRIENDS); echo will output array you need to loop the array or echo json_encode($FRIENDS); to see something
also are you sure that USERNAME is uppercase and not just username in lowercase lowercase as well as for the table name.
also i think you can use a JOIN clause instead of making to SQL requests
You have syntax error:
$FREINDS = array(); should be $FRIENDS = array(); .
And also:
$FRIENDS = $REQUEST_ROW['USERNAME'] should be $FRIENDS[] = $REQUEST_ROW['USERNAME']
And
echo $FRIENDS; should be echo json_encode( $FRIENDS );
The PHP won't actually echo out an array. If you do an echo of an array, it outputs "Array". Plus your javascript wouldn't know what to do with a PHP array if it did pass it that way.
Try:
echo(json_encode($FRIENDS));
Also, you should really listen to the feedback in the comments. Your code is very vulnerable to attack and not set up to scale well for such a potentially huge app.
You have a couple of issues that make your code either less secure or less efficient. The most obvious inefficiency is that you are doing a database call inside your while loop, so if someone has 10 friends, that means you've done 11 database queries when you may have only needed one or two. Here are the two queries:
SELECT * FROM `FRIENDS`
WHERE `USER` = '{$Modules['User']->Username}'
AND `STATUS` = 'accepted' ORDER BY `ID` Limit 10
SELECT * FROM `USERS` WHERE `USERNAME` = '{$FRIENDS_ROW['FRIEND']}'
So before we determine if these two can be combined, the first big red flag is the SELECT *. I use it all of the time, but it will get you kicked out of the better database bars. In your case, it's really unnecessary. We know from the second query that the only thing you are using from the first query is the $FRIENDS_ROW['FRIEND'] to match against the USERNAME. So that first query can become:
SELECT FRIEND FROM `FRIENDS`
WHERE `USER` = '{$Modules['User']->Username}'
AND `STATUS` = 'accepted' ORDER BY `ID` Limit 10
You also have the SELECT * in the second query, and we can tell that (for now) the the only thing you are using is the USERNAME, so it can become:
SELECT USERNAME FROM `USERS` WHERE `USERNAME` = '{$FRIENDS_ROW['FRIEND']}'
Finally, we can see from the second query that the FRIEND name and the USERNAME are identical; otherwise why would you query for the usernames where the username equals the friend name. If that's the case, we can drop your second query completely, since we already know the usernames from the first query.
The reason why it's both inefficient and unsafe is because you are using the OG mysql functions, which are clunky and don't offer the option of prepared statements. Prepared statements let you (among other things) put variables in your query in such a way that when you actually call the query, the parts that are variables are known and can thus be sanitized, avoiding the horrors of mysql injections that everyone has mentioned.
I won't bore you with the play-by-play, but here is what your code might look like if you used the newer mysqli library with a prepared statement:
if($_REQUEST['D'] == 'viewfriends') {
$friends = array();
$friend_lookup = $mysqli->prepare("SELECT FRIEND FROM FRIENDS WHERE
USER = ? AND STATUS = 'accepted'
ORDER BY FRIEND");
$friend_lookup -> bind_param('s', $userName);
$userName = $Modules['User']->Username;
$friend_lookup -> execute();
$friend_lookup -> bind_result($friend);
while($friend_lookup -> fetch()) {
$friends[] = $friend;
}
if($friends) {
echo json_encode($friends);
} else {
echo "Sorry, no friends. Boo.";
}
}
I have this code:
$local_id = $_GET['id'];
$sql = dbquery("SELECT * FROM `videos` WHERE `id` = ".$local_id." LIMIT 0, 1");
while($row = mysql_fetch_array($sql)){
$video_id = $row["youtube_id"];
// the rest
}
how can i check if $local_id does not exist in the db and display an error?
mysql_num_rows
if(mysql_num_rows($sql) == 0) {
//Show error
}
$sql = dbquery("select count(*) from videos where id = ".$local_id." LIMIT 0, 1");
$row = mysql_fetch_row($sql);
if($row[0] == 0)
echo 'error';
You can use the following query:
"SELECT COUNT(*) FROM `videos` WHERE `id` = ".mysql_real_escape_string($local_id)
This query will return one number: how many records have matched your query. If this is zero, you surely know that there are no records with this ID.
This is more optimal than other solutions posted in case you only want to check for the existence of the ID, and don't need the data (if you use SELECT * ..., all the data will be unnecessarily sent from MySQL to you). Otherwise mysql_num_rows() is the best choice, as #Ryan Doherty correctly posted.
Be sure to ALWAYS escape data that came from the outside (this time GET) before you put it into a query (mysql_real_escape_string() for MySQL).
If you fail to do so, you are a possible victim for SQL Injection.
You could have a $count variable and increment it in the while loop. After the loop, check the count, if it is 0, then echo an error message.