Make variables available inside of a function.(PHP) - 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.

Related

Using a PHP variable as a MySQL query table name

self taught at PHP so please spare me if i made any obvious errors,
im trying to dynamically create an accordion and have the corresponding content beneath each accordion header be created from its corresponding table,(if the header is tacos, the information below would come from the tacos_info table) some of the solutions i came up with im not sure about, cheifly passing a variable value as the table name in the mysqli query.
<?php
//initialize list
$res = mysqli_query("SELECT * FROM tables ORDER BY votes DESC");
//build the accordion header and div content in descending order
while($row= mysqli_fetch_assoc($res)){
//create value for SQL table name to build content
$dbname='$row['name']';
//create the accordion headers
$accordioncontent= '<h3>'.$row['name'].'</h3>';
//build the query that will be used to create the accordion content dynamically
$res2 = mysql_query("SELECT * FROM '$dbname' ORDER BY votes DESC");
//while loop to build the div content dynamically
while($row2= mysqli_fetch_assoc($res2)){
//dynamically create the list items i.e the accordion content
$ranks= '<li id="li $row2['id']">
<div class="tut-img">
<img src="<?php echo $row2['img']?>" width="50" height="70" alt="<?php $row['title']?>" />
</div>
<div class="title"><?php $row2['title']?>
</div>
</li>';
}//close content while loop
//create the submit button that submits according to each accordion divs content
$submitbutton='';
//limit submissions to once per IP, per table
$voted=false;
$vcheck= mysqli_query("SELECT 1 FROM sort_votes
WHERE ip='".$_SERVER['REMOTE_ADDR']."'
AND date_submit=CURDATE()
AND Tablename='$dbname' "
);
if(mysqli_num_rows($vcheck)==1)
$voted=true;
//conditional to assign either a submit or edit
if(!$votedIFC){$submitbutton='Enter opinion<span></span>'}
else{$submitbutton='Enter opinion<span></span>'}
//concatonate the div header with the div content
$accordioncontent .= '<div><ul class="sort" id="rank_ul">'$ranks'</ul><div class="button-holder">'$submitbutton'</div></div>';
}//close accordion while loop
//send all this data to the AJAX GET request
echo $accordioncontent;
?>
am i passing these values to the query correctly? is this allowed? if not what are better alternatives? any and all tips, input and knowledge is much appreciated.
First of all, I can see that you are using simple and double quotes sometimes in a strange way. Which IDE are you using for your development? My first recommendation, would be for you to use a proper editor that will automatically check your code syntax.
For example this seems strange (difficult to ready and will surely at one point generate an error):
'<li id="li $row2['id']"> ..... ';
In my opinion, a correct syntax here would be:
"<li id='li ".$row2['id']."'> .... ";
More details here: http://www.trans4mind.com/personal_development/phpTutorial/quotes.htm
Now to answers to your question, you seems to be more focused on the way you are passing the values to the SQL query. If you are looking for best practices, then I'd recommend you to use php PDO. It's a layer between PHP and your database that will among other things, make sure that the you correctly passed values to SQL (reduce risk of SQL injection, problem of quotes, etc ...).
More details about PDO here: http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
My last advises:
Please make efforts in the indentation of your code, it will be easier to read and understand for you and others and it will then avoid obvious errors.
Use correct variable name. For example you are here using $dbname to speak about database tables ...
Good luck.

How to create a dynamic link?

I'm trying to create a link that takes the user to two different pages depending is the user logged or not. Problem is I'm still new to programming and this is quite big bite for beginner like me but its something I have to do. I created something like this so far but either way I suck at searching or there just isnt specific information for what I need
<?php if($userLogged){
echo '<a href="index.php" class="stylelink">';
}
else
{
echo '<a href="index1.php" class="stylelink">';
}
echo "Etusivu</a>";
?>
I'm also using Dreamweaver's login function that creates the MM_Username session and such, and Im not sure how to make the condition. userLogged is still an empty variable. Id appreciate any advice.
Thanks
-John
well, instead of using echo statements in the php tag you can write html and use php for outputting the value of the page like this
Etusivu
The $_SESSION['MM_Username'] works if you have included session_start(); at the beginning of the page and you can use the condition as above instead of $userLogged.

best approach in filling up a profile page?

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.

Php inside a javascript function?

I have a feature on my users inbox that allows users to check/uncheck messages in their inbox that they want to make favourite.
I'm currently testing what happens when a user checks the box (clicks on the image and causes it to go from greyed out to colour meaning the box is checked).
Anyway as you can see from the code below when the box ischecked this url is suppose to be loaded: http://mysite.com/messages/favourite_checked
The message_id of the row the user has checked the box on is suppose to be added onto the end of the url this then loads my controller "messages" and method "favourite_checked" which then passes a variable that grabs the message_id from the url, stores it in a variable then sends it the my model and it is used in a mysql query.
Basically I update the favourites column of my messages table and set it to = 1 where the message_id from url matches the one in the messages table in my database. So yea, where the match is found the "favourite" column in that row is updated to 1. 1 = favourite 0 = not favourite.
Any I just thought I would make it clear what was happening..
My problem is nothing happens when I check the box, nothing is updated so I feel I must be doing something wrong where I try to add the id to the url in the javascript function.
I've tried $(post) also.. nothing happens then also.
Maybe someone can spot it because I really don't know what the problem is.
<script type="text/javascript">
// favourite check box
$('input.favourite:checkbox').simpleImageCheck({
image: '<?php echo base_url()?>images/messages/check.png',
imageChecked: '<?php echo base_url()?>images/messages/unchecked.png',
afterCheck: function(isChecked) {
if (isChecked) {
//query to db from php to update favourite number to 1
$.get('http://mysite.com/messages/favourite_checked'+'<?php foreach ($query as $row): ?><?php $row['id']; ?><?php endforeach; ?>');
}
// else (!isChecked)
// {
// //query to db from php to update favourite number to 0
// $.get('http://mysite.com/messages/favourite_unchecked');
// }
}
});
</script>
I think your basic problem is some confusion about when the PHP is running vs the javascript.
The PHP you put on the page is server side, it will load first, then the javascript will run client-side.
This part here:
$.get('http://mysite.com/messages/favourite_checked'+'<?php foreach ($query as $row): ?><?php $row['id']; ?><?php endforeach; ?>');
Seems like you are wanting this to be dynamic based on what you checked, but I don't see how that url is going to show specifically what you are looking for.
About the PHP:
I think you want to replace this:
<?php $row['id']; ?> // does nothing
with this:
<?php echo $row['id']; ?> // echo's the id
Although I´m not sure that that will work as the loop you have there will generate a strange url, just adding all id's...
About the javascript:
I´m not familiar with the simpleImageCheck() function you are calling, but does it have an onClick or onChange event handler? Otherwise I don´t see your code being run at all.

PHP Query from a FORM

So I have a form that I post to a page and in the form I'm posting certain variables that I build one of my queries with and then call them on my page. How can I post data and also build a query and display the answer on one call?
Maybe I'm not wording it right and I'm learning this stuff, but I just don't know. Should I post to an intermediate page first?
Example: form (variables A & B) to-> page (A & B used in query) and then result is on that same page.
can this be done and what's the method?
Thanks!
This is the basic priniciple, but you must sanitize you input data from the form. For example using mysql_real_escape_string().
But in a single page you can have code like this (it is not tested, I'm not able to on this computer):
<?php
if(isset($_POST['name']))
{
$query = "SELECT * FROM table WHERE firstname = '"+ mysql_real_escape_string($_POST['name']) +"'";
while($node = mysql_fetch_rows())
{
echo "The result: " . $node['id'];
}
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name" />
</form>
This will post to it self, run the query and echo the result, and show the form again.
For small tools and the like, this is an ok approach, but for larger websites I would recommend not mixing the request handling code with the html. Look into using a framework for applying the mvc pattern or something like that.
Without specific examples it's hard to write it, but it's fairly simple.
In a very basic way:
File1.php:
--your form submits to file2.php--
File2.php:
function processForm(inputs) [
--MySql query goes here--
]
function displayResults() [
--Process your query results--
]
processForm($_POST['vars']...);
displayResults();
Does that make sense? Simply make a function that processes and then displays the results again.
If you want to get really fancy you can even do it all in a single file, but you should probably master this technique first if you are first learning.

Categories