TheInternetIsNeat
TheInternetIsNeat

Reputation: 89

How to print ONLY the data, as a string, from a mysql row

I have tried to simply print/echo the data from this row in my table:

The stuff i want to print

I then use the following code (without all the connect stuff):

//please just ignore the query part
$sql2 = "SELECT Password FROM bruger WHERE Brugernavn='$Login_Navn'"; 
$result2 = mysqli_query($con, $sql2);
$row_result2 = mysqli_fetch_assoc($result2);

print_r($row_result2);

And the output of this ends out being:

output of the code

I would like to know what i have to do to make it appear without all the "Array ([Password]....." stuff, so it just ends out being plain "TestPassword". -Do i have to use another function?

Thanks in advance!

Sidenote: Im creating a login system for a school project. It ain´t advanced in any way, and the security/encryption etc. is as low as it gets. But that´s not really what im interested in with the project. If you have some reading material on how to create a login system properly tho´ it would be appreciated.

Upvotes: 1

Views: 173

Answers (2)

J. A. Streich
J. A. Streich

Reputation: 1712

You would echo the place in the array

echo($row_result2['Password']);

If your query brings back multipule fields you could loop over them:

foreach($row_result2 as $key => $val)
{
  echo($key . ':' . $value);
}

Lastly, instead of storing into a associated array, you could use mysqli's bind to bind the results to single varibles:

$sql2 = 'SELECT Password FROM bruger WHERE Brugernavn=?'; 
$stmnt = mysqli_prepare($con, $sql2);
mysqli_stmnt_bind_param($stmnt,'s',$Lpgin_Navn);
mysqli_stmnt_bind_result($stmnt,$result2);
mysqli_stmnt_execute($stmnt);
mysqli_stmnt_fetch($stmnt);
echo($result2);

Or object oriented:

$sql2 = 'SELECT Password FROM bruger WHERE Brugernavn=?'; 
$stmnt = $con->prepare($sql2);
$stmnt->bind_param('s',$Lpgin_Navn);
$stmnt->bind_result($result2);
$stmnt->execute();
$stmnt->fetch();
echo($result2);

The use of mysqli_prepare protects your database from SQL injection attacks (consier if $Login_Navn = "'; drop table burger; --"). Binding the parameter tells it which string to sanitize when running the query. It also will speed up the time it takes to run the same query multiple times on different passed strings.

Lastly, never store passwords if you can help it. If you must, you should read the best practices for storing passwords. This, currently, includes salting (with random salt) and hashing (using a hash algo that is not currently known to be broken) the password before storing it in the database.

Upvotes: 0

That would be echo $row_result2['Password'];

You need to specify the corresponding index of the array to get the respective element to be printed.

Upvotes: 1

Related Questions