Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to select data from a database, dependent on the user and echo it in the html code, but for some reason it won't capture the data.. please see code below:
<?php
$loginuser = $_GET['uid'];
$check = mysql_query("select * from users where username='$loginuser'");
while($row = mysql_fetch_array($check)){
$result = $row['email'];
$result = $row['firstname'];
}
?>
<html>
<head>
<title> SIAA Dashboard </title>
</head>
<body>
<h1> User Dashboard </h1>
<p> You should only see this screen if you are a registered user. </p>
<?php
echo "Your username is: " . $loginuser . "<br><br>";
echo "Your first name is: " . $result=$row['firstname'] . " ";
?>
</body>
</html>
If someone could tell me what I'm doing wrong, it will be much appreciated!
Thanks
Sohail.
A few notes:
Don't use mysql_... functions: they're deprecated. See the documentation
Check whether the input is supplied using isset: if uid is missing from $_GET the visitor will see a PHP warning.
Escape/sanitize user input! If anyone requests your php file with ?uid='; drop table users;-- you're going to have a problem!
If you expect 0 or 1 results, don't use a while loop
Better not use constructs like echo "foo" . $bar = $baz . "something";: it's unclear.
And a suggestion on how to structure your page:
<html>
<head>
<title> SIAA Dashboard </title>
</head>
<body>
<?php
$loginuser = isset( $_GET['uid'] ) ? $_GET['uid'] : null;
if ( empty( $loginuser ) )
{
echo "Missing parameter!";
}
else
{
$check = mysql_query("select * from users where username='"
. mysql_real_escape_string( $loginuser ) . "'" );
if ( $row = mysql_fetch_array($check) )
{
?>
<h1> User Dashboard </h1>
<p> You should only see this screen if you are a registered user. </p>
Your username is: <?php echo $loginuser; ?>
<br><br>
Your first name is: <?php echo $row['firstname']; ?>
<?php
}
else
{
echo "Unknown user!";
}
}
?>
</body>
</html>
Besides that your code is prone to SQL injection as you do not sanitze the $__GET Parameter 'uid' before inserting it in the query and you are using the deprecated mysql extension, your problem is the line
echo "Your first name is: " . $result=$row['firstname'] . " ";
which should read
echo "Your first name is: " . $row['firstname'];
Additionally, you did not establish a connection to the database.
First do not use mysql_* functions and you need to create a mysql connection. This is still as risk for injection but should work.
<?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);
}
$loginuser = $conn->real_escape_string($_GET['uid']);
$sql = "SELECT * FROM `users` WHERE `username` = '$loginuser'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$data = $result->fetch_assoc();
}
$conn->close();
?>
<html>
<head>
<title> SIAA Dashboard </title>
</head>
<body>
<h1> User Dashboard </h1>
<p> You should only see this screen if you are a registered user. </p>
<?php
echo "Your username is: " . $loginuser . "<br><br>";
echo "Your first name is: " . $data['firstname'] . " ";
?>
</body>
</html>
/*
* Best to start using PDO for db, If i was you i would rewrite your entire db script and stay away from mysql.
*
*/
$id = $_GET['uid'];
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $DBusername, $DBpassword);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM users where username= :id');
$stmt->execute(array('id' => $id));
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
print_r($row); // $row will give you access for your variables.
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
<html>
<head>
<title> SIAA Dashboard </title>
</head>
<body>
<h1> User Dashboard </h1>
<p> You should only see this screen if you are a registered user. </p>
<?php
echo "Your username is: " . $loginuser . "<br><br>";
echo "Your first name is: " . $result=$row['firstname'] . " ";
?>
</body>
</html>
Related
I support a database how can I share a variable from one page to another?
My page choose.php when it is loaded generates buttons with a field value of a database table as value.
I have to make sure that at the click of the button:
- save me a table data ("id")
- I am redirected to another page
- on the page where I am redirected to get the variable and put it in a query
it's possible? If so how?
<!DOCTYPE html>
<?php
session_start();
if(!isset($_SESSION["username"])){
header('location: ../index.php');
}else
{
?>
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT idCantiere,nomeCantiere,codiceCommessa,indirizzoCantiere FROM Cantiere";
$result = $conn->query($sql);
echo'<h1> <font face="verdana" color="green">Quale Cantiere desideri Modificare?</font> </h1>';
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo'<br><br><br>';
echo'' . $row["nomeCantiere"] . '';
}
echo'<br><br><br>';
echo 'Nuovo Cantiere +';
} else {
echo "0 results";
}
$idCantierePerSelect = $_POST["idCantiere"];
global = $idCantierePerSelect;
echo $idCantierePerSelect;
$conn->close();
?>
For now I only managed to do the automatic loading of the buttons ...
and I thought of putting "idCantiere", which is the field that I have to go from table to table, global
One way of passing variables between pages is 'posting' it in the URL.
This question has been answered before, look here.
Passing multiple variables to another page in url
In short add:
Then at index.php do
$idCantiere = $_GET['idCantiere']
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"); ?>
I have a search form that is able to retrieve the username of a user, however I can't figure out how to get it to return more than that, I want it to display the first names and last names too.
Below is the code at the minute that works, but when I try and add in more variables, for example if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE ?")) then it doesn't return anything at all and asks to insert a search query.
I have also tried if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE %?%")) and LIKE "%?%")), but no results.
search.php
<?php
include 'connection.php';
if(isset($_POST['searchsubmit']))
{
include 'searchform.php';
$name=$_POST['name'];
if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE ?"))
{
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($personresult);
$stmt->fetch();
?>
<center>
<BR>
<h1>Search Results are as follows:</h1>
<h2>USERNAMES</h2>
<BR>
<?php
print_r($personresult);
?>
</center>
<?php
}
else
{
echo "<p>Please enter a search query</p>";
}
}
else
{
echo "NOT SET!";
}
You are only calling Username .. You need to be calling *
SELECT * FROM users WHERE Username LIKE ?
This is my personal script I use:
<?php
$dbservername = "localhost";
$dbusername = "db_user";
$dbpassword = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (!empty($_POST["username"])) {
$username = $_POST["username"];
}
if (!empty($_POST["password"])) {
$password = $_POST["password"];
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row["Username"] . " " . $row["Firstname"] . " " . $row["Lastname"] . "<br>";
if ($row["Username"] == $username && $row["Password"] == $password) {
echo "success";
// do more stuff here like set session etc
} else {
$echo "incorrect username and/or password";
}
}
}
?>
Are you initializing the statement object with mysqli_stmt_init?
See mysqli_stmt_init and mysqli-stmt.prepare
If the database server cannot successfully prepare the statement,
PDO::prepare() returns FALSE or emits PDOException (depending on error
handling)
add this line in connection.php right after creating connection object:
$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
At least, you can trace possible errors
<?php
include 'connection.php';
if( isset( $_POST['searchsubmit'] ) ) {
include 'searchform.php';
$name=$_POST['name'];
if ( $stmt = $connection->prepare ("SELECT `Username`,`firstname`,`lastname` FROM `users` WHERE `Username` LIKE ?") ) {
/* not 100% sure about whether this is required here like this or not but usually a like expression uses '%' as a wildcard */
$var='%'.$name'.%';
$stmt->bind_param('s', $var );
$res=$stmt->execute();
/* 3 columns selected in query, 3 columns bound in results */
$stmt->bind_result( $personresult, $firstname, $lastname );
if( $res ){
$stmt->fetch();
echo "
<center>
<BR>
<h1>Search Results are as follows:</h1>
<h2>USERNAMES</h2><!-- 3 columns/variables -->
{$personresult},{$firstname},{$lastname}
<BR>
</center>";
}
} else {
echo "<p>Please enter a search query</p>";
}
} else {
echo "NOT SET!";
}
$stmt->close();
$connection->close();
?>
As of recently ive been learning php and at that conjuntion in between where i have to now use Mysql in order to keep my bigger info table ogranized, well i wrote this code in order to show the tables (or so i think i did it right). im completely stumped because i can not see any of the displaying tables that i am calling on and the more ive tried the less i works so i was wondering if anyone can see a loop hole in my code or maybe im doing something wrong? or maybe everything ive done is wrong...?
`
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno () . ")"
);
}
?>
<?php
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed");
}
?>
<!doctype html>
<html lang="en">
<head>
<title>databases</title>
</head>
<body>
<ul>
<?php
while($subject = mysqli_fetch_assoc($result)) {
?>
<li><?php echo $subject["menu_name"] . "(" . $subject["id"] . ")"; ?></li>
<?php
}
?>
</ul>
<?php
mysqli_free_result($result);
?>
</body>
</html>
<?php
mysqli_close($connection);
?>`
Have you forgotten the opening PHP tag at the beginning of your page?
<?php
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno () . ")"
);
}
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed");
}
?>
Two things i think could be wrong.
Here is a correct implementation to compare. It could be the first PHP opening tag, i also added the default port to the connect statement, and added some try catches with error messages, these can tell if the connect or query is not working.
<?php
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
//original connect statement with a port added in
try {
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname , 3306);
} catch(Exception $e) { echo $e->getMessage(); }
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//Query looks fine, easier to trouble shoot when its one line, first get it working then break it up
$query = "SELECT * FROM subjects WHERE visible = 1 ORDER BY position ASC";
// This will try to fetch the result and give an error if it can't.
try { $result = mysqli_query($connection, $query);
} catch(Exception $e) { echo $e->getMessage(); }
if (!$result) { die("Database query failed"); }
?>
Is it alright if I alter some of your codes?
See this:
<!doctype html>
<html lang="en">
<head>
<title>databases</title>
</head>
<body>
<?php
/* ESTABLISH CONNECTION */
$connection=mysqli_connect("localhost","juliegri_AAlassa","YourPassword","juliegri_Aalassaly");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
/* START QUERY */
$result=mysqli_query($connection,"SELECT * FROM subjects WHERE visible='1' ORDER BY position ASC");
?>
<ul>
<?php
/* DO THE WHILE LOOP */
while($subject = mysqli_fetch_array($result)) {
?>
<li><?php echo $subject['menu_name'] . "(" . $subject['id'] . ")"; ?></li>
<?php
} /* END OF WHILE LOOP */
?>
</ul>
</body>
</html>
I'm newbie to pdo. Here I'm trying to edit and update my database records using pdo. Below I posted my two pages coding here. In main page I've fetch the details of particular database table. If user clicks Edit link it will redirect to another page for edit the values of particular record using GET['id'];. In editpage I'm trying to fetch my already stored values. But I cannot able to fetch it. I tried print_r($username); and var_dump($username);. It didn't show the value in editpage.
Mainpage PHP coding :
<?php
include('config.php');
$sql = "SELECT * FROM ebusers";
$db = $conn->query($sql);
$db->setFetchMode(PDO::FETCH_ASSOC);
while($row = $db->fetch())
{
echo "<td>". $row['UserID'] ."</td>";
echo "<br>";
echo "<td><a target=_blank href='edit.php?id=". $row['UserName'] ."'>Edit</a></td>";
echo "<br>";
}
?>
Editpage PHP coding:
<?php
include('config.php');
$uid = $_GET['id'];
$sql = "SELECT * FROM ebusers WHERE UserID = '$uid'";
$db = $conn->query($sql);
$db->setFetchMode(PDO::FETCH_ASSOC);
if($db->fetchColumn()>=1)
{
while($row = $db->fetch())
{
$username = $row['UserName'];
}
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form action="delete.php" method="post">
<input type="text" name="name" value="<?php echo $username;?>" />
<input type="submit" />
</form>
</body>
</html>
Config PHP page
$user = "root";
$password = "password";
try
{
$conn = new PDO('mysql:host=localhost;dbname=evouchers', $user, $password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo 'DATABASE ERROR : ' . $e->getMessage();
}
I don't know where I made a mistake?
Why are you fetching the first column first. Evaluate it in an if statement. And after that fetch the whole row?
What happens when you change
if($db->fetchColumn()>=1)
{
while($row = $db->fetch())
{
$username = $row['UserName'];
}
}
to
while($row = $db->fetch())
{
var_dump($row['UserName']);
}