Assign row values from SQL to php variables from URL query - php

I have a SQL table, a php page. Both set up on a website using cPanel hosting.
The SQL table is like this. Table name is "dbase".
It has two columns, id and name and each column has two rows, say.
Id -> 01, 02
Name -> Name1, Name2.
What I want to do is.
If my page URL is examp.le/page.php?id=01 , or something like that which has a parameter 'id' valued as 01.
How do I assign value for php variable in that page say, $name as the corresponding value for 'name' column in the '01' row?

You have to get the parameter form the url using $_GET[] and then you have to query from the table to get the Name.
Just try this. Hope it helps you.
$id = $_GET['id'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM dbase where Id=".$id;
$result = $conn->query($sql);
$name;
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
$name = $row['Name'];
} else {
echo "0 results";
}
Now just access $name wherever you want

Related

How to fetch a single row from a MySQL DB using MySQLi with PHP? [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I am using PHP with MySQli and I want to fetch a single row from the whole SQL DB, which fits in my condition. Just for a note, this is what my current database looks like :
I want to get that single row where, eg. txnid column's value == $txnid (a variable). I tried to build the SQL Query which would fit my requirements, and here's how it looks like : $sql = "SELECT * FROM 'table1' WHERE 'txnid' = " . $txnid;. When I raw-run this Query in phpMyAdmin, it works as expected. I just want to know, after I run the Query in PHP, how to fetch that row's data which came in as response from the Query using MySQLi?
This is the code which I am using to run the Query :
$servername = "localhost";
$username = "XXXXXXXXXXXXXX";
$password = "XXXXXXXXXXXXXX";
$dbname = "XXXXXXXXXXXXXXXX";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$txnid = $_GET['id'];
$sql = "SELECT * FROM `testtable1` WHERE `txnid` = " . $txnid;
if ($conn->query($sql) === TRUE) {
echo ""; //what should I do here, if I want to echo the 'date' param of the fetched row?
} else {
echo "Error: " . $sql . "<br>" . $conn->error . "<br>";
}
Add LIMIT 1 to the end of your query to produce a single row of data.
Your method is vulnerable to SQL injection. Use prepared statements to avoid this. Here are some links you can review:
What is SQL injection?
https://en.wikipedia.org/wiki/SQL_injection
https://phpdelusions.net/mysqli_examples/prepared_select
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8mb4");
$txnid= $_GET['name_of_txnid_input_field'];
// prepare and bind
$stmt = $conn->prepare("SELECT * FROM `testtable1` WHERE `txnid` = ? LIMIT 1");
$stmt->bind_param("i", $txnid);
// set parameters and execute
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo $row['date_field_you_want_to_display'];
$txnid = $_POST['txnid'];
$sql = "SELECT * FROM tableName WHERE txnid = $txnid";
$result = $conn->query($sql);

How to loop through each item in database

I have a PHP script I'm writing where I have to get data from a database and convert the results into a static HTML page. I'm trying to loop through all the items 1 by 1 in a particular database and grab the value that's in their "nid" column as I go along. I started the script. I have the database connection. Just stuck on how I should do the loop. Should it be a while loop or a for loop? If so how do I go about looping through the items in the table 1 by 1 and grabbing a particular column value? Also attached is the screenshot of the database so you can see the column I'm trying to target.
<?php
// Establish all database credential variables
$serverName = "localhost";
$username = "admin";
$password = "peaches";
$databaseName = "static_site";
// Create Database Connection
$connection = new mysqli($serverName, $username, $password, $databaseName);
// Check Database Connection
if ($connection->connect_error) {
die("Connection failed:" . $connection->connect_error);
} // line ends if statement
$queryNodeRevision = "SELECT nid FROM node_revision";
// line above creates variable $queryNodeRevision > selects column "nid" from table "node_revision"
$dataBaseQueryResults = mysqli_query($connection, $queryNodeRevision);
// line above creates variable $dataBaseQueryResults > actually queries the database and passes in 2 variables
// passes in database connection variable and variable that selects "nid" column from "node_revision" table
?>
Use while loop and mysqli_fetch_array to fetch the value of nid for each row.
$queryNodeRevision = "SELECT nid FROM node_revision";
$results=mysqli_query($queryNodeRevision);
while ($row = mysqli_fetch_array($results)) {
echo $row['nid'];
}

how to include a php variable as part of a table name?

I have a site where I needed to use separate table names for each of my clients because the data has to be updated all the time with a manual import.
example:
kansas_users
newyork_users
I have set a global variable as $client which will create the state name on all pages so if I echo "$client"; then I will see "kansas" for example on any page.
I would like to include this variable as part of my SQL query if possible to make it easier to code:
SELECT "nick, firstname, lastname, cell
FROM database.$client_members
where active =1 and id = $user->id";
Is this possible or even safe to do?
Yes it possible you can do some thing like below
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$client = 'kansas';
$table_name = "database." . $conn->real_escape_string($client) . "_members";
$query = sprintf("SELECT nick, firstname, lastname, cell
FROM %s WHERE active = 1 and id = ?", $table_name);
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user->id);
But i think you should seriously consider normalizing your database to avoid such issues

Query records belonging to the logged in user

I've written the below query:
At the moment this pulls back everything from the MarketingCampaigns table, regardless of which user created the record.
I need to be able to return the result, which counts only the records created by that user.
<?php
$servername = "localhost";
$username = "root";
$password = "doimkr943k3f";
$dbname = "crm4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT format(count(id),0) as id12 FROM MarketingCampaigns";
$result2 = $conn->query($sql);
$row = $result2->fetch_assoc();
echo $row["id12"];
?>
The below is a query I can see has been 'auto-generated' by the tool I use, which checks which fields the user should see in table view. I'm just really unsure how to convert this into the simple, single value SQL queries I have above.
// mm: build the query based on current member's permissions
$DisplayRecords = $_REQUEST['DisplayRecords'];
if(!in_array($DisplayRecords, array('user', 'group'))){ $DisplayRecords = 'all'; }
if($perm[2]==1 || ($perm[2]>1 && $DisplayRecords=='user' && !$_REQUEST['NoFilter_x'])){ // view owner only
$x->QueryFrom.=', membership_userrecords';
$x->QueryWhere="where `Complaints`.`id`=membership_userrecords.pkValue and membership_userrecords.tableName='Complaints' and lcase(membership_userrecords.memberID)='".getLoggedMemberID()."'";
}elseif($perm[2]==2 || ($perm[2]>2 && $DisplayRecords=='group' && !$_REQUEST['NoFilter_x'])){ // view group only
$x->QueryFrom.=', membership_userrecords';
$x->QueryWhere="where `Complaints`.`id`=membership_userrecords.pkValue and membership_userrecords.tableName='Complaints' and membership_userrecords.groupID='".getLoggedGroupID()."'";
}elseif($perm[2]==3){ // view all
// no further action
}elseif($perm[2]==0){ // view none
$x->QueryFields = array("Not enough permissions" => "NEP");
$x->QueryFrom = '`Complaints`';
$x->QueryWhere = '';
$x->DefaultSortField = '';
}
I have a table called membership_userrecords which includes the below fields.
You can see the PK value in the table and which user owns it.
I'm just not sure how to do the SQL query.
Can you help?
EDIT: I really need to work on my PHP syntax lol. Thanks #aynber
Assuming the username and the memberID are the same, this should be your query.
$sql= $conn->prepare("SELECT format(count(*),0) as id12 FROM MarketingCampaigns where memberID = ?");
$sql->bind_param("s", $username);
$sql->execute();
$sql->bind_result($row);
$sql->fetch();
echo $row;
I'm really unsure about your data here.

How to get session variable from 2 different tables?

I am new in PHP. I use session first time. I have two tables in db. First table with name pacra_teams with column id and title. Second table is og_users with multiple column but i use team_title as foreign key as store id against team title.
Now i want to create a session and want to display team name from table pacra_teams and user name from table og_users.
I try following code but i failed.
<?php
// starts session
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
LIMIT 1
";
// setting variable values during session
$_SESSION['og_users.username']=$username;
$_SESSION['pacra_teams.title']=$title;
?>
call these variables
<?php
session_start();
?>
<?php
print_r($_SESSION);
?>
Please help me how i can do this?
One Thing More. if i run seesion.php page it display undefine variable "title"
and if i run print code. It display username "root" but i dont have any user name root in my db
You already defined a query but didn't execute it.
// starts session
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
LIMIT 1
";
$result = $conn->query($sql);
$row = $result->fetch_object();
// setting variable values during session
$_SESSION['og_users.username'] = $row->USER_NAME; // Change to correct column name in table og_users
$_SESSION['pacra_teams.title'] = $row->TITLE_COLUMN_NAME; // Change to correct column name in table pacra_teams
The result will be the same every time without a WHERE clause in your sql statement. It's only going to return the first row it finds. It looks like you're trying to set user information in a session variable so you can call the data throughout your application so here's a possible solution assuming you grab an ID for the user somewhere (IE web form).
This is a simple answer to explain a concept, not a tutorial.
<?php
//Setup your connection stuff here
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";
//Get a user's name from a form
$userName = $_POST['username'];
// Perform your query
$db= new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
WHERE og_users.username = {$userName} LIMIT 1";
if(!$result = $db->query($sql)){
die('Error [' . $db->error . ']');
}
// Setting variable values during session
while($row = $result->fetch_assoc()) {
$_SESSION['ogUsername'] = $row['USERNAME']; // USERNAME is a placeholder for the example
$_SESSION['pacraTeamsTitle'] = $row['TITLE']; // Same here
}
It's not perfect, but hopefully it helps explain the concept and helps you complete your task.

Categories