0

so I have a database table with some user information, like ID, username, etc. and I have been trying to turn a value, for example, Bob's ID into a variable $id from the table. This is what I have right now:

$db = mysqli_connect(THIS WORKS FINE AND CONTAINS SECRET INFO :));
$sql = "SELECT ID FROM users WHERE username='$prompt'";
$result = mysqli_query($db, $sql);

and I need to turn it into a variable, because I am combining everything into a sentence so it could be $username has the id of $id. Thanks

4
  • var_dump $result to see what it is, then figure out how to extract the data you need from it. Commented Jan 31, 2017 at 5:45
  • this might also help stackoverflow.com/questions/15617824/result-mysql-query Commented Jan 31, 2017 at 5:45
  • @Andrew This is what I got: object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(1) ["lengths"]=> NULL ["num_rows"]=> int(1) ["type"]=> int(0) } Commented Jan 31, 2017 at 5:47
  • WARNING: When using mysqli you should be using parameterized queries and bind_param to add user data to your query. DO NOT use string interpolation or concatenation to accomplish this because you have created a severe SQL injection bug. NEVER put $_POST or $_GET data directly into a query, it can be very harmful if someone seeks to exploit your mistake. Commented Jan 31, 2017 at 6:15

1 Answer 1

1

Try like this.use sprintf().The sprintf() function writes a formatted string to a variable.

$db = mysqli_connect(THIS WORKS FINE AND CONTAINS SECRET INFO :));
$sql = "SELECT ID,username FROM users WHERE username='$prompt'";
$result = mysqli_query($db, $sql);

$row = mysqli_fetch_assoc($result);

$sentence = sprintf("%s has the id of %u.",$row['username'],$row['ID']);

echo $sentence;

For more see sprintf

Sign up to request clarification or add additional context in comments.

4 Comments

Just curious, but will it work if I just echo, for example, $row['username']?
["num_rows"]=> int(1) means there is only one row.so $row['username'] will print username fetched from database.
If you're going to echo it anyway, just use printf.
@ tadman yes i aggred with you.But op wants to turn it into a variable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.