I am in a little bit in doubt, if I am on the correct path here. I have a mysql database, where I have login details of users. I am making a profile page, where I would like the informations on a user is shown to the user. I am now trying to return the firstname there is a column in the database. Am I on the correct path with this code?
<td>
Firstname
<?php
$stmt = $mysqli->prepare("SELECT firstname FROM login");
$stmt->execute();
$fname = null;
$stmt->bind_result( $fname);
while($stmt->fetch()) {
$firstname = // Code here
echo $firstname;
}
$stmt->close();
$mysqli->close();
?>
</td>
Update:
I tried to make the code a little bit smaller. This code actually retrives users, but it is all the users in the database, and not only the user I am logged into with. Should the SELECT query be asigned with the primarykey, if I only need the firstname on the current user I am logged in as?
<td>
Firstname
<?php
$sql ="SELECT firstname FROM login;";
$res = $mysqli->query($sql);
//print($res);
if($res){
while($row = $res->fetch_assoc()){
echo $row['firstname'];
}
}
?>
</td>
You are on the correct path but you need to assign your array to a variable so you can print adding your column name in the scope and remove the bind of $fname
//$stmt->bind_result($fname);
while($column = $stmt->fetch()) {
$firstname = $column['firstname'];
echo $firstname;
}
Or you can just use the variable you bind before
$stmt->bind_result($fname);
while($stmt->fetch()) {
echo $fname;
}
You could optimize your query and limit tresult to only one user by adding a WHERE condition to your query, you can use user ID for example
SELECT firstname FROM login WHERE userid = 1
If you're playing around with PHP and trying to learn how things work, you're on a great path. If you're planning on deploying this code to the internet, you have a few issues:
Your markup seems off. Why are you putting all of the first names in a single <td>?
You shouldn't have a SQL query happening inside of a markup. What if you want to show results from a cache or a text file some day? Ideally you wouldn't even mix PHP and HTML. Some folks use PHP's built-in templating abilities, but it's generally preferred to use a template language like jade or twig.
Your code alignment isn't consistent.
But if you're just seeing what PHP can do, good job. Keep trying stuff out. It's the best way to learn for most people. Others like reading a book, then trying stuff.
Related
I'm having trouble with my php code. I have a table in my DB and every entry has a name, type, location etc. The basic idea is that after entering the name from the previous page (that's why there's a POST variable at the start of the code), you get transfered to this page and it prints the corresponding type. The problem is that even though I'm sure the code is correct and I've tried a few different solutions (I've been searching for a while in the forum), I can't print the type variable.
<?php
$k = $_POST['sub1'];
$con = mysqli_connect("localhost","root","","qr code");
$query = mysqli_query($con, "SELECT type FROM array1 WHERE name ='".$k."'");
while($row = mysqli_fetch_assoc($query)) {
echo $row['type']; }
?>
Any ideas? It's probably a very simple solution, but I'm totally stuck now so I'm sorry if it's too basic :P
still getting my feet wet with php and mysqli, have so much to learn, but at this point this question is one of my most important priorities.
I did some research about this issue but am currently overwhelmed by pretty sophisticated stuff for my level, to be honest. I'd like to find the simplest most efficient way to "automatically" generate a great number of pages each with varying data in it.
the example of page 1's code below is extremely simplified, because the actual page actually has a lot more stuff, but the simplified example serves, I hope, to make my point.
<?php
$servername = "servername";
$username = "username";
$password = "password";
$db= "db";
$conn = mysqli_connect("servername","username","password","db");
$query = "SELECT word FROM demo WHERE group=1";
$result = $conn->query($query);
$row = mysqli_fetch_assoc($result);
$word = $row['word'];
echo $word;
?>
in my table I have / would have something like 500 entries (records?) in the 'group' column, numbered 1, 2, 3 etc all the way to 500.
for my specific purpose, I absolutely need to create as many online pages as there are groups -- in this example, 500 pages.
page 2's echo would have to refer to group 2, page 3's echo would have to refer to group 3, and so on.
obviously, there's a way to do this without copying and pasting the code 500 times and manually changing the group in each! haha. but what's the simplest way?
thank you in advance for any understanding and help, and either way, have an awesome day.
If I'm understanding you correctly, I believe you're waiting to create pages from the database Dynamically. You can use a get variable in the request http://yoursite.com/page.php?group=1.
Then in your code update your query to do:
$query = "SELECT word FROM demo WHERE group=".$_GET['group'];
That query is insecure, as any user could inject raw mysql into the $_GET['group'] variable.
$group = mysqli_real_escape_string($conn, $_GET['group']);
$query = "SELECT word FROM demo WHERE `group`='$group'";
This is much safer.
So PHP will look for a file called index.php by default in any directory that it accesses. You can place such a file in the root of public_html or www or where ever your site accesses. Now in this file you can do something like:
<?php
if($_GET['group']){ //Make sure you have the var
$query = "SELECT word FROM demo WHERE `group`=?"; //The query with param
if ($stmt = mysqli_prepare($conn, query){ // try it out
mysqli_stmt_bind_param($stmt, "i", $_GET['group']); // bind the data
$stmt->execute(); //run it
$result = $stmt->get_result(); // get results
//use result to echo and stuff
}
} else {
//Do something incase there is not a group specified.
echo "Nothing here";
}
?>
Now when you go to your site you will get something like 'localhost/index.php' and see Nothing here but if you type localhost/index.php?group='55' you will have access to the page 55 data in result.
I have created a website which gets data from two 'different' MySql database tables. The tables have identical layouts (so the numbers in each table differs but 100% similar in ID's and column names). Now I am a complete self-made programming noob so bear with me in the following.
On the websites front page I display some data from both of the two tables. The way I do this is by creating a variable ($tableName) that holds the name of the table I need. This variable is then used for generating the necessary data in another file (data.php) and then displaying that data on the front page by the file design.php. This process is replicated for all tables in the MySql database. (below is a very simplified format).
Frontpage.php:
<?php
include('../connection.php');
?>
<?php
$tableName = table1;
include('../Data.php');
include('../Design.php');
?>
<?php
$tableName = table2;
include('../Data.php');
include('../Design.php');
?>
.....(etc.)
Data.php:
$query = "SELECT * FROM {$tableName} WHERE ID = 1";
$result = mysqli_query($conn, $query) or die('error');
while($data = mysqli_fetch_array($result)) {
For ($n = 0; $n < 1; $n++){
$dataVariable = $data["columnname"];
}
}
Design.php
<?php echo $dataVariable; ?>
So what happens is that the user goes to the $dataVariable link and is then sent to Ultimate.php which also includes the Data.php file in order to display a hell-uv-alot of data. I therefore have to again declare the $tableName variable in the Ultimate.php file and then duplicate the Ultimate.php file for every single table there is in the MySql database and change href-link in the Design.php file. (very annoying).
My question is: how can I pass on my $tableName variable from the href on the front page to Ultimate.php? I have searched on here and found a way which includes $tableName to the URL opened on Ultimate.php whereafter I use $_GET inside Ultimate.php to collect it. For some reason I couldn't make that work - and i don't know if this is at all a solid way to solve things in my case.
More importantly: I have never worked with programming before so if anyone can advise me whether I am setting this up most efficiently or not that would also be great! I very much welcome links to guides/tutorials which you think might benefit me at this point!
Thanks a lot in advance!
<?php echo $dataVariable; ?>
Then at the top of Ultimate.php:
<?php
$var = $_GET['var'];
?>
This takes the variable off the browser
http://www.example.com/Ultimate.php?var=yourvariable
You can pass variables from a hyperlink to another page using GET.
hyperlink text
$_GET['key']
http://php.net/manual/en/reserved.variables.get.php#refsect1-reserved.variables.get-examples
I have written the following code to generate information from an SQL database:
<?php
$search1 = "SELECT Name FROM users";
if($mysqli->query($search1) == TRUE)
{
echo "You have successfully searched the request";
}
$result = $mysqli->query("SELECT Name FROM users");
echo '<table border=1px>';
echo'<th>Name</th>';
echo $row;
while($row=$result->fetch_array(MYSQLI_ASSOC))
{
echo'<tr>'; // printing table row
echo '<td>'.$row['Name'].'</td>';
echo'</tr>';
}
echo '</table>';
?>
This generates a list of names in the table. There are other columns in the table such as Country, Email, Hobby and Date Signed up. All of which are VARCHAR except the last which is of type DATE. I am trying to figure out code so that when I click on one of the generated names, the rest of the information (Country, Email etc,) is shown.
Just doing something like:
echo '<td><a href=\"userinfo.php?username='.$row['Name'].'\">'.$row['Name'].'</td>';
And then in userinfo.php, read the $_GET['username'] parameter to make a query similar to the one you have above, something like this:
$search1 = "SELECT * FROM users where Name=?";
And then setting the parameter $_GET['username'] to the prepared statement (if you want to avoid MySQL injections).
You can use the following SQL to get only the information that will be used in your listing page, in your case that would be identifier and name columns (you have identifier column, right? if not, check again your database structure - there's something wrong).
SELECT ID, Name FROM `users`
And then you can create extra page in your application, e.g. show.php where you will pass the identifier of each record as $_GET parameter, e.g. show.php?id=5
And there you should create another query:
SELECT * FROM `users` WHERE `ID` = $_GET['id']; /* that's not secure, read below */
Once you have that data, you can list it and you're done.
If you want to create one-page application, you can hide available info with CSS and display it when user clicks on username. Read about jQuery. You can even use AJAX. It's your choice.
If you want to make everything better, you can try use PDO.
Also, be aware of these vulnerabilities:
SQL Injections
Cross-site scripting
I am writing a simple user/login system in Php with postgresql.
I have a function that confirms whether username/passwords exists, which gets activated when a user presses the Login button.
public function confirmUserPass($username, $password){
$username=pg_escape_string($username);
/* Verify that user is in database */
$q = "SELECT password FROM users WHERE email = '$username'";
$result = pg_query($this->link,$q);
/* Do more operations */
}
I want to print the query stored in $results such that I can see it on the browser. When I do it in phppgAdmin using SQL it shows me the output but I cannot see it on the browser. I tried echo and printf but I could not see anything on the browser. I also tried to see view source from the browser but it shows nothing.
Can somebody help me with that?
Regards
From your code: $result = pg_query($this->link,$q);
As you've found already, trying to display the contents of $result from the line above will not give you anything useful. This is because it doesn't contain the data returned by the query; it simply contains a "resource handle".
In order to get the actual data, you have to call a second function after pg_query(). The function you need is pg_fetch_array().
pg_fetch_array() takes the resource handle that you're given in $result, and asks it for its the next set of data.
A SQL query can return multiple results, and so it is typical to put pg_fetch_array() into a loop and keep calling it until it returns false instead of a data array. However, in a case like yours where you are certain that it will return only one result, it is okay to simply call it once immediately after pg_query() without using a loop.
Your code could look like this:
$result = pg_query($this->link,$q);
$data = pg_fetch_array($result, NULL, PGSQL_ASSOC);
Once you have $data, then you've got the actual data from the DB.
In order to view the individual fields in $data, you need to look at its array elements. It should have an array element named for each field in the query. In your case, your query only contains one field, so it would be called $data['password']. If you have more fields in the query, you can access them in a similar way.
So your next line of code might be something like this:
echo "Password from DB was: ".$data['password'];
If you want to see the raw data, you can display it to the browser using the print_r() or var_dump() functions. These functions are really useful for testing and debugging. (hint: Wrap these calls in <pre> tags in order for them to show up nicely in the browser)
Hope that helps.
[EDIT: an after-thought]
By the way, slightly off-topic, but I would like to point out that your code indicates that your system may not be completely secure (even though you are correctly escaping the query arguments).
A truly secure system would never fetch the password from the database. Once a password has been stored, it should only be used in the WHERE clause when logging in, not fetched in the query.
A typical query would look like this:
SELECT count(*) n FROM users WHERE email = '$username' AND password = '$hashedpass'
In this case, the password would be stored in the DB as a hashed value rather than plain text, and the WHERE clause would compare that against a hashed version of the password that has been entered by the user.
The idea is that this allows us to avoid having passwords accessible as plain text anywhere in the system, which reduces the risk of hacking, even if someone does manage to get access to the database.
It's not foolproof of course, and it's certainly not the whole story when it comes to this kind of security, but it would definitely be better than the way you seem to have it now.
You must connect to database , execute query, and then fetch results.
try this example from php.net
<?php
public function confirmUserPass($username, $password){
$username=pg_escape_string($username);
// Connecting, selecting database
$dbconn = pg_connect("host=localhost dbname=publishing user=www password=foo")
or die('Could not connect: ' . pg_last_error());
// Performing SQL query
$query = "SELECT password FROM users WHERE email = '$username'";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
// Printing results in HTML
echo "<table>\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
pg_free_result($result);
// Closing connection
pg_close($dbconn);
?>
}
?>
http://php.net/manual/en/book.pgsql.php