Using PHP have a MySQL statement into multiple PHP variables - php

A little backdrop to what I'm trying to accomplish..
I'm making a simple CMS / blog and I'm trying to have the signature auto created from the database's firstname / lastname values by selecting them by the username..
Then after they are selected I am trying to put them into one variable
Example:
$firstname = row['firstname'];
$lastname = row['lastname'];
$signature = $firstname + " " + $lastname;
echo 'Created by: ' . $signature;
The above is what mentally I'm trying to accomplish but I just can't seem to get quite there. This is what I have so far, and I'm not having any luck...
$username = $_SESSION['username'];
$sqlName = "SELECT * FROM users WHERE username = $username";
$connName->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$resultName = $connName->query($sqlName);
foreach ($resultName as $row) {
$firstname = $rowN['firstname'];
$lastname = $rowName['lastname'];
}
This is my most current rendition for those wondering:
$username = $_SESSION['username'];
$connName = new PDO('mysql:host=localhost;dbname=platform', 'tyler', 'H011mann');
$connName->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlName = "SELECT * FROM users WHERE username = $username";
$resultName = $connName->query($sqlName);
$name = 'Created by : ';
foreach ($resultName as $row) {
$name .= $row['firstname'] . ' ' . $row['lastname'];
}
echo '<div>' . $name. '</div>';

There are some issue with your code. At first glance, I was missing the PDO object. On closer inspection, I've noticed you were using the wrong concatenation operator and you didn't seem to use Prepared Statements either.
Prepared Statements will protect you from SQL injection as well as users using characters that might cause issues for your MySQL database. I've written the following code for you that shoul deal with all your issues. Please make sure to take a look at the comments inside:
<?php
session_start();
//Get Username
$username = $_SESSION['username'];
//MySQL Server Data
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//PDO Object
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
// Set PDO options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instance
try{
$pdo = new PDO($dsn, $dbuser, $dbpass, $options);
}
// Catch any errors
catch(PDOException $e){
print $e->getMessage();
exit;
}
try {
//Setup Query
$sql = "SELECT * FROM users WHERE username = :username";
//Prepare Query
$pdo->prepare($sql);
//Bind Values (to prevent SQL injection)
$pdo->bindParam(':username', $username);
//Execute Query
$pdo->execute();
//Fetch Data
$data = $pdo->fetch(PDO::FETCH_ASSOC);
//Combine results
$signature = $data['firstname']. " " .$data['lastname'];
echo $signature;
} catch (PDOException $e) {
print $e->getMessage();
exit;
}
?>

Try this
$resultName = $connName->query($sqlName);
$signature = 'Created by : ';
foreach ($resultName as $row) {
$signature .= $row['firstname'] . ' ' . $row['lastname'];
}
echo $signature;

$username = $_SESSION['username'];
$sqlName = "SELECT * FROM users WHERE username = $username";
$connName->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$resultName = $connName->query($sqlName);
foreach ($resultName as $row) {
$firstname = $row['firstname'];
$lastname = $row['lastname'];
}
$signature=$firstname.' '.$lastname;

Unless your sample code up there was just some form of pseudo code, the concatenation operator in PHP is ".", not "+". Just use that to combine the 2 values returned into a variable:
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$signature = $firstname . ' ' . $lastname;

Related

Why does my PDO $stmt->bind_result() function call hang after executing a SELECT query?

I have a MySQL database with table "Test" that has one column "TestData". There are three records with the following values for TestData: "This is value 1", "Here is another string", and
"Third just for luck".
I wrote the following PHP code to retrieve the records.
<?php
try {
$hostname = "redacted";
$username = "redacted";
$password = "redacted";
$database = "redacted";
$conn = new PDO("mysql: host=$hostname; dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT TestData FROM Test";
$stmt = $conn->prepare($sql);
$stmt->execute();
}
catch(PDOException $e)
{
$finalResult = $finalResult . "," . $e->getMessage();
}
echo "you are here (" . $stmt->rowCount() . ")<br>";
if ($stmt->rowCount() > 0) {
echo "found (" . $stmt->rowCount() . ")<br>";
$stmt->bind_result($td);
echo "bind successful<br>";
while ($stmt->fetch()) {
echo "testdata (" . $td . ")<br>";
}
} else {
echo "nothing found<br>";
}
?>
The result I receive is
you are here (3)
found (3)
The PHP script never gets to the "echo 'bind successful'" statement. The "$stmt->bind_result($td);" statement hangs.
The query appears to work, given that rowCount = 3. I've used essentially the same structure to perform INSERTS that work properly.
What's wrong with what I'm doing? Thanks.
I changed my code to the following and it works.
<?php
$hostname = "redacted";
$username = "redacted";
$password = "redacted";
$database = "redacted";
$conn = new mysqli($hostname, $username, $password, $database);
if ($conn->connect_error) {
fwrite(STDERR, "Connection failed: " . $conn->connect_error . "\n");
exit(1);
}
$sql = "SELECT TestData FROM Test WHERE ?";
$stmt = $conn->stmt_init();
if(!$stmt->prepare($sql)) {
print "Failed to prepare statement\n";
} else {
$stmt->bind_param("s", $condition);
}
$condition = "1 = 1";
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)) {
foreach ($row as $r) {
echo "testdata(" . $r . ")<br>";
}
}
?>
No more mixing PDO and MySQLi for me. Thanks for the help. Sorry for the inconvenience.
If you are just trying to get the items from the database using php pdo you need to store the results.
$results = $stmt->fetch(); //will get one row
$results = $stmt->fetchAll(); //will take all results and store in an array
hope this helps.

Secure php and sql when selecting and inserting data

I have an app that takes data from MySQL database and also inserting data into it (the user is writing the data that is getting inserted) and honestly I am pretty new to php and don't know a lot about securing and sanitizing strings,
I want to make the php files more secure and I don't know what to look for in order of doing it, if someone can send a tutorial it will be great.
here is the select and insert codes
<?php
header('Content-Type: text/html; charset=utf-8');
$db = "*********";
$username = "*********";
$password = "*******";
$host = "************";
$sql = "select * from sample;";
$conn = mysqli_connect($host,$username,$password,$db);
$conn->set_charset('utf8');
$result = mysqli_query($conn,$sql);
$response = array();
while($row = mysqli_fetch_array($result))
{
array_push($response,array($row[0],$row[1],$row[2]));
}
$str = json_encode(array($response),JSON_UNESCAPED_UNICODE);
$str = clean($str);
echo $str;
mysqli_close($conn);
function clean($string) {
$string = str_replace(' ', ' ', $string);
$string = preg_replace('/[^a-zA-Z0-9,×-×–, : . -]/', '', $string);
return preg_replace('/-+/', '-', $string);
}
?>
and the insert:
<?php
$db = "*********";
$username = "*********";
$password = "*******";
$host = "************";
$conn = mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);
$name =$_POST["name"];
$publisher=$_POST["publisher"];
$date=$_POST["date"];
$sql_query = "insert into sample(name,publisher,date)
values('$name','$publisher','$date');";
if(mysqli_query($conn,$sql_query))
{
echo "data inserted";
}
else
{
echo "error";
}
?>
Use prepared statements any time possible:
$sql_query = "insert into sample(name,publisher,date) values(?,?,?);";
$stmt = mysqli_prepare($conn,$sql_query);
mysqli_stmt_bind_param( $stmt , "sss" , $name,$publisher,$date);
mysqli_stmt_execute($stmt);
And try to use the object style only, not the procedural of the mysqli extention.
You are mixing both here:
$conn = mysqli_connect($host,$username,$password,$db);//procedural style
$conn->set_charset('utf8');//oject style
You can use PDO. It's very simple to build safe SELECT and INSERT queries. Although, you must be careful on some commands such as ORDER BY.
<?php
$pdo = new PDO('mysql:host=localhost;dbname=databasename;charset=utf8', 'username', 'password');
$statement = $pdo->prepare("SELECT * FROM users WHERE firstname = :firstname AND lastname = :lastname");
$statement->execute(array(':firstname' => 'Max', ':lastname' => 'Mustermann'));
if( $statement->rowCount() > 0 ) {
$row = $statement->fetch();
echo "Hello " . $row['firstname'];
}
?>
Mysqli can be used too, but please check out mysqli_real_escape_string.

Reducing MSQL Query to a specific session

Using the code below, I was able to display each username and trial 1/0 flag in the table. What I want to do is display the data only for the existing user so I can say something like "Hello USERNAME, you have TRIAL access..." etc...
We're using standard HTACESS as the un/pass to enter the info area.
What needs to change here to only show the existing user's session?
<?PHP
$user_name = "blahblahblah";
$password = "blahblahblah";
$database = "blahblahblah";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM member_auth";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_array($result) ) {
print $db_field['username'] . " : ";
print $db_field['trial'] . " <br> ";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
please don't use mysql_ functions.. look into PDO or MySQLi here: http://www.phptherightway.com/#databases
Update your query to only return specific user results.
Using Form POST:
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
Using URL Parameters:
$username = mysql_real_escape_string($_GET["username"]);
$password = mysql_real_escape_string($_GET["password"]);
So your SQL query will now look like:
$SQL = "SELECT * FROM member_auth WHERE username = '" . $username . "' AND password = '" . $password . "'";

how to make with print_r only display text in array

I created a members table on my database and entered the username row as user and the password row as password. Then I wrote a script that has to display the password and the username in a database. This is it:
<?PHP
$user_name = "root";
$password = "Hunter123";
$database = "adventure_of_dragons";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM members";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
$id = array($db_field['member_id']); "<BR>";
$username = array($db_field['username']); "<BR>";
$password = array($db_field['password']); "<BR>";
$rank = array($db_field['rank']); "<BR>";
print_r($username);
print_r($password);
}
mysql_close($db_handle);
}
else {
print "Database NOT Found " . $db_handle;
}
?>
but when i run the code it displays this:
Array ( [0] => user ) Array ( [0] => password )
how do I make it display the text like this:
-User -Password
Please help.
That's simple. Just don't make arrays of them in the first place, and use regular echo.
Other bugs in the code
print_r is a debug function (just like var_dump), it is not used for printing out data to user.
Also, this statement: "<BR>"; simply means nothing.
You must echo it for it to have any effect at all.
Another thing is that you've overwritten the DB connection variables in your fetching loop. It's better to use constants for this, like shown below.
Here's your code, fixed
<?php
define("DB_USERNAME", "root");
define("DB_PASSWORD", "Hunter123");
define("DB_DATABASE", "adventure_of_dragons");
define("DB_SERVER", "127.0.0.1");
$db_handle = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
$db_found = mysql_select_db(DB_DATABASE, $db_handle);
if ($db_found || true) {
$SQL = "SELECT * FROM members";
$result = mysql_query($SQL) or die(mysql_error());
while ( $row = mysql_fetch_assoc($result) ) {
$id = $row['member_id'];
$username = $row['username'];
$password = $row['password'];
$rank = $row['rank'];
echo 'ID = ' . $id . '<br>';
echo 'RANK = ' . $rank . '<br>';
echo 'USERNAME = ' . $username . '<br>';
echo 'PASSWORD = ' . $password . '<br><br>';
// two <br>'s, so we get an empty line between users
}
mysql_close($db_handle);
} else {
echo "Database NOT Found " . $db_handle;
}

PDO error when Fetching results

I am trying to show results from a simple select statement using PDO
<?php
// Define and perform the SQL SELECT query
include('config.inc');
$user = $_POST['user'];
$password = $_POST['password'];
$sql = "SELECT * FROM usuarios where user = '$user' AND password ='$password'";
$stm = $db->prepare($sql);
$stm->execute();
// here you go:
$users = $stm->fetchAll();
foreach ($users as $row) {
print $row["user"] . "-" . $row["password"] ."<br/>";
}
?>
And the only thing I get is errors like this one:
Undefined index: user in C:\wamp\www\proyect\select.php on line 16
Perhaps is something really simple I might be overlooking in this test, I am working with php 5.3.5.
This is the included file:
<?php
$dsn = 'mysql:host=localhost;dbname=carrito';
$username = 'root';
$password = 'root';
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch (PDOException $e){
$error_message = $e->getMessage();
//include('db_error.php');
echo $error_mesage;
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
exit();
}
?>
If I may guess:
you have PDO::CASE_UPPER set.
http://www.php.net/manual/en/pdo.constants.php
or your column name is just simply upper cased naturally.
But...stop wondering and start investigating. Simply do
var_dump($users);
to see what you have.
Remove:
$users = $stm->fetchAll();
foreach ($users as $row) {
print $row["user"] . "-" . $row["password"] ."<br/>";
}
And try this:
while($row = $stm->fetch(PDO::FETCH_ASSOC)){
print $row["user"] . "-" . $row["password"] ."<br/>";
}

Categories