How to check if a $_GET variable exists in database - php

How to check if a $_GET variable exists in Database if it does not print an error.
I am using this code:
$connection = mysqli_connect("localhost" , "root" , "" , "test");
$query = "SELECT site_title FROM websites";
$select_all_sites = mysqli_query($connection,$query);
$row_count = mysqli_num_rows($select_all_sites);
for ($i=0; $i < $row_count; $i++){
$row = mysqli_fetch_assoc($select_all_sites);
if($_GET['website'] == $row['site_title']){
echo 'Success';
}else{
echo 'error';
}
}
It prints too much errors or (the else condition remains always true.) Help me out.

It is not safe to directly throw any of php array variables into your query. You need to clean it. Consider using the mysqli_real_escape_string. Although i would suggest to make a switch to PDO.
Back to your question, why can't you use a while loop instead of the for loop. you need to check if the variable website actually exists or not. php's isset function will help. Try this:
<?php
if(isset($_GET['website'])){
if($_GET['website'] == $row['site_title']){
#awesome! it matches
} else{
#it does not match
}
} else{
#website $_GET variable does not exist. Handle error
}
?>

Please try below code and inform me if you will face any error.
<?php
$connection = mysqli_connect("localhost" , "root" , "" , "test");
$query = "SELECT site_title FROM websites";
$select_all_sites = mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($select_all_sites))
{
if($_GET['website'] == $row['site_title'])
{
echo 'Success';
}
else
{
echo 'error';
}
}
?>

You will first have to do a check for is the get variable actually exists. You can do this with the PHP isset function http://php.net/manual/en/function.isset.php if it exists you can proceed to see if it is matching you site title like you do now.

Related

MySQL COUNT not returning False or True in PHP

So I'm trying to check if a user already liked a post.
Code:
function previously_liked($id) {
if (isset($_SESSION['user_login'])) {
$user = $_SESSION["user_login"];
}
else {
$user = "";
}
$connection = new mysqli($host, $username, $password, $database);
$id = $connection->real_escape_string($id);
$query = $connection->query("SELECT COUNT(`id`) AS `count` FROM `likes` WHERE `id` = '$id' AND `user_id` = '".$connection->escape_string($user)."'");
while ( $row = $query->fetch_object()->count ) {
if ( $row->count == 0 ) return false;
else return true;
}
}
The thing is, it's not returning false or true. On my other PHP page I'm trying to run this function like this:
if (previously_liked(70) === true) {
$aliked = "You've already liked this!";
}
echo $aliked;
The only error I'm seeing is Notice: Undefined variable: aliked in profile.php on line 391
Any help is welcome! Thanks!
You can do this things to finds error in your code:
echo $user; //before MySQL query
Query your MySQL statement in MySQL console or app like PHPmyAdmin after replacing ".$connection->escape_string($user)." to your user_id. If it fetch row than your MySQL statement is correct and there is something wrong with $_SESSION["user_login"] value.
Optionally, you can also echo the returning rows to check the output data.
Otherwise check your query statement as column names, table name, database etc.
Hope, it helps you...
Your query is fine, your problem is something else: You're defining $aliked inside the scope of the if-statement, so you can't use it outside. You need to change your code, one possibility is this:
if (previously_liked(70) === true) {
echo "You've already liked this!";
}
or this:
$aliked = "";
if (previously_liked(70) === true) {
$aliked = "You've already liked this!";
}
echo $aliked;

PHP custom function return value from mysql database

i have looked at the other results for what i'm trying to do, none of them do what i need them to. What i am trying to do is something like this:
myfunction(){
require('./connect.php'); //connect to database
$query = mysql_query("SELECT * FROM users WHERE username='$user'"); //user is defined outside the function but it works in my login function which i use the same way.
$numrows = mysql_num_rows($query);
if($numrows == 1){
$row = mysql_fetch_assoc($query);
$value = row['value'];
mysql_close();
return $value;
} else {
$errmsg = "connection failed.";
$value = 0;
return $value;
}
}
In my php file i would do something like this at the top.
$value = myfunction();
This does not work.
Ultimately what i'm trying to accomplish is getting a value from the database and output it from the function in another file.
(this is my first post on stackoverflow so if i need to change this feel free to tell me and i shall)
Your code has several syntax error. Check this, and read my comments:
function myfunction() {
//connect to database
require('./connect.php');
//user is defined outside the function but it works in my login function which i use the same way.
$query = mysql_query("SELECT * FROM users WHERE username='" . mysql_real_escape_string($user) . "'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$row = mysql_fetch_assoc($query);
return $row['value']; //Missing $ sign
//No need to create $value if you just return with that.
//mysql_close();
//return $value;
} else {
//Where do you use this errmsg????
$errmsg = "connection failed.";
return 0;
// These 2 lines are unnecessary.
//$value = 0;
//return $value;
}
} //Missing function close
In my example, I've just leave the mysql functions, but please do not use them, they are deprecated. Use mysqli or PDO instead. Also, avoid sql injections by escapeing your variables!
$row = mysql_fetch_assoc($query);
$value = row['value']; // <-------- you forgot the $
and most probably, the correct way to extract the result is,
$row[0]['value'];
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
i'm thinking you forgot a dot here.
require('./connect.php');
And a bit of function improvement
myfunction(){
require_once('../connect.php'); //connect to database
$query = mysql_query("SELECT * FROM users WHERE username='".$user."'"); //user is defined outside the function but it works in my login function which i use the
$numrows = mysql_num_rows($query);
if($numrows == 1){
$row = mysql_fetch_assoc($query);
$value = $row['value'];
mysql_close();
}
else{
$errmsg = "connection failed.";
$value = 0;
}
return $value;
}

Adding input from textfield to database

I try to add datas which are taken from a textfile to my database with a php script, here is the script:
foreach($lines as $name){
$bolunmus=explode(" ", $name);
$add = false;
if(!exist_in_db($bolunmus[0], $bolunmus[1], $bolunmus[2])){
$add = mysql_query("
INSERT INTO people(name, surname, age)
VALUES('$bolunmus[0]', '$bolunmus[1]', '$bolunmus[2]');", $con);
}
else{
echo (" could not write it.<br>");
}
if($add)
echo $bolunmus[0]." ".$bolunmus[1]." ".$bolunmus[2]." Added to database.";
}
// this is my control function, which will return
// true if data already exist in database,
// else it will return false.
function exist_in_db($name, $surname, $age){
$result = mysql_query("
SELECT * FROM people ORDER BY id
");
while($row = mysql_fetch_array($result)){
if($row['name']==$name && $row['surname']==$surname || $row['age']==$age){
echo $row."could not write it.";
return true;
}else{
return false;
}
}
}
?>
in fact, the problem is when I try to execute this script, it reads from textfile, and if that user does not exist, it adds, until here there is not any problem. But when I try to execute it again, it adds users with same output like "bla bla 0 is added to database." If I don't make any changes in text-file, I want it to control again, and if that user exists, do not add it, thanks everybody.
if($row['name']==$name && $row['surname']==$surname || $row['age']==$age)
^ ^
There should be a bracket here.
if(($row['name']==$name && $row['surname']==$surname) || $row['age']==$age)
To debug further, try var_dump($bolunmus);

How to debug PHP database code?

I am new in PHP and need help with my below code. When I am entering wrong userid instead of giving the message "userid does not exist" it is showing "password/id mismatch. Please guide me where I am wrong.
<?php
session_start();
$id = $_POST['userid'];
$pwd = $_POST['paswd'];
$con = mysqli_connect("localhost", "????", "????", "??????");
if ($con) {
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
if ($result) {
$row = mysql_fetch_array($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist !!!";
}
} else {
echo "Connection failed - ".mysqli_error()." -- ".mysqli_errno();
}
?>
The main problem you have is that you're mixing up between the mysqli and mysql functions. These two libraries are not compatible with each other; you must only use one or the other.
In other words, the following line is wrong:
$row=mysql_fetch_array($result);
It needs to be changed to use mysqli_.
While I'm here, going off-topic for a moment I would also point out a few other mistakes you're making:
You aren't escaping your SQL input. It would be extremely easy to hack your code simply by posting a malicious value to $_POST['userid']. You must use proper escaping or parameter binding. (since you're using mysqli, I recommend the latter; it's a better technique).
Your password checking is poor -- you don't appear to be doing any kind of hashing, so I guess your passwords are stored as plain text in the database. If this is the case, then your database is extremely vulnerable. You should always hash your passwords, and never store the actual password value in the database.
I've gone off topic, so I won't go any further into explaining those points; if you need help with either of these points I suggest asking separate questions (or searching here; I'm sure there's plenty of existing advice available too).
else
{
echo "ID/Password Mismatch";
}
is connected with the
if($row["userid"]==$id && $row["paswd"]==$pwd)
{
So since you are giving a wrong id. It echo's: ID/Password Mismatch
Also the else at if ($result) { wont ever show since
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
You need some additionnal checks:
select * return 1 row (not 0, and not more)
you need to protect the datas entered by the html form (for example someone could enter 1 or 1 to return all rows
<?php
session_start();
$con = mysqli_connect("localhost", "????", "????", "??????");
$id = mysqli_real_escape_string($_POST['userid']);
$pwd = mysqli_real_escape_string($_POST['paswd']);
if ($con) {
// don't even do the query if data are incomplete
if (empty($id) || empty($pwd)
$result = false;
else
{
// optionnal : if userid is supposed to be a number
// $id = (int)$id;
$result = mysqli_query($con, "SELECT * FROM users WHERE userid='$id'");
}
if (mysqli_num_rows($result) != 1)
$result = false;
if ($result) {
$row = mysqli_fetch_assoc($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist, or incomplete input";
}
} else {
echo "Connection failed - " . mysqli_error() . " -- " . mysqli_errno();
}
?>
Try with isset() method while you are checking if $result empty or not.
that is in line
if ($result) {.......}
use
if (isset($result)) { .......}
$result is always true, because mysqli_query() only returns false if query failed.
You could check if $result has actual content with empty() for example.
You can use this sql compare password as well with userid
$sql= "SELECT * FROM users WHERE userid='".$id.", and password='".$pwd."'";

PHP Update MySQL DB with AJAX call isn't doing anything

I'm trying to update a field on my database with PHP and AJAX
I have tested and found that the correct data is being sent, but the PHP that is handling the update is not working correctly.
All that happens is that I get the else response in conditional.
I need to update the DB depending on what the user input is.
Like I said, all I get for the response is the else response.
$youruname = $_POST['youruname'];
$selectedplayer = $_POST['selectedplayer'];
$selPlayerUname = $_POST['selPlayerUname'];
$flag = "";
$itStatus = "";
$checkit = mysqli_query($conn,"SELECT it FROM login WHERE uname='$selPlayerUname'");
while($row = mysqli_fetch_array($checkit))
{
$itStatus = $row["it"];
}
if($itStatus == "not it")
{
mysqli_query("UPDATE login SET it = CASE WHEN uname = '$youruname' THEN 'not it' ELSE 'it' END WHERE uname IN ('$youruname', '$selPlayerUname')");
$flag = "success";
}
else if($itStatus == "it")
{
$flag = "nope";
}
else
{
$flag = "error";
}
echo json_encode(array("message" => $flag, "tagged" => $selectedplayer));
mysqli_free_result($checkit);
mysqli_close($conn);
There is something confusing here. You have a loop and after loop conditionals. Shouldnt your update query be inside a loop like:
while($row = mysqli_fetch_array($checkit))
{
$itStatus = $row["it"];
if($itStatus == "not it")
{
mysqli_query("UPDATE login SET it = CASE WHEN uname = '$youruname' THEN 'not it' ELSE 'it' END WHERE uname IN ('$youruname', '$selPlayerUname')");
$flag = "success";
}
else if($itStatus == "it")
{
$flag = "nope";
}
else
{
$flag = "error";
}
}
Your $iStatus gets the last value from the database since its in the loop and then you check in conditionals
If above does not help then check your $_POST values to see if any of them are blank or null and do the query on PHPMyAdmin see if it actually returns anything.
mysqli_query requires you to pass the connection.
I wasn't doin that.
When I passed the values to the query directly, I figured it out.
Thank you very much for the help everyone

Categories