best approach in filling up a profile page? - php

Well I am a newbee so kindly please ignore if there is any mistake in my question,I have this question on my mind.Iam just creating a small website like a profile information.
Okay see when user logs in with his email into the website, we use php scripting and retrieve the data from mysql and put that data in the page using mostly printf or echo
So there is possibilty of 2 ways to do
for example one of the table of my database looks like this
name birthday aboutme gender dreams music movies blabla//
someperson xx xx xx xx xx xx
first method demo.php
<html>
<body>
name: <?some php script to get user name?>
<20 lines of html tags and data>
birthday: <?some php script to get user name?>
<20 lines of html tags and data>
about user <?some php script to get user about?>
<some more html data>
<?some more php scripting?>
In the first method we are always connecting to the database and getting the data and then after 20 lines of html code and then again we are connecting to the same table and database and getting the next columns value and disconnecting it and then again we are connecting to the server and more. In this process we are connecting and disconnecting from server
So in the first method we are always connecting and disconnecting from server, I was just thinking it may cause a serious overhead on the server as we are connecting and disconnecting for every 10 lines of code.is my thinking true or is there anything wrong?
second method demo.php
<?php
retrieve all the data you need at a time here and then use
echo "<html>"
echo "<body>"
echo "name: <?just php variable value that was retrieved?>
echo "<20 lines of html tags and data>"
echo "birthday: <?just php variable value that was retrieved?>
?>
In the second method we are using the php script run by server just get the data at the start and then just echo them with the html tags and data that was retrieved, but i was thinking it is so unneccasary because we are making the server to execute the html tags where a normal browser clearly would do
I am finding both ways causing a serious overhead issue on the server.could anyone explain what is the best way to do it? is there any other way the professionals choose , I am not sure how they make through it.
Well is there a way to retrieve the data at once from the database and then just echo it back between the html tags?
simply like
<?get all the data from database here>?
<div> echo 'some php variable'
<span> echo 'some php variable'
Is there a way like this? Kindly let me know the best approach to do it.Thanks
any help is greatly appreciated

You are correct in thinking that you do not have to declare all of your html using php echo. The php generates the HTML as it moves down your code. So you can declare HTML inbetween php calls.
For example:
<html>
<body>
<?php
$results = mysql_query(SELECT name,gender FROM table WHERE id='34';
// Additional code to assign $results array to variables
?>
<div><?=$name;?></div>
<div><?=$age;?></div>
</body>
</html>
The most important thing to note is that you can call php multiple times through out your document and it will continue to work off past php calls. All variables and functions are stored throughout the page.
Hope this helps.

If all your data is in the same table then you only need a single query. And you should switch in and out of php instead of composing the html inside php. It might look something like this:
<?php
$db = new PDO($dsn, $user, $password);
$stmt = $db->prepare('SELECT * FROM user_profile WHERE user_id = ?');
$stmt->execute(array($user_id));
$profile = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->close();
?>
<html>
<head>
<title> <?php echo $profile['username']; ?> Profile</title>
</head>
<body>
<div>
<div>
<div>
<?php foreach($profile as $attribute => $value): ?>
<div>
<span class="label"><?php echo $attribute ?></span>
<span class="profile_value"><?php echo $value; ?> </span>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
</body>
</html>

Yes, I would get all of the data up front if that is possible (if it is not dependent on anything else in the execution of your script).
If I follow what you are saying correctly, you are pretty close in your pseudocode at the end there. You seem to want something like this:
<?
// here is where you get all the data from MySQL using PHP
?>
<!-- HTML now -->
<div>
<?
//PHP starts again
echo $something;
//PHP ends
?>
<!-- HTML again -->
</div>
You can jump in and out of PHP as many times as you'd like, whenever is most appropriate.

Related

How do you put html edit text fields in php

I want to put two html edittext fields with a label next it saying please input a reg number and a button in the end, whereby the user can input a new registration number. I want to do it within the php script, but I don't know how to incorporate it
Thing is, I am not quite sure how to do this and how to validate the button on click. Like how do I get the values on button click?
This is what I have so far:
<?php
include "init.php"
if(!empty($_POST['driverNo'])){
$driverNoText = $_POST['driverNo'];
$stmt = "SELECT registrationNo FROM cars WHERE driverNo = ?";
$result = $conn->prepare( $stmt );
$result->bind_param( 's', $driverNoText );
$result->execute();
$result->store_result();
$result->bind_result( $registrationNo );
while( $result->fetch() )
{
echo $registrationNo;
}
$result->free_result();
?>
Is this even possible or would I have to create a html file and then include this php script?
Sorry, I am quite new to all this web dev stuff
Usually the flow for this kind of single purpose PHP file is that you can include html codes at the end of the PHP script. Treat PHP just like a html file, with a little bit advance thing that it's capable to do more than just HTML.
Which means, the file can be in this kind of format:
<?php
//------------------------
// Start of your php inits
// .....................
//------------------------
// Section where you have your code checking
//
if (!empty($_POST...
//do something useful, sanitize inputs, insert into db
//echo out something like "thanks for submission here"
} else {
//you can close the php tag here and put your html codes here
?>
<!doctype html>
.....
<form action="<?php echo $_SERVER['PHP_SELF'] ?>>
<input...>
<input type="submit" />
</form>
<?php
//and don't forget the closing bracket
}
If you are new and trying out PHP, go ahead and have this as the sample. This is generally not recommended anyway because it's a maintenance nightmare if your code grows. Generally you will need to look for frameworks that can help you with these tedious tasks.

How do I echo PHP code from database and make the syntax highlighted?

Is it good for users to be allowed to insert PHP code as an input and then store to database? If yes how can we echo out the inputs and display them in a page safely without losing syntax highlighting?
I tried to echo it out this way but it tends to execute on the webpage
echo''.$row['input'].'';
Any answer will be appreciated. Thanks
You need to store your code samples in the database using htmlentities etc. So
<?php
//comment
?>
It must look like this in your MySQL table:
<?php // comment ?>
Create a PHP page that can SELECT the entries from the database table. It must include:
<head>
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
</head>
Echo your code sample from your query something like:
echo '<pre class="prettyprint">'.$row['code_sample'].'</pre>';

Make variables available inside of a function.(PHP)

Im building an application to track certain information about the clients we deal with like name/date/hrs worked/phone number etc. This information is stored in a db. Because we have different departments like SEO/WEB/Sales etc, and different people within these teams, the app provides different ways to filter the information depending on the filter button pressed.
When someone presses a "filter button", in this example, lets say they pressed the "view by department" button, it takes them to actual hardcoded pages.
As an example:
viewSeoAccs.php
viewWebAccs.php
ViewSalesAccs.php
And in these pages i have queries which pull the information based on the filter pressed but the html is the same. Now here comes the problem.
I have many different pages(based on filters) and every time there is an edit to be made to the html, i have to go into EVERY PHP page to implement the changes.
What i want to do is create a function that spits out the html for me. I have gotten about half way and i know the problem, just cant seem to find a solution.
Here is some code.
In my functions.php file, i have a function called "htmlBlockTEST" that has this code.
EXAMPLE: (code chopped for easy reading)
<?php
function htmlBlockTEST(){
echo '' ?>
<h2 class="accName fl"><?php echo $row['company_name']; ?></h2>
<div class="<?php echo $row['acc_risk']; ?>"> Risk Level. </div>
//ALOT MORE CODE goes here lol.
<?php
}
?>
This is in the header and bought in via "include_once('functions.php').
Under this, i have specific variables that pull in the queried data. (example below)
$pullAllAccounts = "SELECT * FROM tlm_accounts ORDER BY company_name ASC;";
$pullAllAccountsDoIt = mysqli_query($c2d, $pullAllAccounts) or die ("could not pull WEB team data" . mysqli_error($c2d));
?>
now i loop through the db and display the information like so:
<?php
while($row = mysqli_fetch_array($pullAllAccountsDoIt)){
$compName = $row['company_name'];
?>
<?php htmlBlockTEST(); ?>
<?php
}
?>
In this code directly above, where the function call "htmlBlockTEST" is, is where the problem is. Since The variables which hold the queries are outside the function, I'm assuming that they aren't being passed into the function. I dont want to put them inside the function because the HTML is the same throughout all the pages, but not ALL data.
I need the variables that hold for example $row['company_name'] to be also available inside the function so that it doesn't throw "undefined variable" errors.
How can i make this happen? What is the best way to get these variables in the while loop(or otherwise) to be available inside the function???
PS, ive google and found things like $GLOBALS['x'] etc but from what ive read, its not the best way or easiers and overall im confused on how to even use it.
Any help is greatly appreciated.
Thanks in advanced.
Option 1:
while($row = mysqli_fetch_array($pullAllAccountsDoIt)){
htmlBlockTEST($row);
}
Option 2:
global $row;
while($row = mysqli_fetch_array($pullAllAccountsDoIt)){
$compName = $row['company_name'];
htmlBlockTEST();
}
//and in your htmlBlockTEST() function just right this:
function htmlBlockTEST(){
global $row; ?>
<h2 class="accName fl"><?php echo $row['company_name']; ?></h2>
<div class="<?php echo $row['acc_risk']; ?>"> Risk Level. </div>
<?php
//ALOT MORE CODE goes here lol.
}
?>
You have some more options of course.

is it possible to dynamically assign ID to an element in webpage using JS/ PHP?

can i set the id of an element programatically, as in a dynamic setting of id of an element, during runtime of the webpage?
Consider this scenario -
<body id="body1">
Now, i want to set the id of this element "body" dynamically, using the value of a variable in the php code. Is this possible? something like -
<body id=" <?php echo $bodyID; ?> ">
I use php and jquery in the page; please let me know whether such dynamic id assignment is possible to the elements in the html.
thanks.
PHP is the background language, it's what produces your HTML output. So basically, what ever you output from PHP eventually becomes your HTML, meaning yes you can use PHP variables as your elemnt-ID or anything else for that matter.
<?PHP
$var = "body1";
?>
<body id="<?PHP echo $var; ?>"> Hello my ID is <?PHP echo $var; ?></body>
OR You can output all of the HTML using a single echo statement.
<?PHP
$var = "body1";
echo "<body id='$var'>Hello my ID is $var</body>";
?>
In conclusion, whatever is left after PHP is finished executing is your HTML code that the end users browser interprets... Hope this helps...
$(function() {
var variable = 'insert_id';
$('body').attr('id', variable);
});
gives (with jquery)
<body id="insert_id">
Why not? As long as you keep your randomizer ( Math.rand ) big enough there should be little chance for conflicts.
I usually do this, and then at the same time call a JS method and passing the same ID. That would require you storing the ID aside so you can pass it later.
Edit: If you are only setting this on the body then you would not need to access it later.

type php code into textarea, store in database, then execute

Anybody have any idea how I might go about doing something like this.
I've got a textarea setup to allow users to edit page content. the content is then stored in a database and is retrieved on the frontend by php within an html template. something like:
<html>
yada yada...
<?php
echo get_page_contents_by_id($_GET['id']);
?>
yada yada...
</html>
its all run in a .php file, in case anyone wanted to call that out.
What I'm wondering is, because I'm getting the content from the database via php, is there any way that I can retrieve php code within that content and still run it without doing any sort of file writing.
You can use the PHP eval() method to execute the PHP code returned from the database - just as if it was actually written in your PHP file directly.
e.g.
<?php
eval("echo('hello world');");
?>
Prints:
hello world
You can use eval for this purpose.
http://php.net/manual/en/function.eval.php
eval() is as James Goodwin and Gazler say in fact the only way to execute PHP code from string data.
In addition to the security consequences - it will become possible to compromise your whole web site by gaining access to your mySQL data - this approach will make code very hard to debug, as you will have to follow all error messages through the eval()d code.
I attempted to do this same thing, but with the addition of tags and normal HTML tags. This will not work. If you need to store HTML along with your PHP, consider a more XHR solution that relies less on PHP code for every page.
Consider another alternative. Really.
Regardless of any security checks you do, function parsing, etc., this is still an EXTREMELY bad idea.
A slightly less bad idea, why not look into a templating solution like http://www.smarty.net or http://www.google.com/search?q=php+template+engine
Below is the code to execute the code in textarea.
<?php
if($_POST){
print_r($_POST);
extract($_POST);
$file = rand(1000,10000); // creating file with random number
file_put_contents($file.'.php', '<?php '.$code.' ?>');
ob_start();
include $file.'.php';
echo ob_get_clean();
unlink($file.'.php'); // deleting the created file after execution.
die('test');
}
?>
<textarea id="testcode" ></textarea>
<input type="submit" onClick="return changePermissions1()" />
<script>
function changePermissions1(){
var code = {};
code['code'] = $("#testcode").val();
var pass_url = "executefile.php"; // there you can pass the code
$.ajax({
type : "POST",
beforeSend : loadingStarts,
url : pass_url,
data : code,
success : function(responseText){`enter code here`
loadingEnds();
alert(responseText);
}
});
}
</script>

Categories