I want to check if the user what rank a user has, which is stored in my database as an integer of 0, 1, 2, or 3.
I want it to be echo'd like echo $my_rank; #Instead of it saying 0,1,2,or 3 it says User for 0, Moderator for 1, Admin for 2, and Owner for 3.
Here is my code:
$my_rank = $_SESSION['rank'] = array("owner","administrator","moderator","user");
$rank = array (
'0' => 'user',
'1' => 'moderator',
'2' => 'administrator',
'3' => 'owner'
);
config.php
<?php
# Error Reporting
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
# No Error Reporting
//error_reporting(0);
# Message Responses
$success = array();
$danger = array();
$warning = array();
$info = array();
# Define the Database
define('DB_SERVER','localhost');
define('DB_USERNAME','blah');
define('DB_PASSWORD','blah');
define('DB_DATABASE','blah');
# Connect to the database
$con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (!$con) {
$danger[] = mysqli_connect_error();
} else {
//echo "It worked";
}
?>
Well... Going by the information you've given me, it seems like all that is needed is a query, to get the data from the database. Then we can echo it.
In the else block in your database connection, we can do something like:
# Connect to the database
$con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (!$con) {
$danger[] = mysqli_connect_error();
} else {
//echo "It worked";
// HopefulLlama code below:
// Construct our SQL query, which will retrieve data from the database.
$sql="SELECT * FROM Users";
$result=mysqli_query($con,$sql);
// Loop through all results return by our query
while ($row = mysqli_fetch_assoc($result)) {
// $row['rank'] will contain our Integer of 0, 1, 2, or 3
echo $row['rank']
// This will access your $rank array, and use the index retrieved from the database as an accessor.
echo $rank[$row['rank']]
}
}
One can query the database with sql statements. The one you're looking for is a select upon the usertable:
// array which holds the info
$rank = array ('user', 'moderator', 'administrator', 'owner');
// set up db connection
$con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (!$con) {
$danger[] = mysqli_connect_error();
} else {
//echo "It worked";
// Baklap4's Addition:
// SQL statement to retrieve the row where username is piet
$sql = "SELECT * FROM Users WHERE username = `piet`";
// Execute the query and check if there is a result.
if ($result = $con->query($sql)) {
// if there are results loop through them.
while ($row = mysqli_fetch_assoc($result)) {
// print for each rank a different rank name.
echo $rank[$row['rank']];
}
// free resultset
$result->close();
}
// close connection
$con->close();
//clean up the temp variables
unset($obj);
unset($sql);
unset($result);
}
This will retrieve The user Piet from your database and print the rank (which is listed in the database).
Then it'll unset all the temporary values made within the whileloop so you can't reuse them again.
What you should do is change the hard coded value piet to a variable. One could go to http://localhost/scriptname.php?username=piet to retrieve the same outcome.
To make this a variable change the sql line as following:
$sql = "SELECT * FROM Users WHERE username = $_GET['username']";
Related
I need help with some code. I want to select data from mySQL to a graph on my web page.
The data must be from the current logged in user, and when I select data to a card it works fine, but when I select it to a graph the graph disappears.
I'm using this code for the cards, and it works fine:
$sql = "SELECT energyexpenditure FROM energy4project WHERE user_id = '{$_SESSION["user_id"]}' ORDER BY time_stamp DESC LIMIT 1;";
This is the code for my current graph that don't show data based on logged in user:
<?php
header('Content-Type: application/json');
$host = "localhost";
$user = "`blabla";
$pwd = "blabla";
$db = "blabla";
$conn = new mysqli($host, $user, $pwd, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT energyexpenditure, time_stamp FROM energy4project ORDER BY time_stamp DESC LIMIT 7;";
$result = $conn->query($sql);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
mysqli_close($conn);
echo json_encode($data);
?>
When I implement the code from the cards in the graph code it doesn't work.
Why does the SELECT WHERE user = '{$_SESSION["user_id"]} not work in the graphs?
If I understood good your Mysql query return an empty result. Try to modify your code as follows:
if(!$result = $conn->query($sql)) {
echo "query error.";
die();
}
$data = array();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$data[] = $row;
}
/* free result set */
$result->free();
/* close connection */
$conn->close();
//uncomment the below line if you want to check de result of your mysql query because it seems be good.
//var_dump($data); die(); echo "<pre>";
echo json_encode($data);
So if you don't have any mysql error, verify your database name, table name are correctly and if it has data in your table.
Reference: https://www.php.net/manual/en/mysqli-result.fetch-array.php
Regards
I have a SQL table (modules) with two columns (id, name). Now I can retrieve the rows from this through a PHP script but what I want is to use the value of id as the key, and the value of name as the value, in a multidimensional array. Then I want to be able to encode those into a JSON, retaining the relationship between key/value. I've muddled something together but it returns null.
the relevant code from index.php
$mod1 = $core["module1"];
$mod2 = $core["module2"];
$modules = $db->getModulesById($mod1, $mod2); //module names & ids
$response["module"]["mod1"] = $modules[$mod1];
$response["module"]["mod2"] = $modules[$mod2];
$response["module"]["mod1name"] = $modules[$mod1]["name"];
$response["module"]["mod2name"] = $modules[$mod2]["name"];
echo json_encode($response);
The function from DB_Functions.php
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_error());
}
// selecting database
mysqli_select_db($con, DB_DATABASE) or die(mysqli_connect_error());
$query = "SELECT * FROM modules WHERE id= '$mod1' OR id='$mod2'";
$result = mysqli_query($con, $query);
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
// process each row
//each element of $arr now holds an id and name
$arr[] = $row;
}
// return user details
return mysqli_fetch_array($arr);
close();
}
I've looked around but I'm just not 'getting' how the query return is then broken down into key/value for a new array. If someone could ELI5 I'd appreciate it. I'm just concerned with this aspect, it's a personal project so I'm not focusing on security issues as yet, thanks.
You are pretty well there
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if (!$con) {
die("Connection error: " . mysqli_connect_error());
}
$query = "SELECT * FROM modules WHERE id= '$mod1' OR id='$mod2'";
$result = mysqli_query($con, $query);
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
// here is wrong
//return mysqli_fetch_array($arr);
// instead return the array youy created
return $arr;
}
And call it and then just json_encode the returned array
$mod1 = $core["module1"];
$mod2 = $core["module2"];
$modules = $db->getModulesById($mod1, $mod2); //module names & ids
$response['modules'] = $modules;
echo json_encode($response);
You should really be using prepared and paramterised queries to avoid SQL Injection like this
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if (!$con) {
die("Connection error: " . mysqli_connect_error());
}
$sql = "SELECT * FROM modules WHERE id= ? OR id=?";
$stmt = $con->prepare($sql);
$stmt->bind_param('ii', $mod1, $mod2);
$stmt->execute();
$result = $stmt->get_result();
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
// here is wrong
//return mysqli_fetch_array($arr);
// instead return the array youy created
return $arr;
}
mysqli_fetch_array requires the result of a mysqli_query result. Passing the constructed array to mysqli_fetch_array() is not going to work.
If you want to have a specific value from a row to use as its key, you can't resolve this with any mysqli_* function. You could however construct it yourself:
while($row = mysqli_fetch_assoc($result)) {
// process each row
//each element of $arr now holds an id and name
$arr[$row['id']] = $row;
}
mysqli_close($con);
return $arr;
You should close the connection before returning the result, code positioned after a return will not be executed.
I need some help and I can't figure it out,i tried searching the internet but I found nothing
So I'm using this code from w3schools
<?php
$servername = "localhost"; //Obviously this are set to my parameters
$username = "username"; //Obviously this are set to my parameters
$password = "password"; //Obviously this are set to my parameters
$dbname = "myDB"; //Obviously this are set to my parameters
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Some code goes here
}
} else {
echo "0 results";
}
$conn->close();
?>
How can I modify this code to echo certain items only?
EXAMPLE
I have 10 items in talbe People (Table people contains id,age,name,gender)
I want to echo out 3 out of 10 People by using their ID which are 1 trough 10
I know i can use this AND id IN(1, 5, 9)"; This just echoes them out 1 after another
Is there a way to echo out id 1 goes here , id 5 goes here and than id 9 goes there like in 3 different places with 3 different codes or something? is this even possible?
You could use:
class people
{
public function people()
{
$sql = $this->conn->prepare("SELECT * FROM `people`");
$sql->execute();
$result = $sql->fetch(PDO::FETCH_OBJ);
return $result;
}
}
then when you want certain information you could simply use in say index.php:
$fetch = new people();
$info = $fetch->people();
you can then run simple echo's such as $info->name or $info->id etc etc..
Depending on how you're searching for the user you could just add
WHERE `userid` = :id
$sql->bindParam(':id', $userid);
and add $userid into the people($userid)
But this will vary depending on how you're pulling out specific users.
use this code
<?php
//using PDO
try
{
$conn = new PDO('mysql:dbhost=myhost;dbname=mydbname;', 'user','pass');
}
catch (PDOException $e)
{
echo $e->getMessage();
}
$getId = $conn->query("
SELECT * FROM users
WHERE id = 1
AND id = 5
AND id = 9
");
while ($ids = $getId->fetch(PDO::FETCH_OBJ)
{
echo $getId->id . '<br>';
}
I need to connect to two databases using PHP and use the results from the first query to get the rest of the data I need out of a second database.
So for the second connection, I need to connect to the second database and Select state and zipcode where the results from connection 1 (client) is equal to the firstname in database 2. How would I do this?
<?php
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['cd']) && is_numeric($_GET['cd'])) {
// get id value
$id = intval($_GET['cd']);
}
$results = $id;
//Open a new connection to the MySQL server
require "calendarconnect.php";
//chained PHP functions
$client = $mysqli->query("SELECT client FROM appointments WHERE ID = $results")->fetch_object()->client;
print $client; //output value
$mysqli->close();
Connection To Database Code is similar to the below
<?php
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','some database','some password','some username');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
This isn't tested, but I think it would go something like this.
<?php
$dbc1 = new MySQLi()or die('error connecting to database');
$dbc2 = new MySQLi()or die('error connecting to database');
//build query 1
$query1 = "SELECT * FROM Table";
$result1 = $dbc1->query($query) or die("Error in query");
$thing1 = '';
// check result
if($result1->num_rows){
//fetch result as object
$row = $result1->fetch_object();
//set attributes
$thing1 = $row->Name;
}
//build query 2
$query2 = "SELECT * FROM AnotherTable WHERE Id = '$thing1'";
$result2 = $dbc2->query($query) or die("Error in query");
$thing2 = '';
// check result
if($result2->num_rows){
//fetch result as object
$row = $result2->fetch_object();
//set attributes
$thing2 = $row->Name;
}
?>
You would need to make 2 different connections
<?php
$mysqliDB1 = new mysqli('localhost', 'DB1UserId', 'pwd', 'db1');
$mysqliDB2 = new mysqli('localhost', 'DB2UserId', 'pwd', 'db2');
Now when you use the $mysqliDB1->.... you are talking to the DB1 database and when you use the $mysqliDB2->.... you are talking to the DB2 database
So
$client = $mysqliDB1->query("SELECT client FROM appointments WHERE ID = $results")
->fetch_object();
$locn = $mysqliDB2->query("SELECT state,zipcode
FROM location
WHERE ClientID = {$client->FirstName}")
->fetch_object();
echo $locn->state;
echo $locn->zipcode;
I am guessing the table name and so on, but I am not clarevoyant so you will have to fill that in for yourself.
If you want to perform queries in two databases at the same time you need to have two separate mysqli objects. To open the connection you can use the following code:
// Don't forget to enable error reporting!
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db1 = new mysqli('localhost', 'user', 'pass', 'dbName');
$db1->set_charset('utf8mb4'); // always set the charset
$db2 = new mysqli('localhost', 'user', 'pass', 'dbName2');
$db2->set_charset('utf8mb4'); // always set the charset
Then you can perform your two statements in each database separately.
// get id value
$id = intval($_GET['cd']);
// Get client name from DB1
$stmt = $db1->prepare('SELECT client FROM appointments WHERE ID = ?');
$stmt->bind_param('s', $id);
$stmt->execute();
$client = $stmt->get_result()->fetch_object();
// Get state and zipcode from DB2
$stmt = $db2->prepare('SELECT state,zipcode FROM location WHERE ClientName = ?');
$stmt->bind_param('s', $client->client);
$stmt->execute();
$location = $stmt->get_result()->fetch_object();
echo $location->state;
echo $location->zipcode;
I've got an sql query that contains a number of statements. It:
sets a user variable
calls a stored procedure
calls another stored procedure
selects some data
I know that the query is correct, because I've tested it in MySQL Workbench, under the same user. The query is this:
set #current_post = 535; /* 535 for testing, this will be a variable */
call under_user_type(#currrent_post, #user_type, #user_id);
call get_category(#current_post, #category);
select p.post_title, p.post_name,
(
swell_wp.post_score(p.ID)
) as score,
(
swell_wp.is_under_user(p.ID, #user_type, #user_id)
) as under_user,
(
swell_wp.is_under_category(p.ID, #category)
) as under_category
from wp_posts as p
where p.post_type = 'post'
and p.id != #current_post
and p.post_status = 'publish'
having (
under_user = true
or under_category = true
)
order by score desc;
that's just stored in a string: $sql. I then do this with it in PHP:
$query = new MySQLi(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$query->multi_query($sql);
do {
$query->next_result();
} while( ! $result = $query->use_result() );
print_r($result);
this prints a result object, but one that is empty. Trying to iterate over it doesn't produce any results either.
What am I doing wrong? Can I even use user variables like this? Or will I need to turn the procedures into stored functions and do three separate queries?
Try this:
$query = new MySQLi(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($query->multi_query($sql)) {
do {
if ($result = $query->use_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
} while ($query->next_result());
} else {
echo 'ERROR FOR QUERY!';
}
This should help you trap any errors. Also, I think your use_result needs to be swapped with the next_result.
UPDATED: One other thing, have you checks to make sure the variables you are passing to the query actually contain data? Print our the query to make sure you can run it in the database and get results manually too.
You are apparently not fetching the rows from the result. Please change the code to this and it will print the results.
$query = new MySQLi(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$query->multi_query($sql);
do {
/* store first result set */
if ($result = $query->use_result())
{
while ($row = $result->fetch_row())
{
print_r($row);
}
$result->close();
}
/* print divider */
if ($query->more_results())
{
printf("-----------------\n");
}
} while ($query->next_result());