I have a database called $addressdb. I want to search through a table on that database with a result the user inputted ($usersName). My mistake is probably really stupid. I am new with mySQL.
<?php
//IF THE LOGIN is submitted...
if ($_POST['Login']){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "addressdb";
$usersName = $_POST['users'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT userID, userName FROM users WHERE userName =$usersName";
$result = mysqli_query($conn, $sql);
...
My line of error is
$sql = "SELECT userID, userName FROM users WHERE userName =$usersName";
More specifically the variable call.
Best approach is :
$sql = "SELECT userID, userName FROM users WHERE userName ='".mysqli_real_escape_string($conn, $usersName)."'";
Here it is not so applicable since you are passing the plain text. But when taking data from html page you should use this way.
Try something like this :
$sql = "SELECT userID, userName FROM users WHERE userName = '".$usersName."'";
You need to use quotes around your $userName.
$sql = "SELECT userID, userName FROM users WHERE userName = '$usersName'";
But to be clear, you should escape your user input at least with mysqli_real_escape_string($conn, $userName);
Related
I want to select the password data of a user so they can log in on my website (for a member only website). I have a hash of the password and the username written to a table called "users" upon account creation. I do not know how to select a row on the table, so I get the error when the code looks for, something?
I found this on w3, but I don't understand what each part of the code means.
I tried to edit the code so it would match my user case, but I don't know how to.
$servername ="127.0.0.1";
$dbusername = "root";
$dbpassword = "";
$dbname = "users";
//create connection to db
$conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
$sql = "SELECT id, username, password FROM users";
$result == $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row == $result->fetch_assoc()) {
echo $userid = $row["id"] && $serverpassword = $row["password"] && $serverusername = $row["username"];
}
} else {
echo "User Lookup Failed";
}
$conn->close();
You don't need to select all records from database and then iterate all of them to check correct user. Besides, you should only select user by username and password as below:
$sql = "SELECT id, username, password FROM users WHERE username = '".$serverusername."' AND `password` = '".serverpassword."' ";
Apart, you should use data binding instead of variable to avoid SQL injection.
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
First i would like to say thank you for letting me ask questions again. I know my previous question was a bit low level of knowledge. Today, I would like to ask if the principle of converting mysql to mysqli in ajax is same with html. Suppose this is my Connect.php
<?php
$host = "localhost";
$dbusername = "root";
$dbpassword = "765632";
$dbname = "student";
$link_id = mysqli_connect($host,$dbusername,$dbpassword,$dbname) or die("Error " . mysqli_error($link_id));
?>
and my ajax.php is
<?php
//Connect to MySQL Server
include 'Connect.php';
mysql_connect($host, $dbusername, $dbpassword);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Escape User Input to help prevent SQL Injection
$first_name = mysql_real_escape_string(trim($_GET['first_name']));
// Retrieve data from Query
$query = "SELECT student_id, LRN, first_name, last_name, grade, section FROM student_information WHERE first_name LIKE '%{$first_name}%'";
$result = mysql_query($query) or die(mysql_error());
//Generate the output
$searchResults = '';
if(!mysql_num_rows($result))
What are the changes should i made to convert it to mysqli without changing its logical scheme.
Did you mean this?
$link_id = mysqli_connect($host, $dbusername, $dbpassword);
//Select Database
mysqli_select_db($link_id, $dbname) or die(mysqli_error($link_id));
// Escape User Input to help prevent SQL Injection
$first_name = mysqli_real_escape_string($link_id, trim($_GET['first_name']));
// Retrieve data from Query
$query = "SELECT student_id, LRN, first_name, last_name, grade, section FROM student_information WHERE first_name LIKE '%{$first_name}%'";
$result = mysqli_query($link_id, $query) or die(mysqli_error($link_id));
//Generate the output
$searchResults = '';
if(!mysqli_num_rows($result))
im having problems in PHP with selecting Infomation from a database where username is equal to $myusername
I can get it to echo the username using sessions from the login page to the logged in page.
But I want to be able to select things like 'bio' and 'email' from that database and put them into variables called $bio and $email so i can echo them.
This is what the database looks like:
Any ideas?:/
You should connect to your database and then fetch the row like this:
// DATABASE INFORMATION
$server = 'localhost';
$database = 'DATABASE';
$dbuser = 'DATABASE_USERNAME';
$dbpassword = 'DATABASE_PASSWORD';
//CONNECT TO DATABASE
$connect = mysql_connect("$server", "$dbuser", "$dbpassword")
OR die(mysql_error());
mysql_select_db("$database", $connect);
//ALWAYS ESCAPE STRINGS IF YOU HAVE RECEIVED THEM FROM USERS
$safe_username = mysql_real_escape_string($X);
//FIND AND GET THE ROW
$getit = mysql_query("SELECT * FROM table_name WHERE username='$safe_username'", $connect);
$row = mysql_fetch_array($getit);
//YOUR NEEDED VALUES
$bio = $row['bio'];
$email = $row['email'];
Note 1:
Dont Use Plain Text for Passwords, Always hash the passwords with a salt
Note 2:
I used MYSQL_QUERY for your code because i don't know PDO or Mysqli, Escaping in MYSQL is good enought but Consider Using PDO or Mysqli , as i don't know them i can't write the code with them for you
Simplistic PDO examples.
Create a connection to the database.
$link = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Use the $link variable when creating (preparing) and executing your SQL scripts.
$stmt = $link->prepare('insert into `history` (`user_id`) values(:userId)');
$stmt->execute(array(':userId' => $userId));
Code below will read data. Note that this code is only expecting one record (with 2 data elements) to be returned, so I'm storing whatever is returned into a single variable (per data element), $webId and $deviceId.
$stmt = $link->prepare('select `web_id`, `device_id` from `history` where `user_id` = :userId');
$stmt->execute(array(':userId' => $userId));
while($row = $stmt->fetch()) {
$webId = $row["web_id"];
$deviceId = $row["device_id"];
}
From the picture I can see you are using phpMyAdmin - a tool used to handle MySQL databases. You first must make a connection to the MySql server and then select a database to work with. This is shown how below:
<?php
$username = "your_name"; //Change to your server's username
$password = "your_password"; //Change to your server's password
$database = "your_database" //Change to your database name
$hostname = "localhost"; // Change to the location of your server (this will prolly be the same for you I believe tho
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db($database, $dbhandle)
or die("Could not select examples");
?>
Then you can write something like this:
<?php
$bio = mysql_query("SELECT bio FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
and
<?php
$email = mysql_query("SELECT email FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
Where *your_database_table_name* is the table in the database you selected which you are trying to query.
When I was answering your question, I was referencing this site: http://webcheatsheet.com/PHP/connect_mysql_database.php. So it might help to check it out as well.
My script is supposed to log the user into my database.
it does this by checking whether or not the username and password matches a row on the staff table.
if it is discovered that the username and password does exist it stores the username and password on the cookie.
The problem that I'm getting is that users are not being logged in.
It has been identified via the echo method that the following variables have the following values upon clicking the button
$row = 0
$username = whatever is in the username field on the form
this seems to indicate that there is something wrong with the query
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'the_shop';
mysql_select_db($dbname);
if(isset($_GET['submit']))
{
$username = $_GET['username'];
$password = md5($_GET['password']);
echo "$username + $password <br />";
// insert user into db
// $sql = "INSERT INTO `logindb`.`users` (`id`, `username`, `password`) VALUES (NULL, '".$username."', '".$password."');";
// echo $sql;
// $result = mysql_query($sql);
// getting user from db
$query = "SELECT Username, Password FROM staff WHERE `Username`='.$username.'";
$result = mysql_query($query)
or die(mysql_error());
$num=mysql_numrows($result);
echo $num;
if($num <= 0) {
echo "login not successful";
echo "$username";
}
else
{
$_SESSION['username'] = '$username';
$_SESSION['password'] = '$password';
//header("Location:Admin_Control_panel.php");
}
}
?>
For starters your $query has unwanted characters (.) in there.
"SELECT Username, Password FROM staff WHERE `Username`='.$username.'"
^ ^
Should be.
"SELECT Username, Password FROM staff WHERE `Username`= '$username'"
Without the dots.
This line:
$query = "SELECT Username, Password FROM staff WHERE `Username`='.$username.'";
Needs to be:
$query = "SELECT Username, Password FROM staff WHERE `Username`='$username'";
There is no need to concatenate the string since you're using double-quotes and PHP is parsing the $ values inside a double quoted string.
Your query should be:
$query = 'SELECT Username, Password FROM staff WHERE Username = ' . $username;
I suggest looking into PDO (PHP Data Objects) as an alternative to the method you are using and parameterising your variables.
http://php.net/manual/en/book.pdo.php
$query = "SELECT Username, Password FROM staff WHERE `Username`='$username'";