PHP Select fields from database where username equals X - php

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.

Related

Use PHP variable to search through SQL database

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);

Update database table with PHP

I am trying to update for some products their category in database. I want to find products that have in their name a specific word and after that I want to update the category for this products.
I want to select IDs from sho_posts where sho_posts.post_title contain this part of word '%Audio CD%' and after that to update the sho_term_relationships.term_taxonomy_id with value 2 where sho_term_relationships.object_id=sho_posts.id.
I wrote a little PHP code but it make only selection part. What is wrong?
<?php
$username = "user_name";
$password = "password";
$hostname = "host";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("1812233_shoping",$dbhandle)
or die("Could not select examples");
echo "Connected to MySQL<br>";
$result = mysql_query ("SELECT `id` FROM `sho_posts` WHERE CONVERT(`post_title` USING utf8) LIKE '%Audio CD%' ");
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}."<br>";
}
$sql = "UPDATE 'sho_term_relationships'
SET 'term_taxonomy_id' = '123'
WHERE 'object_id' = $row";
//close the connection
mysql_close($dbhandle);
My new cod for script now is:
$username = "_shoping";
$password = "password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("_shoping",$dbhandle)
or die("Could not select examples");
echo "Connected to MySQL<br>";
$result = mysql_query ("SELECT `id` FROM `sho_posts` WHERE CONVERT(`post_title` USING utf8) LIKE '%Audio CD%' ");
while ($row = mysql_fetch_array($result)) {
$id[] = $row['id'];
/*echo "ID2:".$id."<br>";*/
}
foreach ($id as $value) {
echo "value:".$value."<br>";
}
/*$id = $row['id'];*/
$sql = "UPDATE sho_term_relationships
SET term_taxonomy_id = '123'
WHERE object_id =".$value;
mysql_query($sql);
//close the connection
mysql_close($dbhandle);
now it make an update but only for one row, how to make for all rows? From select query I get 4 result
Try this:
$sql = "UPDATE sho_term_relationships
SET term_taxonomy_id = '123'
WHERE object_id = ".$row{'id'};
And make sure to run the query mysql_query($sql)
Also, I think you might want to add this query inside the while loop
You are using single quotes instead of backticks (which are in this case not necessary). Change your update query to this:
$sql = "UPDATE sho_term_relationships
SET term_taxonomy_id = 123
WHERE object_id = $row";
Also, you are missing some pieces of your code; nothing will be called on that query. It's not being executed at all.
Also you have some other problems here, mainly due to the high risk of sql injection. First of all stop using mysql_ functions, they are deprecated. You should prepare your variables. Here's a demonstration of the key parts of your script in mysqli_ format.
This should also solve most of your issues (there may be a few more if I don't full understand your original question).
You would call your database like this (and check for errors)
$dbhandle = new mysqli($hostname, $username, $password);
if ($dhandle->connect_error) {
die("Connection failed: " . $dbhandle->connect_error);
}
Then you would select your data like this (assuming that term might not be the same every time, and might be coming from a post variable named search).
Edit: For example, if you have an HTML form that is getting this variable like so:
<input type="select" name="search_term" />
you name the variable like this:
$search = $_POST['search_term'];
and then you set it up for your query for the like operator
$search_term = '%'.$search.'%';
$result = $dbhandle->prepare("SELECT `id`
FROM `sho_posts`
WHERE CONVERT(`post_title` USING utf8)
LIKE ? ");
$result->bind_param("s",$search_term);
$result->execute();
$result->bind_result($id);
And then you can get your data through the while loop like so
while ($result->fetch()) {
... stuff you want to do here...
}
$result->close();
Then you would use this in your update query (which would take a similar syntax), and you can just get the information from $id which was created with the bind_result above:
$sql = $dbhandle->("UPDATE sho_term_relationships
SET term_taxonomy_id = 123
WHERE object_id = ?");
$sql->bind_param("s",$id);
$sql->execute();
$sql->close();
It may take a little bit to get used to this, but I find it easier to parse, and also is much more secure

Php script update VIEW from other data base

I need to write a script which will take the values from two columns and use them to update the column in a view that I created in another database. In the first database I have sku and qty as well as in the view.
here is my code:
$server = 'localhost';
$user = 'invodata';
$pass = 'Abcd1234!1';
$dbname = 'tboinvodata';
$con = mysql_connect($server, $user, $pass) or die("Can't connect");
mysql_select_db("tboinvodata") or die(mysql_error());
$result = mysql_query("SELECT item, onhand FROM immaster"); <- this is getting the values from the columns in the first data base
$server = 'localhost';<-setting up my second connection to other database
$user = 'tbo';
$pass = 'Abcd1234!1';
$dbname = 'i187358_mage1';
$con = mysql_connect($server, $user, $pass) or die("Can't connect");
mysql_select_db("i187358_mage1") or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {<-this gets the array from other database
UPDATE qtyview SET qty = $row["onhand"] WHERE sku = item;<- this should update the necessary columns "sku" is used in my view and "item" is used in the first data base I use this so the proper rows in the other columns get updated.
}
?>
really not sure what I am doing wrong I am pretty new to this though.
You can make multiple calls to mysql_connect() and use them like this.
First connect to two your MYSQL USER
$con1 = mysql_connect($server, $user, $pass);
$con2 = mysql_connect($server, $user, $pass, true);
Then establish a connect with different DATABASE
mysql_select_db('firstdatabase', $con1);
mysql_select_db('seconddatabase', $con2);
Then query from firstdatabase like this
mysql_query('select * from views', $con1);
And query from seconddatabase
mysql_query('select * from views', $con2);
This code is not tested by me...but i think it will work good for you.. :)

migrating mysql to mysqli in ajax environment

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))

mysql_query() not taking php variables

I'm passing a variable to a mysql query, $name is a variable that is getting a decrypted string. It is later passed to the SEARCH query. $name has a name in it (which i have seen via an echo).
The SEARCH query just wont take this variable. If i quote the string that is present in the SQL table, i do get an output (count as 1). I cant see where the problem is, because the same code is working in another file (its taking a variable in its query from an HTML entry though), and its embarrassing!
$decrypted_text1 = mcrypt_ecb(MCRYPT_DES, $key_value, $encrypted_text1, MCRYPT_DECRYPT);
$name = $decrypted_text1;
$username = "root";
$password = "speaker1";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_selectdb("login", $dbhandle);
$query = "SELECT * FROM users WHERE Username='$name' ";
$result = mysql_query($query, $dbhandle) or die(mysql_error());
$count5 = mysql_num_rows($result);
Delete the quotation marks around the variableit should look like this:
$query = "SELECT * FROM users WHERE Username=$name ";

Categories