How to display results of a php method in an html page - php

I've built a contest system where users submit tickets then one is randomly chosen to win, and now I'm trying to figure out a way to display to users the tickets they have already submitted. Each ticket has an id, a date, and an invoicenumber. I want to display all the invoice numbers that a user has submitted so far.
Here is the method I have in my methods page. (I've organized my methods into one php file and then i just call them when needed.)
function GetSubmittedBallots()
{
if(!$this->CheckLogin())
{
$this->HandleError("Not logged in!");
return false;
}
$user_rec = array();
if(!$this->GetUserFromEmail($this->UserEmail(),$user_rec))
{
return false;
}
$qry = "SELECT invoicenumber FROM entries WHERE user_id = '".$user_rec['id_user']."'";
$result = mysql_query($qry,$this->connection);
while($row = mysql_fetch_array($result))
{
echo $row['invoicenumber'];
}
}
and then on my html page that I want it to echo on, i just call it
<?php GetSubmittedBallots(); ?>
Sadly, this doesn't work. So my question is, how would i go about displaying the $row array on my html page?

<?php
require("methods.php"); // Include the file which has the "GetSubmittedBallots" function or method, if it's in a separate file
GetSubmittedBallots(); // Run the function / method
?>
If this doesn't work, please let us know any errors you receive.

Does it echo "Array"?
That's because you are trying to echo an array.
You should use something like print_r or var_dump, given that you are just trying to access the queried results. In my opinion the method should build a multidimensional array with the records, and then the template logic should loop through them and echo the values in a nice way. Be it a table or nicely arranged HTML.

If I'm not wrong, $this keyword is indicating you're in a class? If so, you need first to init that class and try to call GetSubmittedBallots function after init;
// assuming that class's name is Users
$users = new Users();
$users->GetSubmittedBallots();

Related

How can I assign a php return value without causing my sql to run twice?

I am making a wordpress plugin that deals with forms.
I have a form that upon submit, a function is called to insert the values into the DB.
From that function, I am returning the clientID value which was auto Incremented.
I then assign that returned value to a new variable in a new form on the same page.
It works, but I am getting two DB inserts now. IT seems when I assign the new Variable to the function, it runs the insert statement twice.
What I am trying to accomplish is to insert the user into the first table within a function and return just the Clients ID so I can than use the ID for another table insert.
Any help would be appreciated.
The form which on submit calls the function to insert into DB
<form action="" id="new_client_form" method="POST" onsubmit="return submit_new_client()">
The function which contains DB code and returns Client ID
function submit_new_client () {
if (isset($_POST['submit'])) {
/////
$insertClient = $db -> exec("INSERT INTO client SET .......");
$clientId = $db -> lastInsertId();
echo $clientId .'Is the New client ID';//This is printing the correct ID(used for testing)
}
return $clientId;
}
add_action('init', 'submit_new_client');
The new form/ Where I assigned the variable to the function
<?php
$client = submit_new_client();
if(isset($_POST['submit'])) {
echo "<p>The Client Id is</p>";
echo "$client";
} else {
echo "<p>No client ID</p>";
}
?>
For example, Once the form is submitted I will get an Echo from the function saying the Client ID is 32. But when I go down to the next form it will say the Client ID is 33.
First off, in the HTML form, you have onsubmit="return submit_new_client(). The onsubmit attribute is used to call a Javascript function, not a PHP function, so I'm surprised the PHP function is being called at all.
Is it possible for you to post the code in its entirety?
Edit: I did a brief search on the add_action function you're calling. Are you sure that this call isn't calling your submit_new_client() function at some point? See the documentation I found here: https://codex.wordpress.org/Function_Reference/add_action

change body of if statement based on its condition

Here is my question
I have a class say ABC and a function XYZ defined inside it and that function is returning something based on the above logic in it.
class ABC {
function XYZ{
..........
.......
return "--- ";
}
}
Now there is an object on another page of this class which calls this method.
$z= new ABC;
if( $z->XYZ() )
{
some output
}
else{
another output
}
My problem is i dont have access to PAGE 2. but i need to change the output of else statement. I have only access to class ABC because i am overriding it in a module. so, in short i can only alter function XYZ. Whats the solution??
If its of any significance, i am working on MAGENTO ECOMMERCE Platform and class is a block class and page 2 is a template
You can alter the output html with an observer with the http_response_send_before event.
Capture the html and do your stuff.
You have a good explanation here
I hope this can help you
you can also do as follow :
<?php
ob_start();
// do your stuff
// ...
// here you capture all the output that it is generated by your scripts
$v = ob_get_contents();
// alter the value of $v by detecting if it should be changed. you can user regex for example to
// detect and update
// ...
// here you clean all data stored in buffer
ob_clean();
// and put the updated data in buffer
print $v;
// end of buffer operations
ob_end_flush();
?>
hope it helps,
You need a way to differentiate PAGE1 from PAGE2, lets say by the URL if it's possible. So you would have to change your method that will check on which page is currently and according to it, it will change the output, but you must write the output in the method itself instead of writing it in the template.
class ABC {
function XYZ {
$result = $this->getResult(); //Helper method to get the result.
if ($result) {
//Do something when result is true.
} else {
$url = $this->checkUrl(); //Check URL of the page.
if ($url == PAGE2) { //If you are on PAGE2
//Do something specific for the PAGE2
} else {
//Do something for all other pages
}
}
}
}
I know it's not the perfect solution, but I hope it will help you somehow.
The page number has to be specified somewhere in the $_GET or the $_POST array (or in another query). Check that variable and implement the alternative logic.

Pulling data with specific parameters from db using PHP

Let's say I have 3 columns/divs/sections in my html layout, let's call them cat1, cat2, cat3. Then I have a database with a table called "Content". In that table I have the fields id, title, content, category.
Now I want to populate those 3 columns with their corresponding content from my mysql table. For example - get all the content from table where category = cat1(corresponding to the first column).
I could just make 3 functions that each have their own parameter, but I don't want to repeat code. How can I do this with a single function, but just using a different parameter?
I was thinking something like this:
public function displayAll_with_category ($category) {
$sql = $con->prepare("SELECT * FROM Table WHERE Category=?");
$sql->bindParam(1, $category);
$sql->execute();
while ($row = $sql->fetch()) {
echo $row['Title'];
}
}
Then in my HTML:
<div id="cat1">
// Using a central class
<?php include('class.php'); $obj = new handler; $obj->displayAll_with_category(); ?>
</div>
So far so good, I need to somehow be able to alter the $category parameter so I can use the same function to call the contents for cat1/2/3. I have no idea how to do that, usually I need to send something to the PHP function via a button or form, but this time that's not the case. Is this even doable in pure PHP? I can think of doing this with AJAX, but for now I want to know if it can be done with PHP.
I'm not sure if this is what you want.
This would get you the data for category 1, 2 and 3.
I just created a loop in the view to call the function with different parameters:
<?php
for($cont = 0; $cont<4; $cont++){
?>
<div id="cat1">
// Using a central class
<?php include('class.php'); $obj = new handler; $obj->displayAll_with_category($cont); ?>
</div>
<?php
}
?>
Oh and if I were you i would try to separate the logic from the view and I will print the result of the function in the view instead of doing it inside it.

Do I have an instance of this object?

I keep getting an 'Undefined variable' notice when I call on an object I 'think' I have instantiated, but apparently haven't. I can't put a finger on my the error. The object is $fgmembersite, according to my error messages it doesn't exist, I'm confused about why. It maybe a simple case of me messing up my directories in the include/require portion of my scripts but I've been looking at them and can't see anything wrong. Tell me if you guys want to look at my file hierarchy.
And again thanks for the help!
I have three PHP files that are at play.
First one is login-home.php
<?PHP
require_once("./profile_settings/view.php");
if(!$fgmembersite->CheckLogin())
{
$fgmembersite->RedirectToURL("login.php");
exit;
}
?>
/*a bunch of stuff*/
<img id="profile_avatar" src="profile_settings/<?php echo fetchAvatarLocation(); ?>"></img>
/*a bunch of stuff*/
Next I have view.php which holds a function I use to generate the path-name of where I store my picture.
<?php
include("./include/membersite_config.php");
function fetchAvatarLocation()
{
$user_id = $fgmembersite->UserId();
$query = mysql_query("SELECT * FROM ddmembers WHERE id_user = '$user_id'");
if(mysql_num_rows($query)==0)
die("User not found!");
else
{
$row = mysql_fetch_assoc($query);
$location = $row['imagelocation'];
return $location;
}
}
?>
And finally I have membersite_config.php
<?PHP
include("fg_membersite.php");
$fgmembersite = new FGMembersite();
//Provide your site name here
$fgmembersite->SetWebsiteName('Mysitename.com');
//Provide the email address where you want to get notifications
$fgmembersite->SetAdminEmail('My.Email#Provider.net');
//Provide your database login details here:
//hostname, user name, password, database name and table name
//note that the script will create the table (for example, fgusers in this case)
//by itself on submitting register.php for the first time
$fgmembersite->InitDB(/*hostname*/'localhost',
/*username*/'user',
/*password*/'password',
/*database name*/'database',
/*table name*/'table');
//For better security. Get a random string from this link: http://tinyurl.com/randstr
// and put it here
$fgmembersite->SetRandomKey('**************');
?>
fg_membersite is a file that contains the class fgmembersite that stores a bunch of functions, the ones that I need it for are...
function UserId()
{
return isset($_SESSION['userid_of_user'])?$_SESSION['userid_of_user']:'';
}
function UserName()
{
return isset($_SESSION['username_of_user'])?$_SESSION['username_of_user']:'';
}
The object is not in the scope of the function, so it is undefined. You need to pass it in as a parameter:
function fetchAvatarLocation( $fgmembersite)
Then call it with the object as a parameter:
<img id="profile_avatar" src="profile_settings/<?php echo fetchAvatarLocation( $fgmembersite); ?>"></img>
An alternative is to use global variables, but I wouldn't recommend it.

Display personal messages list

I have a personal message system in my website done simply with php/sql. Actually I am facing the trouble to display them using jquery. The db has as fields: message_id, message_from, message_to, message_topic, message_subject and message_status. The way I am showing the message_topic is repeating eight times the following:
echo '<table><tr><td>';
retrieve_msg_topic($result);
echo '</td></tr>'; //of course I won't make 8 tables!!!
the function called is:
function retrieve_msg_topic($result)
{
if($row = mysql_fetch_assoc($result))
{
echo $row['usernombre'];
$message_topic = stripslashes($row['message_topic']);
echo '<div id="msg'.$row['message_id'].'">';
echo $message_topic;
echo '</div>';
//this will return: <div id="msgN">message topic (title, commonly subject)</div>
}
} //end function retrieve msg topic
So far I have a list on a table with the last eight messages sent to the user. The following row is reserved for pagination (next/prior page) and, after that, another row showing the message I select from the list presented, like we see in Outlook. Here is my headache. My approach is to call another function (8 times) and have all of them hidden until I click on one of the messages, like this:
echo '<tr><td>';
retrieve_msg_content($result);
retrieve_msg_content($result); //repeat 8 times
echo '</td></tr></table>';
the function this time would be something like this:
function retrieve_msg_content($result)
{
if($row = mysql_fetch_assoc($result))
{
echo '<script type="text/javascript">
$(document).ready(function(){
$("#msg'.$row['message_id'].'").click(function(){
    $(".msgs").hide(1000);
$("#'.$row['message_id'].'").show(1000);
});
});
</script>';
echo '<div class="msgs" id="'.$row['message_id'].'" style="display: none">'
.$row['message_subject'].
'</div>';
}
/* This function returns:
// <script type="text/javascript">
// $(document).ready(function(){
// $("#msgN").click(function(){
// $(".msgs").hide(1000);
// $("#N").show(1000);
// });
// });
// </script>
// <div class="msgs" id="N" style="display: none">Message subject (body of message)</div>
*/
} //end function retrieve msg content/subject
I could simply explain that the problem is that it doesn't work and it is because I do if($row = mysql_fetch_assoc($result)) twice, so for the second time it doesn't have any more values!
The other approach I had was to call both the message_topic and message_subject in the same function but I end up with a sort of accordion which is not what I want.
I hope I was clear enough.
The easiest way to fix your troubles would be to copy the results of the MySQL query into an array
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
And then use that to build your tables.
edit: What I meant was more along the lines of this:
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
echo '<table>';
foreach($yourArray as $i) {
retrieve_msg_topic($i);
}
echo '<tr><td>';
foreach($yourArray as $i) {
retrieve_msg_content($i);
}
echo '</tr></td></table>';
And then removing everything to do with the SQL query from those functions, like this:
function retrieve_msg_topic($result) {
echo '<tr></td>'$result['usernombre'];
echo '<div id="msg'.$result['message_id'].'">';
echo stripslashes($result['message_topic']);
echo '</div><td></tr>';
}
Right now you're doing some weird key mojo with ret[0] being the topic and $ret[1] being the message, which isn't a good practise. Also, I don't see the declaration of $i anywhere in that code.
The error suggests that the result is empty or the query is malformed. I can't be sure from the code I've seen.
A few other notes: it seems weird that you're using stripslashes() on data that's directly from the DB. Are you sure you're not escaping stuff twice when inserting content into the DB?
Always use loops instead of writing something out x times (like the 8 times you said in your question). Think of a situation where you have to change something about the function call (the name, the parameters, whatever). With loops you have to edit 1 place. Without, you need to edit 8 different places.
BTW, another solution to this problem would be using AJAX to load content into the last cell. If you're curious, I could show you how.
more edits:
For AJAX, build your message list as usual and leave the target td empty. Then, add a jQuery AJAX call:
$('MSG_LIST_ELEMENT').click(function() {
var msgId = $(this).attr('id').replace('msg','');
$.get(AJAX_URL+'?msgID='+msgId,function(data) {
$('TARGET_TD').html(data);
})
});
Replace the capitalized variables with the ones you need. As for the PHP, just echo out the contents of the message with the ID $_GET['msgID'].
However, make sure you authenticate the user before echoing out any messages, so that someone else can't read someone's messages by switching the id number. Not sure how authentication works on your site, but this can be done by using session variables.

Categories