PHP & MYSQL: Select from where id=$id - php

So I'm making a usergroup function that allows me to block off pages to lower user levels. This is my function for grabbing info:
function grab_info($id, $requested_info){
$id = $_SESSION['user_id'];
$requested_info = $requested_info;
$con = new mysqli('localhost', 'root', '', 'login');
if ($con->connect_errno >0){
die("Handle your connection error here");
}
$sql = "SELECT * FROM `users` WHERE `id` = $id";
if (!$result = $con->query($sql)) {
die("There as a query error for some reason handle your query error");
}
while($row = $result-fetch_assoc()){
$info = $row[$requested_info];
return $info;
}
}
Right here:
$sql = "SELECT * FROM `users` WHERE `id` = $id";
if (!$result = $con->query($sql)) {
die("There as a query error for some reason handle your query error");
}
is where something is going wrong. This is my method for grabbing the info:
$id = $_SESSION['user_id'];
$rank = grab_info($id, 'rank');//Gets rank from our id
$meets = can_access($rank, 4, true);//We're saying our user has a rank of 1 to access this page you need a rank of 3 and only 3 hence strict
if ($meets == false){//user cant access page
header("Location: index.php");
die();
}
Basically, it just keeps giving me the "There as a query error for some reason handle your query error" and I'm stuck. New to php so sorry if it's messy.

Using prepared statements and cast the variable as an integer.
$stmt = $con->prepare("SELECT * FROM `users` WHERE `id` = ?");
$stmt->bind_param("i",$id);
$id = (int) $_SESSION['user_id'];
$stmt->execute();
$result = $stmt->get_result();

Check to make sure that $id is actually set. If it's null that will cause your query to explode.

$sql = "SELECT * FROM `users` WHERE `id`='{$id}'";
Try this :)

$query=mysql_query("SELECT * FROM user WHERE user_email='$user_email');

Please try this:
function grab_info($id, $requested_info){
$id = $_SESSION['user_id'];
$requested_info = $requested_info;
$con = new mysqli('localhost', 'root', '', 'login');
if ($con->connect_errno >0){
die("Handle your connection error here");
}
$sql = "SELECT * FROM users WHERE id =". $id;
if (!$result = $con->query($sql)) {
die("There as a query error for some reason handle your query error");
}
while($row = $result->fetch_assoc()){
$info = $row;
return $info;
}
}

Related

query returns nothing php

I attempt to get the result of a very simple query with the function query but nothing appears. If I execute the query in PHPMyAdmin, with the same data, I have a result.
There is my code :
$sql = "SELECT * FROM users WHERE email='$email'";
$response = $conn->query($conn, $sql);
The $conn variable is correct, I did an Insert with that.
$response is null. I can do an echo and there is nothing.
What can I do to solve this problem ? What can I check ?
Thank you very much.
You don't need to pass connection in query.
Solution:
$sql = "SELECT * FROM users WHERE email='$email'";
$response = $conn->query($sql);
while($res = $response->fetch_array()){
$name=$res['nameofuser']; //just an example
}
echo $name;
Real solution (prepare stmt):
$sql = "SELECT * FROM users WHERE email=?";
$response = $conn->prepare($sql);
$response->bind_param('s',$email);
if(!$response->execute()){
echo "Error query: " . $response->error . ".";
}
$result=$response->get_result();
while($res = $result->fetch_array()){
$name=$res['nameofuser']; //just an example
}
echo $name;
'Tips' add to real solution check if query is done.
After execute query . fetch the results
$stmt = $conn->prepare( "SELECT * FROM users WHERE email= ? ");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0) exit('No rows');
while($row = $result->fetch_assoc()) {
// your code
}

Table 'databasename.info' doesn't exist

So I installed this jackpot script with a layout and everything and within the jackpot script there was a set.php file which I tried to set up, it looked like this:
<?php
$sitename = "csgoxd.net";
$link = #mysql_connect("localhost:3306", "csgoxdne", "thisisasecretpassword");
$db_selected = mysql_select_db('csgoxdne_csgoxddb', $link);
mysql_query("SET NAMES utf8");
function fetchinfo($rowname,$tablename,$finder,$findervalue) {
if($finder == "1") $result = mysql_query("SELECT $rowname FROM $tablename");
else $result = mysql_query("SELECT $rowname FROM $tablename WHERE `$finder`='$findervalue'") or die (mysql_error());
$row = mysql_fetch_assoc($result);
return $row[$rowname];
}
?>
So I'm new when it comes to coding in general (I know some basic stuff but that's it) so basically I'm not sure if I'm supposed to fill out more of this file because I get this error on my website.
"Table 'csgoxdne_csgoxddb.info' doesn't exist"
I'm new to this and I'm trying to learn so help is much appreciated.
You should use MySQLi to make use of its advantages it offers over MySQL. You can see more here.
The script you have isn't all too bad, but it does need some tweaking. It's vulnerable to injection like Marc B said. I'm going to assume that csgoxdne_csgoxddb is your table name.
Try this:
<?php
$mysqli = new mysqli("localhost:3306", "csgoxdne", "thisisasecretpassword");
if (mysqli -> error){ print ("Error connecting! Message: ".$mysqli->error); }
mysqli_set_charset($mysqli, 'utf8');
function fetchinfo($rowname, $tablename, $finder, $findervalue) {
if ($finder == "1") {
$query = "SELECT * FROM $tablename WHERE rowname = '$rowname'";
$result = mysqli_query($mysqli, $query);
} else {
$query = "SELECT * FROM $tablename WHERE `$finder`='$findervalue'";
if (!$query) {
die('Invalid query: ' . $mysqli->error);
}
$result = mysqli_query($mysqli, $query);
}
return $result;
}
?>
Oh and make sure the port number on your localhost is correct.
Also to go through the values of result you can use:
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
#do things
}
}

Moving from MySQL to MySQLi message not displaying on no results

i'm currently trying to start using MySQLi instead of MySQL, but for some reason that I don't understand this is working for the first part of changing the password, but then failing on the error message. Can anyone tell me why? Cheers
$sql1 = <<<SQL
SELECT *
FROM Users
WHERE UserID = '$UserID'
&& Password = '$hashedPW'
SQL;
if ($db->query($sql1)) {
$sql2 = $db->query("UPDATE Users SET Password = '$NEWhashedPW' WHERE UserID=$UserID");
if($db->affected_rows === 0) { echo $_SESSION['changepass'] = 'error'; header('Location:'.$_SERVER["HTTP_REFERER"]);
} else {
$_SESSION['changepass'] = 'success'; header('Location:'.$_SERVER["HTTP_REFERER"]);
}
} else {
echo 'error';
}
$result1->free();
$db->close();
Question, why are you looping through the data if only 1 result is being returned?
$sql1 = "SELECT * FROM `Users` WHERE `UserID` = ".$UserID." AND `Password` = '".$hashedPW."'";
$result = $db->query($sql1);
if($db->num_rows($result)) { // Assuming you have a num_rows() function
$db->query("UPDATE `Users` SET `Password` = '".$NEWhashedPW."' WHERE `UserID` = ".$UserID);
$_SESSION['changepass'] = !$db->affected_rows() ? 'error' : 'success';
header('Location:'.$_SERVER["HTTP_REFERER"]);
} else
echo "User not found";
$result1->free();
$db->close();
This is also assuming that your query() function has some form of debugging ability and that you have a num_rows() function
If not, write one!
The num_rows() function should work similar to this (procedural style):
function num_rows($res) {
return mysqli_num_rows($res);
}
Simply whack that into your database class and you should be good to go.
May need edits, I don't know how your DB class is set up

PHP and SQL syntax issue

I am having problems with a (should be simple) bit of code. I am getting info from a form and trying to echo out an entry/ies in a database that match the form specifications. I think that my HTML is correct, and my problem lies in the PHP. Here is my code that I need help with:
<?php
$submit = #$_POST['submit'];
$gender = $_POST['gender'];
$hair = $_POST['hair'];
$height = $_POST['height'];
$body = $_POST['body'];
if ($submit){
//open database
$connect = mysql_connect("xxxx", "xxxx", "xxxx") or die("Couldnt Connect to Server");
mysql_select_db("xxxx") or die("Couldnt find database");
$query = mysql_query("SELECT * FROM `table` WHERE `gender`='$gender' AND `hair`='$hair' AND `height`='$height' AND `body`='$body'");
$query_run = mysql_query($query);
if ($query_run = mysql_query($query)) {
while ($query_row = mysql_fetch_assoc($query_run)) {
$pic = $query_row['picture'];
};
};
};
?>
This is a self submitting page <form action='thispage.php' method='post'>. Later down the page in the empty space is where I am going to echo $pic.
Is this method correct/the best way to do it? If need be, I will post the code for the entire page. It is only 75 lines right now.
And before I am told that I should be using SQLi, this is more of a proof of concept right now, and more importantly I don't know how to make the changes from SQL to SQLi.
edit: Within the form, there are only options, not text input (if that matters)
Here's how I would do it using modern libraries
// check that all required POST parameters are present
if (isset($_POST['submit'], $_POST['gender'], $_POST['hair'], $_POST['height'],
$_POST['body'])) {
// create DB connection
$pdo = new PDO('mysql:host=localhost;dbname=xxxx;charset=utf8',
'xxxx', 'xxxx');
// set error mode and use real prepared statements if possible
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// prepare an SQL statement with parameter placeholders
// I changed the * to just `picture` as that's all you were using in your OP
$stmt = $pdo->prepare('SELECT `picture` FROM `table` WHERE `gender` = ? AND `hair` = ? AND `height` = ? AND `body` = ?');
// execute with the POST parameters
$stmt->execute(array(
$_POST['gender'],
$_POST['hair'],
$_POST['height'],
$_POST['body']
));
// load all "picture" results into an array
$pics = array();
while ($pic = $stmt->fetchColumn()) {
$pics[] = $pic;
}
}
$query = mysql_query("SELECT * FROM `table` WHERE `gender`='$gender' AND `hair`='$hair' AND `height`='$height' AND `body`='$body'");
$query_run = mysql_query($query);
if ($query_run = mysql_query($query)) {
while ($query_row = mysql_fetch_assoc($query_run)) {
$pic = $query_row['picture'];
};
};
should be
$query = "SELECT * FROM `table` WHERE `gender`='$gender' AND `hair`='$hair' AND `height`='$height' AND `body`='$body'";
if ($query_run = mysql_query($query)) {
while ($query_row = mysql_fetch_assoc($query_run)) {
$pic = $query_row['picture'];
};
};
$query = mysql_query("SELECT * FROM `table .........
$query_run = mysql_query($query); extra

Error when I passed on values on function

Sorry about the last post I had. Here's my revision, please help me.
<?php
//connect database
$sql = "SELECT * FROM user where user_id = 8320 AND password = 'admin' ";
$query = pg_query($sql);
var_dump($row = pg_fetch_array($query)); //dumps correctly.
?>
BUT THE PROBLEM IS THIS..when I try to make it as a function LIKE:
function check($user_id, $password)
{
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($sql);
$row = pg_fetch_array($query);
return $row;
}
AND CALL IT HERE:
var_dump($data = check(8320, 'admin')); DUMPS NULL;
How come it ended up like this?
Its returning NULL because there is an error with your SQL query, and no results are being returned. You should do some error checking in your function, try this version:
function check($user_id, $password)
{
$dbconn = pg_connect("host=localhost dbname=test");
$sql = "SELECT * FROM user where user_id = $1 AND password = $2 ";
$result = pg_query_params($dbconn, $sql, array($user_id,$password));
$row = pg_fetch_array($result);
if (!$row) {
echo pg_last_error($dbconn);
} else {
return $row;
}
}
Try the code below. It should work fine for you.
$data = check(8320, 'admin');
var_dump($data);
Seems like your PostgreSQL resource is missing inside the function. You have two options.
Declare the connection resource inside the function using global.
Establish the connection inside the function.
This is the first option:
$conn = pg_connect('host','user','pass','db');
function check($user_id, $password)
{
global $conn;
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
And this is the second option:
function check($user_id, $password)
{
$conn = pg_connect('host','user','pass','db');
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
According to the PHP manual, You may omit connection resource, but it is not recommended, since it can be the cause of hard to find bugs in scripts.

Categories