Load MySQL Data into Corresponding PHP Variables - php

I got this work for me, but I'm sure there's a better way to get this done. But, I've searched many hours without finding the exact answer to what I'm looking to do. Basically getting the variable usrID from the URL, I need to search MySQL for the corresponding information to this user. Later I want to use the different fields on my page (better website) to personalize the experience.
<?php
$servername = "localhost";
$username = "authorized-user";
$password = "secret";
$dbname = "agentDB";
$usrID = "001";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM agentInfo WHERE usrID = '$usrID'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$Lname = $row["Lname"];
$Fname = $row["Fname"];
$tl = $row["tl"];
}
}
mysqli_close($conn);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Load MySQL Data into Corresponding PHP Variables</title>
</head>
<body>
here is the body<br>
My name is: <?php echo $Fname; ?> <?php echo $Lname; ?><?php echo $tl; ?>
</body>
</html>

You could create a variable to store a full name and then "tl" on it like this:
$user_info = $Lname . ", " . $Fname . ": " . $tl;
Then:
<?php echo $user_info; ?>
Wherever you need that information.
If you want to minimize the amount of variables being assigned you could wrap it in a function and return the desired data field:
function fetchUserData(userData) {
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM agentInfo WHERE usrID = '$usrID'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$userData = $row[userData];
}
}
return $userData;
}
mysqli_close($conn);
You can the get the specified data like this:
<?php echo fetchUserData("Fname"); ?>

Related

How to write WHERE referring to a drop down list select?

There is a drop-down list on the PHP website that contains names taken from the database,
after selecting a name from the list, e.g. "Aprilia", I would like all records to be displayed from the database
where mark = Aprilia
I know I should add in the code below just in a SELECT WHERE x = y query
but I just don't know how to do it;
it should look like this in my opinion:
$result = mysqli_query($conn, "SELECT * FROM motorcycles WHERE mark = X");
And I just can't find this X (X should be the user pick from the dropdown list)
How to write it?
Photos:
https://imgur.com/a/PMu4At7
<?php
require_once 'header.php';
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "projectinz";
// Create connection
//$conn = new mysqli($servername, $username, $password, $dbname);
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<select name="mark" id="mark">
<?php
$query = $conn->query("SELECT mark FROM motocykle");
while($kategoria = mysqli_fetch_array($query))
{
echo '<option>'.$kategoria['mark'].'</option>';
}
?>
</select>
<?php
$wynik = mysqli_query($conn,"SELECT * FROM motocykle");
while($row = mysqli_fetch_array($wynik))
{
echo "<br>".$row['mark']." ".$row['model']." ".$row['capacity']." ".$row['power']."<br>";
}
mysqli_close($conn);
?>
</body>
</html>
EDIT !!!
find1.php
<?php
require_once 'header.php';
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "projectinz";
// Create connection
//$conn = new mysqli($servername, $username, $password, $dbname);
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<form action="../includes/find.inc.php" method="post">
<select name="mark" id="mark">
<?php
$query = $conn->query("SELECT mark FROM motocykle");
while ($kategoria = mysqli_fetch_array($query)) {
echo '<option value="id">'.$kategoria['mark'].'</option>';
}
?>
</select>
<button type="submit" name="findmoto">Find</button>
</form>
<?php
$wynik = mysqli_query($conn,"SELECT * FROM motocykle ");
while ($row = mysqli_fetch_array($wynik)) {
echo "<br>".$row['mark']." ".$row['model']." ".$row['capacity']." ".$row['power']."<br>";
}
mysqli_close($conn);
?>
</body>
</html>
find.inc.php
<?php
session_start();
if (isset($_POST['findmoto'])) {
require 'dbh.inc.php';
$id = $_POST["id"];
$marka = $_POST["mark"];
echo $id;
echo $marka;
$display = "SELECT * FROM motocykle WHERE id='$id';";
$run = mysqli_query($conn, $display);
if ($run) {
echo $display;
} else {
echo "not";
}
}
BUT:
https://imgur.com/a/RA5wuus
Where is the problem?
<option value="1">Name</option> has attribute value witch is sent to POST when form is submitted. You need to set it with probably ID from table and then after POST you filter by that ID in WHERE part of your SQL.
First change
<select name="mark" id="mark">
<?php
$query = $conn->query("SELECT id, mark FROM motocykle");
while($kategoria = mysqli_fetch_array($query))
{
echo '<option value="'.$kategoria['id'].'">'.$kategoria['mark'].'</option>';
}
?>
</select>
Second change
if(isset($_POST['findmoto'])) {
require 'dbh.inc.php';
$selectedId = intval($_POST["mark"]);
echo $selectedId;
$display = "SELECT * FROM motocykle WHERE id='$selectedId';";
$run = mysqli_query($conn, $display);
if($run)
{
echo $display;
}
else
{
echo "not";
}
}

What is the best way to simply show the first name, on html page, retrieved from database?

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'blood_db';
$connection = new mysqli($dbhost,$dbuser,$dbpass,$db);
if($connection->connect_error){
die("Server Error ".$connection->connect_error);
}
else{
$query = ("SELECT first_name FROM accounts WHERE email_address = '".$_SESSION['username']."'");
$obj = $connection->query($query);
echo "Welcome ".$obj->first_name;
here it shows a notice, which is "
Notice: Undefined property: mysqli_result::$first_name "
It is returning the object, So how would i extract the first name from it?
// printf("Welcome %s",$result->);
echo '<br>Logout';
use below code
$result = $connection->query($query);
if($result){
$row = $result->fetch_assoc();
echo "Welcome ".$row['first_name'];
}else{
// check error
}
you can try this which select data and add condition if you want to check that data empty or not
$obj = $connection->query($query);
if ($obj->num_rows > 0) {
$row = $obj->fetch_assoc();
echo "Welcome ".$row['first_name'];
}
if you do not want to check data have then use this
$row = $obj->fetch_assoc();
echo "Welcome ".$row['first_name'];
for more information
https://www.w3schools.com/php/php_mysql_select.asp
A very basic example would be like this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$firstname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM tbl_test WHERE email_address = '". $_SESSION['username']. "'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Retrieve Firstname
while($row = $result->fetch_assoc()) {
$firstname = $row["first_name"];
}
} else {
echo "No results found!";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<header>
<h3>Welcome <?php echo $firstname; ?></h3>
</header>
</body>
</html>
<?php
$conn->close();
?>

Convert DEC value into hexadecimal in a table column

Actually I guess the question is duplicate, but I didn't understand whats the WRONG with my SQL code. My error is
Notice: Undefined index: CI in
C:\wamp\www\LOCATIONVIEWER\exampleDB.php on line 30.
I need to convert all decimal value of column into hexadecimal value. Help me to do it... :)
Here is my code:
<html>
<head>
<title>test</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "locationviewer";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//CI is a column name of the table
$sql = "SELECT CONV(CI,10,16) FROM locationdata";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "CI: " . $row["CI"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
You should change following code:
$sql = "SELECT CONV(CI,10,16) FROM locationdata";
To
$sql = "SELECT CONV(CI,10,16) AS `CI` FROM locationdata";
this issue happened because php can not see CI index and current index is somthing like CONV(CI,10,16)

background refresh information from database AJAX

I have created a website which retrieves text which has been uploaded to my database. the problem with this is i want a refresh of the content from that database ever second. but i can't find how to do this anywhere. i want this done in the background. and if possible a way to make the textbook that i will put in later to input the data into the server, also not do a full refresh but send the content in the background. thank you every answer will count.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY id ASC LIMIT 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<div id='message'> <br> ". $row["firstname"]. " " . $row["lastname"] . "<br> </div>";
}
} else {
echo "0 results";
}
$conn->close();
?>
In a file, simply echo out the results. Then in another file, load the echoed results in a div like this:
db_results.php file which will echo out results:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY id ASC LIMIT 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<p>". $row["firstname"]. " " . $row["lastname"] . "</p>";
}
} else {
echo "0 results";
}
$conn->close();
?>
display.php file which will refresh the results in a div:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
setInterval(function() {
$("#load_results").load("db_results.php");
}, 1000);
});
</script>
</head>
<body>
<div id = "load_results"></div>
</body>
</html>
db_results.php file will query database, will fetch the results and will echo them out. The second file (display.php) loads the first file in a div and refreshes the div every second, so updated results are loaded in the concerned div.
P.S.: Keep both files in same directory or adjust the path accordingly.

Getting data from MySQL table via Codeigniter

I'm having issues getting this data from within a codeigniter Controller.
$q = $this->db->get('offers_orders');
$this->db->select('total');
$this->db->where('order_number', $orderid);
$orderdata = $q->result_array();
$orderamount = $orderdata[0]['total'];
Do you see anything wrong with this code ?.
Yes, Try :
$this->db->select('count(*) as total', false);
$this->db->where('order_number', $orderid);
$q = $this->db->get('offers_orders');
OR,
$q = $this->db->select('count(*) as total', false)->where('order_number', $orderid)->get('offers_orders');
You need first to defined your select and where method then you call the get() method which are used for get data.
Like this:
$this->db->select('total');
$this->db->where('order_number', $orderid);
$q = $this->db->get('offers_orders');
And as I see from your query, you need to fetch only one result and for it better solution is to use row() function because this function returns a single result row.
Like this:
$orderdata = $q->row();
$orderamount = $orderdata->total;
Also to learn more about it you can read this acticle.
<!DOCTYPE html>
<html>
<body>
<?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);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>

Categories