PHP Code Problem - php

function check_login($array_val)
{
$strQury = "Select * from tblsignup where usr_email ='".$array_val[0]."' and usr_password = '".$array_val[1]."'" ;
$result = mysql_query($strQury);
$row_user = mysql_fetch_array($result);
if(mysql_num_rows($result)>0)
{
$msg = "true";
}
else
{
$msg = "false";
}
return $msg ;
}
The return value is Object id #1true???? what is object id#1?

Change from:
echo $objUser.check_login($array_login);
to:
echo $objUser->check_login($array_login);
The . operator in PHP does string concatenation, while the arrow allows you to access object methods and attributes.

You're returning the strings "true" or "false" when you probably mean the boolean values true and false.
Oh, and your code is wide open to a visit from Little Bobby Tables. You really should use mysqli and proper prepared statements instead.

Try this:
function check_login($array_val)
{
$strQury = "Select * from tblsignup where usr_email ='".$array_val[0]."' and usr_password = '".$array_val[1]."'" ;
$result = mysql_query($strQury);
$row_user = mysql_fetch_array($result);
if(mysql_num_rows($result)>0)
{
return true;
}
else
{
return false;
}
}
Let us know what result you get when using that code.

user single quotes and things will start to work better. also check your query for sql injection bug as it does have it.

Change
echo $objUser.check_login($array_login);
to
echo $objUser;
echo check_login($array_login);
You should end up with the following result:
Object id #1
true
My guess is that $objUser was set earlier with something along these lines:
$objUser = new User;
As a result, it is an object (the first one declared) and will return Object id #1 when you just echo it. You will need to read up on classes to understand that more.

Related

How to fetch and dispaly specific data with PDO

I'm having issues making my project for lesson attendance and management work the way I'd like it to. Sorry if this has already been addressed here. After days of searching, I still cannot for the life of me find a way to display a limited result set from my DB query to my home page.
This part of the project gets all Towns listed on my homepage like so:
Verona
Mantova
Rovereto
Bardolino
...
What I'd rather want is to get control over whatever is displayed! Specifically, I'd like to have ONLY Rovereto and Bardolino returned (as example). I'm thinking of probably doing this with additional page e.g. index1.php so when this page is loaded it will show only desired values and not all fetched values!
The search function result is also case sensitive. If I type "Bardolino", I get result but with "bardolino", no joy at all. I'm new to this, please help me out. Thank you very much.
File index.php:
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Lesson Number</th>
<th>Town</th>
</tr>
</thead>
<tbody>
<?php
for($i=0; $i < count(User::get_all_users()); $i++){
echo "<tr>";
echo "<td>".User::get_all_users()[$i]['id']."</td>";
echo "<td>".Lesson::get_lesson_by_id(User::get_all_users()[$i]['lesson_id'])['number']."</td>";
echo "<td>".show_town(Lesson::get_lesson_by_id(User::get_all_users()[$i]['lesson_id'])['town_id'])."</td>";
echo "</tr>";
}
?>
File user_controller.php:
if(isset($_GET['type']) && $_GET['type'] == 'search'){
global $user_search_list;
$user_search_list= array();
for($i=0; $i < count(User::get_all_users()); $i++){
$user = User::get_all_users()[$i];
$lesson_number = Lesson::get_lesson_by_id($user['lesson_id'])['number'];
$town_name = show_town(Lesson::get_lesson_by_id($user['lesson_id'])['town_id']);
if(strpos($lesson_number,$_GET['search_term']) !== False ||
strpos($town_name,$_GET['search_term']) !== False)
{
$user_search_list[] = $user;
}
}
$_SESSION['search_list'] = $user_search_list;
header("Location: search_user_list.php");
exit();
}
if(isset($_GET['type']) && $_GET['type'] == 'reserve'){
$user = User::get_user_by_id($_GET['user_id']);
if(!empty($_GET['seat_id'])) {
if(count($_GET['seat_id']) * $user['price'] > intval(Balance::get_user_balance($_SESSION['user_id'])['amount'])){
header("Location: reserve.php?user_id=".$user['id']."&balance_error=set");
exit();
}else{
foreach($_GET['seat_id'] as $seat_id){
echo $seat_id;
echo "<br>";
Reservation::create_reservation('', $_SESSION['user_id'], $_GET['user_id'], $seat_id, getdate()[0]);
Balance::update_balance($_SESSION['user_id'], intval(Balance::get_user_balance($_SESSION['user_id'])['amount']) - intval(User::get_user_by_id($_GET['user_id'])['price']));
Seat::reserve_seat($seat_id,$_SESSION['user_id']);
Action::create_action('', "User - ".$_SESSION['user_id'].'reserve Seat ID - '.$seat_id. " on User ID - ".$_GET['user_id'],"reserve" , getdate()[0]);
}
if(count(Reservation::get_all_reservations_by_user($_SESSION['user_id'])) == 5){
Balance::update_balance($_SESSION['user_id'] ,intval(Balance::get_user_balance($_SESSION['user_id'])['amount']) + 10);
header('Location: index.php?reserve_success=set&reward=set');
exit();
}
header('Location: index.php?reserve_success=set');
exit();
}
}
else{
header("Location: reserve.php?user_id=".$user['id']."&seat_error=set");
exit();
}
}
function show_town($id){
return Place::get_place_by_id(Town::get_town_by_id($id)['place_id'])['name'].
}
File User.php:
class User
{
static $id;
static $lesson_id;
static $starting_date;
static $starting_time;
static $arrival_time;
static $price;
static function create_user($id, $lesson_id, $starting_date, $starting_time, $arrival_time, $price){
global $db;
$sql = "INSERT INTO `lesson_database`.`users` (`id`, `lesson_id`, `starting_date`, `starting_time`, `arrival_time`, `price`) VALUES (NULL, '".$lesson_id."', '".$starting_date."', '".$starting_time."', '".$arrival_time."', '".$price."');";
$db_result = $db->query($sql);
if($db_result){
return True;
}
else{
return False;
}
}
static function get_all_users(){
global $db;
$sql = "SELECT * FROM `users`";
$db_result = $db->query($sql);
if($db_result){
return $db_result->fetchAll();
}
else {
return False;
}
}
static function get_user_by_id($id){
global $db;
$sql = "SELECT * FROM `users` WHERE `id` = '".$id."' LIMIT 1";
if(!isset($sql)){
echo "not set";
}
$db_result = $db->query($sql);
if($db_result){
$db_row = $db_result->fetch(PDO::FETCH_ASSOC);
if($db_row){
return $db_row;
}
else {
return False;
}
}
return False;
}
static function delete_user($id){
global $db;
$sql = "DELETE FROM `lesson_database`.`users` WHERE `users`.`id` = '".$id."'";
$db_result = $db->query($sql);
if($db_result){
return True;
}
else{
return False;
}
}
}
I feel a little bit like you've jumped ahead and skipped some basics as lots of this doesn't make sense.
Firstly, you've said about using PDO in the title but you're not using PDO in your queries, you really need to be using PDO so if you're not sure how then try and find a good tutorial about using prepared statements.
Secondly, you're doing loads of extra calls within loops and duplicating calls all over the place so I think you could do with looking for a tutorial on design patters and think about how you could streamline this code.
As a very basic you could get all your users once by using a fetchAll (or fetch_assoc i think in mysqli) and then just loop through that variable e.g.
<?php
$users = User::get_all_users;
foreach($users as $user){
$lesson = Lesson::get_lesson_by_id($user['lesson_id']);
echo "<tr>";
echo "<td>".$user['id']."</td>";
echo "<td>".$lesson['number']."</td>";
echo "<td>".show_town(lesson['lesson_id'])['town_id'])."</td>";
echo "</tr>";
}
as for your search the simplest way would be to pass a search string in the url and use global $_GET['searchString'] (obviously you will need to sanitize the string) and then search for results directly in sql such as
SELECT * FROM table WHERE town LIKE . $yourvariable .% (ideally in your newly learned PDO style)
then it will be both not case sensitive and will also mean you've got the data in the first place so you don't waste time looping through a bunch of extra rows.
If you need to make this case insensitive in the meantime then the simplest way is to convert the search and the comparison string to the same case (strtolower for example) and then they will match
It also strikes me that your database might not be in good shape as I would be surprised to find that a user table contains lesson ids, so you might want to look into the idea of database normalisation, this will then allow you to do some more creative queries and more easily gather together accurate information for whatever your task is (i.e. make it scalable and manageable).
I hope some of that is helpful, sorry it's not a quick answer but it's not a quick problem I think. Don't fear though, we all started somewhere!!

How do I query a database in PHP and return results based on matching user-input?

I’m trying to write a PHP script with MySQLi to query a database.
I’d like it if the user-input could be checked against the database and then return a result from the column ‘conjugation’ if the string in the column ‘root’ of the table ‘normal_verbs’ is in the input.
So if the user input is something like "foobar", and the root-column has "foo", I'd like it to see 'foo' in 'foobar' and return that value of 'conjugation' in that row.
I can’t seem to get the query to work like I want it to. The one I'm using below is basically just a placeholder. I don't entirely understand why it doesn't work.
What I’m trying, is this :
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('localhost','user','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$m= db_query("SELECT `conjugation` from normal_verbs where `root` in (" . $y . ")");
if($m === false) {
// Handle failure - log the error, notify administrator, etc.
} else {
// Fetch all the rows in an array
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
print_r ($rows);
It’s not giving me any errors, so I think it’s connecting to the database.
EDIT2: I was wrong. I was missing something obvious due to misunderstanding MySQLi and have edited the code accordingly. So the above code does work in that it connects to the database and returns a result, but I'm still stumped on a viable SQL statement to do what I want it to do.
Please try this:
SELECT 'conjugation' FROM 'normal_verbs' WHERE " . $y . " LIKE CONCAT('%',root,'%')
It selects all rows where root contains $y anywhere.
In addition, your code is vulnerable to SQL injections. Please look here for more information.
Try this SQL Query Like this
SELECT `conjugation` from normal_verbs where `root` like '%$y%'

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;
}

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."'";

Categories