Fastest way to get MySQL cell data as a string? - php

I want to take the value of a single MySQL cell and use it as a string inside PHP code - I already know the cell exists, where it is, and nothing else is needed. What's the easiest way to do this? All the examples I've found focus on using a loop to output multiple rows into a table, which seems needlessly complicated for my purposes.
Basically what I want to do is this:
require_once 'login.php'; // Connects to MySQL
$sql = "SELECT name FROM users WHERE id='1'"; // id is determined elsewhere
$result = mysqli_query($connect, $sql);
echo "Your name is " . $result;
But I get an error message that it's not a valid string.

You forgot to fetch record from $result using mysqli_fetch_assoc().
So you can fix your code this way:
$result = mysqli_query($connect, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "Your name is " . $row['name'];
}

Related

What is the difference between the two? (query select and display result)

I am trying to understand what the difference is between these two lines of code.
I have two pages ACR.php and webPage1.php. ACR.php is included on any page I need to have a database connection. The goal is to obtain the value from the database and display it on the webpage.
// ACR.php //
<?php
// Est. Connection
$dbc = mysqli_connect($ACR_host, $ACR_user, $ACR_pass, $ACR_tablename)
or die('Error communicating to MySQL server');
// Select value from row in table
$thisPort = $dbc->query("SELECT activePort FROM table1 ")->fetch_row()[0];
// Select value from row in table
$thatPort = "SELECT activePort FROM table1";
// Displays result
$result1 = mysqli_query($dbc, $thisPort);
$result2 = mysqli_query($dbc, $thatPort);
?>
webpage1.php will not display the correct value when echoing $result1 but rather echo 'result not found'.
// webPage1.php //
<?php include 'ACR.php';?>
<!--html-->
<tr>
<th>Port<span id="portDisplay"></span><sup></sup>:</th>
<td id="showPort" style="text-align:left;width:75%;">
<?php
session_start();
if (mysqli_num_rows($result1) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result1)) {
echo " " . $row["activePort"];
// echo $row;
}
} else {
echo "result not found";
}
mysqli_close($dbc);
?>
</td>
</tr>
However, if I echo in $result2, the correct value displays from the database table.
Why is this? What makes this so? Are not both $thisPort and $thatPort calling the same row in the table?
UPDATE: I use $thisPort, in part, when fetching a local and remote address. So i would prefer using the current syntax for $thisPort as it works but changing it to the syntax of $thatPort crashes the page. Why is it the value can be pulled from the Database when using this method, but not when i need to display the port on the page.
I don't want to initiate an extra variable ($thatPort), if I don't have to, to simply echo the value from the database when the original var ($thatPort) should and is already doing this.
$thisPort already contains a row from the database. This is not a valid argument to supply to mysqli_query. If you look at your php error log, you'll probably see (depending on your log settings) that the line $result1 = mysqli_query($dbc, $thisPort); generates an error message; $result1 will actually contain FALSE.
$thatPort contains a SQL query string, which is a valid argument to the mysqli_query function, and creates a valid result set in $result2.

mysqli_fetch_assoc doesnt return first row

sorry I am very new to PHP. This has probably been asked before but I am unable to get this code working, I am currently trying to check whether a user has logged in before but the mysqli_fetch_assoc only seems to pull through the second row, this query should only return one row so i only figured it out it was returning two when i added a duplicate to my DB. I have found similar questions and solutions but havent been able to figure it out.
Thanks in advance.
require_once 'login.php';
$db_server = mysqli_connect($db_hostname,$db_username,$db_password,$db_database);
$query = "SELECT * FROM users WHERE username = 'ben944' AND firstlogin = '0'";
$result = mysqli_query($db_server,$query);
if(!$result) {
echo "not working";
exit;
}
$row = mysqli_fetch_row($result);
while($row = mysqli_fetch_assoc($result))
{
print_r($row);
}
The separate $row = mysqli_fetch_row($result); line already fetches and removes the first row from the result before the while loop starts. That's why it's not printed by the while loop (which you have added for debugging purposes obviously).

Fecthing information from mysql

I really got a problem now. I tried for decades and I can't find why it is not working. I want to get the user that is logged in to see their email on a specific page. I tried a new code now and i get this error: Notice: Undefined variable: row in
The code I use is:
<?
$username = $_SESSION['username'];
$sql = "select * from users where username=" . $username . "";
echo $sql;
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
}
?>
AND
<?php echo $row['email']; ?>
<?php
$username = $_SESSION['username'];
$query = mysql_query("select * from users where username='".$username."'");
while ($row = mysql_fetch_array($query)) {
$email=$row["email"];
}
echo $email;
?>
try this.
don't use mysql_* functions
I think... Problem is in SQL query. I propose your column "username" is something like VARCHAR(50). So you have to add quote.
$sql = "select * from users where username='" . $username . "'";
I see a bug, and a design problem.
You've designed your script so that you're printing whatever was last assigned to $row in the condition of your while loop.
You're getting the error because the query is not returning anything and the loop is not running. Therefore, $row is never assigned. That being said, you probably don't want to use a while-loop if all you're trying to do is display the value of the "email" column in the first record returned. If you did want to, then stop it.
Call mysql_fetch_assoc() on your $result (doesn't return as much data), and check that it doesn't return FALSE (one or more records weren't found).
if((row = mysql_fetch_assoc($result)) === false)
die("Error.");
?>
Email:

php mysqli help, first line in DB not being returned?

Here is my code
<?php require_once 'connect.php';
$sql = "SELECT * FROM `db-pages`";
$result = $mysqli->query($sql) or die($mysqli->error.__LINE__);
while ($row = $result->fetch_assoc()) {
echo($row['pagetitle'].' - To edit this page click here<br>');
}
}
?>
I've added a couple more rows to the Database and it's returning them all, apart from id=1 in the DB. Any idea why?
try it like this:
while ($row = $result->fetch_assoc()) {
echo($row['pagetitle'].' - To edit this page click here<br>');
}
Double check the title and ensure it's got nothing that will affect php out-putting it.
Also escape all of your DB output using htmlentities, it makes for good practise in the event someone gets creative.

PHP If Statements With mySQL Results

The code below is supposed to check if there is a person in the database with a row in the database with the username it gets from the cookie login.And if there is it is supposed to include a page and if there isn't a person in the database with this user_id it is supposed to echo.Here is my code so far please tell me how I would do this.I also already know before someone tells me that mySQL statements like I have it are becoming depreciated.Here is My code:
<?php
include("dbconnect.php");
mysql_select_db("maxgee_close2");
$username = $_COOKIE['maxgee_me_user'];
$result = mysql_query("select user_id from users where username = '$username'");
$row = mysql_fetch_array($result);
mysql_free_result($result);
$check = mysql_query("SELECT * FROM events_main WHERE user_id ='$row['user_id']'") or die(mysql_error());
if(1==1){
if (mysql_num_rows($check)>0)
{
include("example.php");
}
else
{
echo "example";
}
}
?>
In the double-quoted string, your array variable $row['user_id'] is being incorrectly parsed due to the fact that you have quoted the array key without surrounding the whole thing in {}. It is permissible to omit the {} in a double-quoted string if you don't quote the array key, but the {} adds readability.
check = mysql_query("SELECT * FROM events_main WHERE user_id ='{$row['user_id']}'") or die(mysql_error());
//-------------------------------------------------------------^^^^^^^^^^^^^^^^^^
// Also acceptable, but not as tidy, and troublesome with multidimensional
// or variable keys - unquoted array key
check = mysql_query("SELECT * FROM events_main WHERE user_id ='$row[user_id]'") or die(mysql_error());
//-------------------------------------------------------------^^^^^^^^^^^^^^^^^^
As mentioned above, $_COOKIE is never considered a safe value. You must escape its values against SQL injection if you continue to use the old mysql_*() API:
$username = mysql_real_escape_string($_COOKIE['maxgee_me_user']);
2 Things right off the bat, like Waleed said you're open to SQL injection, not very nice thing to have happen to you. I would look into reading tutorials about MySQLi and PDOs, from there try and dive into a better way or running queries.
Also you are choosing to use cookies instead of sessions to store the username? Cookies can be modified client-side to say anything a smart user with firebug would want them to be. Sessions are stored server-side and the client (end-user) is only given an id of the session. They cannot modify the username if you send it as a session. (They could try and change the session id to another random bunch of numbers but thats like pissing into the wind, pardon my french.
Heres some pseduo code that will get you on your way I think
<?php
include("dbconnect.php");
$database = "maxgee_close2"; //Set the database you want to connect to
mysql_select_db($database); //Select database
$username = $_SESSION['maxgee_me_user']; //Grab the username from a server-side stored session, not a cookie!
$query = "SELECT user_id FROM `users` WHERE `username` = '" . mysql_real_escape_string($username) . "' LIMIT 1"; //Note the user of mysql_real_escape_string on the $username, we want to clean the variable of anything that could harm the database.
$result = mysql_query($query);
if ($row = mysql_fetch_array($result)) {
//Query was ran and returned a result, grab the ID
$userId = $row["user_id"];
mysql_free_result($result); //We can free the result now after we have grabbed everything we need
$query_check = "SELECT * FROM `events_main` WHERE `user_id` = '" . mysql_real_escape_string($userId) . "'";
$check = mysql_query($query_check);
if (mysql_num_rows($check)>0) {
include("example.php");
}
else {
echo "example";
}
}
?>
That code may/may not work but the real key change is that fact that you were running
mysql_free_result($result);
before your script had a chance to grab the user id from the database.
All in all, I would really go back and read some more tutorials.

Categories