If statement doesn't work in a function - php

Not sure if this is a common problem or not, but I ran upon it. When trying to put a if/else statement into a function, it simple does not work. But when do the if/else without the function, it does work (So, I know that the if/else is correct).
I have 2 separate documents, Home.php and Functions.php here is what I have inside those files"
Home.php (the PHP)
<?php
$db = new PDO("mysql:host=localhost;dbname=TEST;charset=utf8","Xero","");
include("Functions.php");
menu();
?>
And then we have the Functions.php (the PHP)
<?php
$db = new PDO("mysql:host=localhost;dbname=TEST;charset=utf8","Xero","");
function menu() {
echo "
<div id='menu'>
<div id='user-menu'>
";
// Check AutoLogin-User then :
$getAutoUser = $db->prepare("SELECT * FROM `users-PHP_FNC` WHERE `ip`='" . $_SERVER['REMOTE_ADDR'] . "'");
$getAutoUser->execute();
if ($autoUser = $getAutoUser->fetch(PDO::FETCH_ASSOC)) {
echo "
" . $autoUser['user'] . "
";
}
// If no AutoLogin-User was found:
else {
echo "
Test
";
}
echo "
</div>
</div>
";
}
?>
Not sure why this doesn't work. Are you not allowed to have if/else statements in a PHP function?

Actually, you can be sure that if ... else statements work inside the scope of a function.
Therefore, the problem lies elsewhere... But there is another thing that you should do:
// Replace this
if ($autoUser = $getAutoUser->fetch(PDO::FETCH_ASSOC))
// By this
if ($autoUser == $getAutoUser->fetch(PDO::FETCH_ASSOC))
Why ?
Because when you say if ($something = $somethingElse) you tell PHP different things in a particular order:
1st => assign the current value of $somethingElse to $something
2nd => test if $something and $somethingElse share the same value
2nd becoming obviously true because of 1st.
To bypass the 1st step, simply use == in place of =.

$db is not in the function's scope. You would have to pass it in. I would make my code more like:
// connect.php - should be in a separate secure folder I'll call restricted
<?php
function db(){
return new PDO('mysql:host=localhost;dbname=TEST;charset=utf8', 'Xero', '');
}
?>
// index.php
<?php
include_once 'restricted/connect.php';
function menu(){
$db = db();
echo "<div id='menu'><div id='user-menu'>";
// Check AutoLogin-User then :
$getAutoUser = $db->prepare("SELECT * FROM `users-PHP_FNC` WHERE ip='{$_SERVER['REMOTE_ADDR']}'");
$getAutoUser->execute();
if($autoUser = $getAutoUser->fetch(PDO::FETCH_ASSOC)) {
echo $autoUser['user'];
}
else{
// If no AutoLogin-User was found:
echo 'Test';
}
echo '</div></div>';
}

Related

How to declare and use global variables

On this test page https://wintoweb.com/sandbox/question_2.php , the visitor can make searches in the DB and tick as many checkboxes as wished. When button [Accept...] is clicked, I want the result of all searches to be shown under 'Your selections so far'. Right now, only the last search is displayed. I tried using a global array to store the result of previous searches and increment it upon each new one. That's where I have a problem.
On top of file I have :
<?php
global $all_authors;
array ($all_authors, '');
?>
At bottom of file I have :
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
if(isset($_GET['search'])){
//echo 'Search</br>';
} elseif(isset($_GET['display_this'])) {
echo getNames();
}
function getNames() {
$rets = '';
if(isset($_GET['choices']) and !empty($_GET['choices'])){
foreach($_GET['choices'] as $selected){
$rets .= $selected.' -- ';
}
//array_push($all_authors, $rets); // This is the problem
//print_r($allAuthors); // this too
echo '</br><b>Your selections so far :</b></br>';
}
return $rets;
}
?>
EXPECTED: Results of all previous searches to be listed
ACTUAL: No go due to problem with array_push(). See function gatNames()
You should make the array global inside the function, so on top:
$all_authors = array();
In the bottom:
function getNames() {
global $all_authors;
// Do the rest of the stuff
}
You are returning $rets from your getNames function but not using it. You just need to use this variables $rets instead of Global Variable.
if(isset($_GET['search'])){
//echo 'Search</br>';
} elseif(isset($_GET['display_this'])) {
$rets = getNames(); //The $rets will hold the value returned by your function getName().
if( !empty ( $rets ) ) {
echo '</br><b>Your selections so far :</b></br>';
echo $rets;
}
}
You could remove the echo statement from inside your getNames Method.
function getNames() {
$rets = '';
if(isset($_GET['choices']) and !empty($_GET['choices'])){
foreach($_GET['choices'] as $selected){
$rets .= $selected.' -- ';
}
}
return $rets;
}

PHP PDO: Object auto-deconstructs after calling function

I've got a situation, where the object created in the top position in my PHP file, gets deconstructed before reaching the end of the PHP code on that file
File1.php:
//* This is all in the same PHP file *//
<?php
session_start();
include 'includes/user.inc.php';
$userOBJ = new User; //Declaring the object
?>
//*** jQuery and HTML code here ***//
<?php
if($userOBJ->isAdmin($_SESSION['session_u-name']) == true){
AdminControl();
}
// This code gets done without any problem
function AdminControl(){
echo "<a id='dbControlAdmin' onclick='changeDisplayAdm()'>Database
Control</a>";
}
?>
//*** More HTML and jQuery Code here ***//
<?php
$userOBJ->getUsersName(); //The object is no longer available when reaching this code
?>
In the Object Class I have this function as the deconstructor:
public function __destruct(){
echo "<b style='color: red;'>Status:</b> Database Connection->Disconnect";
}
This are the functions that are called through the Object:
public function isAdmin($user){
$userToGet = $user;
$stmt = $this->Connect()->prepare("SELECT admin_db FROM user_secure WHERE username_db=?");
$stmt->execute([$userToGet]);
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$value = $row["admin_db"];
if($value == 1){
return true;
} else {
return false;
}
}
}
public function getUsersName(){
$stmt = $this->Connect()->prepare("SELECT username_db FROM user_secure");
$stmt->execute();
while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)){
echo "<option value='" . $row['username_db'] . "'>" . $row['username_db'] . "</option>";
}
}
}
When I run the website, in the top left corner appears this message
Status: Database Connection->Disconnect
Which is the instruction that the object has in the __destruct function, and the website deploys a PHP error where that last function call is: $userOBJ->getUsersName();
The error is:
Notice: Undefined index: username_db in C:\wamp64\www\NewKali\includes\user.inc.php on line 57
I don't get where the __destruct function is called or why it is called! Hope that you can help me.
Thank you for your time!
rename column username_db into a column, which actually exists on the server.
OWNER EDIT:
I changed $row['username_db'] to $row["username_db"] and it worked... (Also changed a few other things)
My final code in the function was this:
public function getUsersName(){
$stmt = $this->Connect()->prepare("SELECT * FROM user_secure");
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$value = $row["username_db"];
echo "<option value='" . $value . "'>" . $value . "</option>";
}
}
You're setting $userOBJ = new User twice.

How to get a single variable attached to the URI?

I don't seem to able to acquire a GET variable that is attached to the URI.
The codes are => at the controller
...
parse_str($_SERVER['QUERY_STRING'], $_GET);
....
$data['ti'] = $this->input->get('hamleno');
this->load->view('anasayfa', $data);
The codes are => at the view the link is
...
<div class="row"><?php for ($b=0; $b<=(count($hml)-1); $b++) { ?><?php echo $hml[$b]." "; ?> <?php } ?></div>
The link is working. I have added the
$config['uri_protocol'] = "PATH_INFO";
to the config.php file.
However I am not able to get the $ti variable
if ($ti){
$t=$ti;
}else{
$t = $this->input->post('t');
if (!$t) $t = 0;
if( $this->input->post('ileri') ) {
$t=$t+1;
if($t>($uz-1)){
$t=$uz-1;
}
} // Forward button was pressed;
if( $this->input->post('geri') ) {
$t=$t-1;
if($t<0){
$t=0;
}
} // Back button was pressed;
}
I'm not familiar with codeigniter, but I've always passed GET variables in this manner:
URL = www.site.com/folder/webpage.php?myvariable=myvalue
I would retrieve that value this way:
$x = $_GET['myvariable'];
or with codeigniter: (I think)
$x = $this->input->get('myvariable');
Tailored to your example, I would personally de-obfuscate your loop code just a little and instead of switching from PHP to HTML and back in one line, I would simply echo both from PHP like this:
(I also don't exactly understand the url you're using, so here is my approximate)
<?php
for ($b=0; $b<=(count($hml)-1); $b++)
{
echo '',$hml[$b],' ';
}
?>
I found out how Codeigniter solves the problem =>
$get = $this->uri->uri_to_assoc();
if(isset($get['hamleno'])){
$data['ti'] = $get['hamleno'];
}
This sends the $b assigned to $hamleno together with all the other stuff in $data.
Thank you all for your kind comments

How can I set a variable variable from within a function in PHP?

I am making a form, some of which is optional. To show the output of this form, I want to be able to check whether a POST variable has contents. If it does, the script should make a new normal PHP variable with the same value and name as the POST variable, and if not it should make a new normal PHP variable with the same name but the value "Not defined". This is what I have so far:
function setdefined($var)
{
if (!$_POST[$var] == "")
{
$$var = $_POST[$var]; // This seems to be the point at which the script fails
}
else
{
$$var = "Not defined";
}
}
setdefined("email");
echo("Email: " . $email); // Provides an example output - in real life the output goes into an email.
This script doesn't throw any errors, rather just returns "Email: ", with no value specified. I think this is a problem with the way I am using variable variables within a function; the below code works as intended but is less practical:
function setdefined(&$var)
{
if (!$_POST[$var] == "")
{
$var = $_POST[$var];
}
else
{
$var = "Not defined";
}
}
$email = "email"; // As the var parameter is passed by reference, the $email variable must be passed as the function argument
setdefined($email);
Why don't you do it this way:
function setdefined($var)
{
if (isset($_POST[$var]) && !empty($_POST[$var]))
{
return $_POST[$var];
}
else
{
return "Not defined";
}
}
$email = setdefined('email');
echo("Email: " . $email);
The variable you create in first example is only available inside the function
You could make that unknown variable submitted by possibly malicious user, global one. To do so, add this to the start of your function:
global $$var ;
This is not only ugly, but maybe unsafe too.

Writing dynamic URL paths WITHOUT mod_rewrite

So, right now I'm trying to generate dynamic URLs as well as their paths without using .htaccess or the use of modules. Basically, I'm trying to rewrite and output URL paths that work statelessly on different localhosts served by Apache.
I would like to have an index.php that gets URIs through a query string like this (obviously not code):
-> index.php (echos dynamically generated URL hyperlinks)
-> index.php?q=/ (echos every URI in JSON)
-> index.php?q=/some_id (outputs table some_id info w/ links to reviews)
-> index.php?q=/some_id/reviews (outputs table column of reviews w/ link to review_ids)
-> index.php?q=/some_id/reviews/review_id (output related column info)
Could someone walk me through how I'd go about doing this? I figure I'm going to have to write the URL using $_SERVER methods and explode while iterating through an array of table IDs..?
Any help is greatly appreciated!
EDIT:
Here's the code I was trying to write :/
<?php
$db = $user = $pw = 'logininfo';
try {
$dbconn = new PDO('mysql:host=localhost;db='.$db, $user, $pw;
}
catch (Exception $e) {
echo "Error: ";
echo $e->getMessage();
}
?>
<!DOCTYPE HTML>
<head>
<title>Product Reviews</title>
</head>
<body>
<h1>Product List:</h1>
<h2>
<ul>
<?php
try {
$sql = "SELECT somename, some_id FROM products";
$stmt = $dbconn->query($sql);
if($stmt !== false) {
foreach($stmt as $row) { //output just name
echo "<li>";
echo htmlentities($row['somename'])."<br />";
if($stmt !== false) {
$url = "<a href=index.php?q=".
htmlentities($row['some_id'])."/>".
htmlentities($row['somename'])."'s Review</a>";
echo $url; //output URL
echo "</li>"."<br />";
}
else {
echo "Unnecessary";
}
}
if($_GET['url']) { //don't really know what to put here
header("Location: $url"); //can't use headers anyway
}
}
$stmt = null;
}
catch (PDOEXCEPTION $e) {
echo $e->getMessge();
}
?>
</ul>
</h2>
</body>
</html>
You can write URLs as :
http://example.org/index.php/reviews/id/ [where id can be your review id]
and use $_SERVER['PATH_INFO'] in index.php to get part of URL which is after index.php, then explode the text and get desired data out of it.
<?php
$query_string = explode('/', $_SERVER['PATH_INFO']);
switch(count($query_string)) {
case 2:
$some_id = (int) $query_string[1];
if ($some_id === 0) {
//(echos every URI in JSON)
}
else {
// (outputs table some_id info w/ links to reviews)
}
break;
case 3:
//(outputs table column of reviews w/ link to review_ids)
$some_id = (int) $query_string[1];
$table_name = $query_string[2];
break;
case 4:
//(output related column info)
$some_id = (int) $query_string[1];
$table_name = $query_string[2];
$review_id = (int) $query_string[3];
break;
default:
// Error case
}
?>
Try this for size
if (isset($_GET['q']) && !empty($_GET['q']))
{
$params = explode("/",$_GET['q']);
if (isset($params[3]) && !empty($params[3]))
echo "(output {$params[2]} {$params[3]} info)";
else if (isset($params[2]) && !empty($params[2]))
echo "(outputs table column of {$params[2]} w/ link to review_ids)";
else if (isset($params[1]) && !empty($params[1]))
echo "(outputs table {$params[1]} info w/ links to reviews)";
else
echo "(echos every URI in JSON) ";
}
else
echo "(echos dynamically generated URL hyperlinks)";

Categories