Quantcast
Channel: PHP Freaks: PHP Help
Viewing all 13200 articles
Browse latest View live

php search help

$
0
0

Hi

 

I am making a search form where the admin can search for a name using a input field and returns the results for records that match the name, that side of it works but I can't get the id record number retrieved from the db and make it a clickable link but I get the following error in the id column

 

Notice: Trying to get property of non-object in /home/firstqualityfina/public_html/admin/unsecured-loan-applicants/search-unsecured-loan-applicant-results.php on line 97

 

On line 97 is the following

echo "<a href='view-specific-unsecured-loan-applicant.php?id=" . $results->id ."'>".$results->id . "</a>";

The whole code looks like the following

<?php
//load database connection
    $host = "localhost";
    $user = "";
    $password = "";
    $database_name = "";
    $pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ));
// Search from MySQL database table
$search=$_POST['search'];
$query = $pdo->prepare("select id, fullname, address, emailaddress, phonenumber, mobilenumber, amountloan, term, homeowner, DATE_FORMAT(loanappdate, '%d/%m/%Y') AS 'loanappdate' from unsecured_loans where fullname LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();

$query->execute();
// Display search result
         if (!$query->rowCount() == 0) {
			 	echo "<div style='clear: both;'>";
				echo "<br><br>";
echo "<table class='records'>";
echo "<thead>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Full Name</th>";
echo "<th>Address</th>";
echo "<th>Email Address</th>";
echo "<th>Phone Number</th>";
echo "<th>Mobile Number</th>";
echo "<th>Unsecured Loan Amount</th>";
echo "<th>Term(Months)</th>";
echo "<th>Applicant Status</th>";
echo "<th>Unsecured Loan Application Date</th>";
echo "<th>Actions</th>";
echo "</tr>";
           echo "</thead>";

		   while ($results = $query->fetch()) {
				echo "<tr><td>";
				echo "<a href='view-specific-unsecured-loan-applicant.php?id=" . $results->id ."'>".$results->id . "</a>";
				echo "</td><td>";
                echo $results['fullname'];
				echo "</td><td>";
                echo $results['address'];
				echo "</td><td>";
                echo $results['emailaddress'];
				echo "</td><td>";
                echo $results['phonenumber'];
				echo "</td><td>";
                echo $results['mobilenumber'];
				echo "</td><td>";
                echo '£' . $results['amountloan'];
				echo "</td><td>";
                echo $results['term'];
				echo "</td><td>";
                echo $results['homeowner'];
				echo "</td><td>";
                echo date("d/m/Y", strtotime($results['loanappdate']));
				echo "</td><td>";
				echo '<a onClick=\"javascript: return confirm("Are you sure you wish to delete this applicant?");\" href="delete.php?id=<?= $row["id"]; ?>">Delete</a></td>';
				echo "</tr>";
				echo "</table>";

		   }
		 }
	?>

Thank you in advance


Datagrid suggestion

$
0
0

I thought it would be more useful to move my biz app to the web, so I can work on it on the go. Everything went well! The only section I am stuck on is a page where I need to put in products and services.

qty, desc, cost, total, then sub totals (labor,tax etc.)

 

I've searched the net for  some ideas, and most were overkill, others were too confusing. it is just one page I need.  currently I just set up a table with JS but that seems to be more work than needed. Needs to adjust on the fly, ergo why I am using JS with the table. But my code seems to be more complex than needed, as it seems I am looking for a spreadsheet style.

if i put "1" qty column I want the total to reflect it with the cost, and the totals as well. but the way I am going at it, is horrible (mostly because It needs to be JS, and I am not that fluent in it)

 

anyone run across this, and how I might implement something of this nature - doesn't even have to be a table. I only enter at most 2 - 5 items at any given time. Do not want to use jquery if I do not need to. The page I currently have is a huge mess as I have been working on it forever LOL. Just cant get it to work.

 

don't need code, just shoot me with some ideas, I'll scratch my head from there.

Undefined Index if ID added to text field

$
0
0

Hi all,

 

Strange one.

I have Google Maps Places API added to a text field for Autocomplete purposes. However, if I add the id="address" to the text field and save the data I get Undefined Index.

 

Here is the text field:

<div class="form-group">
<label><?php echo $lang_company_address; ?></label>
<input type="text" class="form-control" id="address" name="company_address" value="<?php echo $row['company_address']; ?>"/>
</div>

Here is where I am getting the Undefined error:

$company_address = mysqli_real_escape_string($mysqli, $_POST['company_address']);

And here is the Google JS code:

    <script>
            function initMap(){
                var autocomplete = new google.maps.places.Autocomplete($("#address")[0], {});

                google.maps.event.addListener(autocomplete, 'place_changed', function() {
                    var place = autocomplete.getPlace();
                    console.log(place.address_components);
                });
            }
        </script>

The script above works fine. Although I do get the dreaded Ooops Something went wrong error, which I presume is tied to the above somehow.

The API key is called as below:

<script src="https://maps.googleapis.com/maps/api/js?key=<?php echo $row['google_api']; ?>&libraries=places&callback=initMap" async defer></script>

The key is stored in the database.

 

Any ideas?

Combine validators together with formvalidation.io ?

$
0
0

I'm using a Bootstrap multiselect (https://github.com/davidstutz/bootstrap-multiselect ) which I want to validate on a form (defaultForm) with a formvalidator (The best jQuery validation plugin to validate form fields, support Bootstrap, Foundation, Pure, SemanticUI, UIKit frameworks - FormValidation) .

This example works fine. It revalidate on selecting a option from the multiselect.

'tags[]': {
                   validators: {
                        callback: {
                            message: 'Select one or more options</font>',
                            callback: function(value, validator, $field) {
                                    var options = validator.getFieldElements('tags[]').val();
                                    return (options != null && options.length >= 1 && options.length <= 10);
                            }
                        }
                    }
                },

But I want this to validate when another dropdown menu has selected "Yes". (it has two options as a answer - Yes and No). I also get this thing to work with the following code.

'tags[]': {
                   validators: {
                        callback: {
                            message: 'Select one or more options</font>',
                            callback: function(value, validator, $field) {
                                   var x = document.getElementById("data_important");
                                   var i = x.selectedIndex;
                                   return (x.options[i].text == 'No') ? true : (x.options[i].text == '');
                            }
                        }
                    }
                },

So both options works fine, but I can't get them combine together, that the it's going to validate only when another dropdown (data_important) is chosen"Yes" and that it revalidates when selecting a option on the multiselect with name "tags[]".



Is there a fix to combine them together, that both elements works?

 

 

Attached Thumbnails

  • voorbeeld.png

How can I display the name of the month that the user requests?

$
0
0

I have the basics of it down, I just don't know how to output the name of the month with the number in the array.

Number formating and calculating within array

$
0
0

Hi everyone,

 

I have this php code in which I can apply a number format feature when echoing $ask:

 

<!DOCTYPE html>
<html>
<body>
  <?php
    $json_string = file_get_contents("https://api.flowbtc.com:8400/GetTicker/BTCBRL/");
    $parsed_json = json_decode($json_string);
    $ask = $parsed_json->{'ask'};
    echo number_format($ask, 2, ',', '');
  ?>
</body>
</html>
 
However, when I do it within an array so it works with my Messenger chatbot, it simply doesnt work.
 
In the example below how can I do the number formating in the result of .$ask * 1.025 on the "value" line?
 
<?
 
header('Content-Type: application/json');
////Text / Image / Structured
 
/// $_POST['message'];   /// Message user Inputs
/// $_POST['senderid'];   /// Facebook Sender ID
///
 
    $json_string = file_get_contents("https://api.flowbtc.com:8400/GetTicker/BTCBRL/");
    $parsed_json = json_decode($json_string);
    $ask = $parsed_json->{'ask'};
 
 
 
$received_message = $_POST['message'];
 
$message = array();
 
 
///Text Message
$message['bmsg'][0] = array(
'type'=>'text',
                                 'value'=>'Valor de referencia de 1 bitcoin incluindo taxas: R$ ' .$ask * 1.025
);
 
echo json_encode($message);
 
?>
 
 
Any help will be appreciated. Thanks!!!
 

Notice: Undefined index: location in /storage/h5/444/813444/public_html/index.php on line 6

$
0
0

Notice: Undefined index: location in /storage/h5/444/813444/public_html/index.php on line 6

 

PHP 5.4 server

 

im getting this error above...

 

script is as below:-

 

pls help anyone?

 

 

 

<?php

 
$GLOBALS['key'] = "thisisapasswordkeytoprotectmarketingplan";
$GLOBALS['expiry'] = 5*60; // in seconds
 
if ($_GET['location'] == 'viewMarketingPlan' && strlen($_GET['key']) > 0 && $_GET['view'] == 'true') {
 
    $key = $GLOBALS['key'];
    $data = trim($_GET['key']);
    $data = base64_decode(strtr($data, '-_,', '+/='));
    $decoded = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), $data, MCRYPT_MODE_CBC, md5(md5($key))), "\0");
    $decoded = explode("|SEAN|", $decoded);
    list($code, $race, $country, $expiry) = $decoded;
 
    if ($expiry >= (time()+$GLOBALS['expiry'])) exit;
 
    if ($country == "IN") {
        $file = "mp-india";
    } else if ($race == "M") {
        $file = "mp-malaysia-ms";
    } else {
        $file = "mp-malaysia-en";
    }
 
    $filepath = "../../marketing-plans/{$file}.pdf";
 
    header('Content-type: application/pdf');
    //header('Content-Disposition: attachment; filename="Tasly-Marketing-Plan.pdf"');
    @readfile(realpath($filepath));
    exit;
}
 
require_once 'functions.php';
 
session_start();
 
if (isset($_SESSION['user'])) {
 
    if ($_SESSION['status'] == 'Active') {
 
        // force auto logout if inacrive for more than 1 hour
        if (strlen($_SESSION['lastActive']) > 0 && ($_SESSION['lastActive']+(1*60*60)) <= time()) {
            header("Location: logout.php");
        }
 
        $_SESSION['lastActive'] = time();
 
        $location=$_GET['location'];
 
        if (empty($location))
            $location='index';
 
        changelocation($location);
    
    } else {
        //the status session variable isn't registered and not equal to active, send them back to the inactive page.
 
        /*
        $host  = $_SERVER["HTTP_HOST"];
   `    $uri   = rtrim(dirname($_SERVER["PHP_SELF"]), "{\\}");
        $extra = "inactiveDist.php";
        */
        header("Location: inactiveDist.php");
    }
 
} else {
 
    //the session variable isn't registered, send them back to the login page
    /*
    $host  = $_SERVER["HTTP_HOST"];
    $uri   = rtrim(dirname($_SERVER["PHP_SELF"]), "{\\}");
    $extra = "login.php";
    */
    header("Location: login.php");
        
 
}
 
 
function changelocation($location) {
 
        $user=$_SESSION["user"];
        $post=$_SESSION["post"];
        $name=$_SESSION["name"];
 
        require_once "dbconnect.php";
        include ('header.php');
        echo '<table cols="3" border="0" cellpadding="10" cellspacing="0" align="center" width="100%">';
 
        echo '<tr>';
        echo '<td width="20%" bgcolor="" valign="top" rowspan="4">';
        include('navbar.php');
        echo '</td>';
        echo '<td bgcolor="" valign="top">';
 
        $locations = array('viewInfo', 'changePass', 'netListing', 'detailNetListing', 'PGS', 'monthPGS', 'downDetail', 'histBonusSum', 'bonusSum', 'periodInq', 'networkbns', 'Inquiry2', 'Inquiry', 'periodActlines', 'periodActlines2', 'ActDownlines', 'ActDownlines2', 'estTotalSales', 'newPromo', 'newProducts', 'productPricing', 'Greenair', 'Pillow', 'viewMarketingPlan');
 
        if (in_array($location, $locations)) {
            // marketPlan2-13
            //substr($location,0,10) == 'marketPlan' && substr($location,10,strlen($location)) >= 2 && substr($location,10,strlen($location)) <= 13) {
 
            require_once "{$location}.php";
 
        } else if (in_array($location, array('index', 'importantNotice'))) {
 
            require_once "main.php";
 
        }
 
        echo '</td></tr></table>';
        include ('footer.php');
}
 

timestamp showing hour which is not there

$
0
0

Hello,

 

I am comparing these 2 time stamps to see how much time has passed. They time passed is 66 seconds.

 

When I format them back into h:m:s, it shows 1 hour, 1 minute and 6 seconds instead of just 1 minute and 6 seconds.

 

I was just wondering why this was?

 

Thanks

$startStamp = 1487156507;
$endStamp = 1487156573;
$howLong = $endStamp - $startStamp;
echo $howLong . "<br>";
echo(date("h:m:s",$howLong)) . "<br>";

Issue with a select statement

$
0
0

So i haven't coded in a while ... and can't figure out why is this happening

 

 

If i did a Select statement like this ...

 

$sql = "SELECT id, player, team, date, min, fppmp, fpts FROM NBA2017 WHERE player='$player' ORDER BY date DESC LIMIT 10 ";

 

it works!!

 

 

 

But i have 42 columns on the DB.... So I changed it to this ..

 

$sql = "SELECT * FROM NBA2017 WHERE player='$player' ORDER BY date DESC LIMIT 10 ";

 

and i get no results ...

 

 

Maybe basic but i need help!!!  Thanks in advance!! ::)

Ahhh! How to assign active class to menu item

$
0
0

I have my menu in an include file called menu.php and I want to assign a class called 'active' to the <li> to the page that I am on. How can I do this in PHP?

<!-- navigation -->
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="index.php">Home</a></li>
<li><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Insect Control <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="insect-control.php">Insect Control</a></li>
<li><a href="ant-cockroach-control.php">Ant & Cockroach Control</a></li>
<li><a href="bed-bug-treatment.php">Bed Bug Treatments</a></li>
<li><a href="fly-control.php">Fly Control</a></li>
<li><a href="wasp-hornets-bee-control.php">Wasp, Hornet & Bee Control</a></li>
</ul>
</li>
<li><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Rodent & Vermin <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="rodent-vermin.php">Rodent & Vermin</a></li>
<li><a href="rats-mice-infestation.php">Rats & Mice Infestation</a></li>
<li><a href="squirrel-control.php">Squirrel Control</a></li>
</ul>
<li><a href="#">Contact</a></li>
</ul>
</div>
</nav>
<!-- end navigation -->

Hello A-Z Help

$
0
0

Hello everyone im new here and im very happy that i found smth good here (just a think).

im trying to create alphabetic power search module for joomla 

 

my web test is this ->http://vps365826.ovh.net/index.php/africa as you can see the alhabetic line

( A B C D E G I K L M N R S T U Z ) as you see some words missing well thats cause i dont have articles with words ex (F) photo ex. ( http://prntscr.com/e9j9iu )

well i want to create it with all alphabetic words even if we dont have article with that word 

i've created with my friend that code 

<div class="ordered">
            <ul>
                <?php
                $db = JFactory::getDBO();
                $query = 'SELECT count(*) as nm, SUBSTR(title,1,1) as alpha FROM #__content WHERE catid = '.$catid.' GROUP BY SUBSTR(title,1,1)';
                $db->setQuery($query);
                $mostIng = $db->loadObjectList();
                foreach ($mostIng as $row) {
                    echo '<li data-text="'.$row->alpha.'">'.$row->alpha.' '.'</li>';
                }
                ?>
            </ul>
        </div>

but i want it somethink like that 

<div class="ordered">

    	<ul>
    		<li class="orderedLabel closed">Αναζήτηση αλφαβητικά ></li>
    		<li>A</li>
    		<li>B</li>
    		<li>C</li>
    		<li>D</li>
    		<li>E</li>
    		<li>F</li>
    		<li>G</li>
    		<li>H</li>
    		<li>I</li>
    		<li>J</li>
    		<li>K</li>
    		<li>L</li>
    		<li>M</li>
    		<li>N</li>
    		<li>O</li>
    		<li>P</li>
    		<li>Q</li>
    		<li>R</li>
    		<li>S</li>
    		<li>T</li>
    		<li>U</li>
    		<li>V</li>
    		<li>W</li>
    		<li>X</li>
    		<li>Y</li>
    		<li>Z</li>
    	</ul>
    </div>

well thanks for your time and sorry for my bad english im trying to learing btw thank you very much!!!

How to create progress bar to show calories left for user to burn to reach their goal

$
0
0

I'm making a calories burned calculator which links to goals the user has made.

 

I want to create a progress bar that updates when the user clicks a button that shows how many calories the user has yet to burn in order for them to reach their goal.

 

I've stored the amount of calories burned for each activity the user inputs.
The users goals are set in either lbs or kg, so I'm not sure how I can set a value for these units. confused.gif?v=3

 

Also, I'm not sure how I should calculate the calories left to burn.

 

I've looked online, however can't find anything that relates to how to made a progress bar with data from an sql database.

 

Database: 'registration' Table: 'tracklog' and 'goal'

 

Any help would be much appreciated!!!

Array checking help

$
0
0

Hi,

 

I am sure that the solution is easy but it's flummoxed me! I have a python script that sometimes doesn't record the temperature so I end up with 23 readings instead of 24 per day, or less.

My php script reads the date from the db and puts it into a array to use in a graph. My problem is that I need to check the correct temperature reading go with the correct hour of the day.

Array
(
    [0] => Array
        (
            [0] => 00
            [1] => 4.30
        )

    [1] => Array
        (
            [0] => 01
            [1] => 4.30
        )

    [2] => Array
        (
            [0] => 02
            [1] => 4.10
        )

    [3] => Array
        (
            [0] => 03
            [1] => 4.00
        )

    [4] => Array
        (
            [0] => 05
            [1] => 3.70
        )
etc etc..

Above [0][0] is the time and [0][1] is the temperature, what I need is for the time to match the array key. So in [4][0] the time is 05 but the key is 04 i.e...

Array
(
    [0] => Array
        (
            [0] => 00
            [1] => 4.30
        )

    [1] => Array
        (
            [0] => 01
            [1] => 4.30
        )

    [2] => Array
        (
            [0] => 02
            [1] => 4.10
        )

    [3] => Array
        (
            [0] => 03
            [1] => 4.00
        )

    [4] => Array
        (
            [0] => 04
            [1] =>
        )

    [5] => Array
        (
            [0] => 05
            [1] => 3.70
        )

This is the code I use to make the array

while($row = $result->fetch_array())
{

$inside[] = $row;

$date = strtotime($inside[$i][Time]);
$inside[$i][4] = date('G', $date);
$inside[$i][2] = $inside[$i][0];

unset($inside[$i][Temp]);
unset($inside[$i][Time]);
unset($inside[$i][1]);
unset($inside[$i][0]);


++$i;

}

I can get it to check the time against the key, but I can not get it to correct the key to the time. 

Can anyone help??

 

Many thanks James

 

 

mysql construct to apply multiple fields to a single like

$
0
0

Still new.  Off topic - not really php?  Hope not.  Who else knows mysql like the php crowd.

 

I find this clause  construct in many places on this new site:

and t2.keyword like concat('%', :bc11, '%')
 or t2.name    like concat('%', :bc12, '%')
 or t2.des     like concat('%', :bc13, '%')

He's trying to find the search term anywhere in any of the 3 fields.  bc11, bc12 and bc13 are binding 'keys' that receive identical values.  Is there a way to build this something like this:?

and any (t2.keyword, t2.name, t2.des) like concat('%', :bc11, '%')

I had to make up something my self :-).  Thanks.

 

Remove bytes off of a string

$
0
0

I have the following script.  When echoing $data, it included some strange character at the beginning of the message

<?php
require 'vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$socket->on('connection', function (\React\Socket\ConnectionInterface $client) use ($loop){
    $client->on('data', function($data){
        echo($data."\r\n");
    });
});
$socket->listen(1337,'0.0.0.0');
$loop->run();

Turns out that $data has 4 bytes pretended on it to represent the length of the message.  On the receiving connection, how can I get those 4 bytes and also remove them from $data.

 


mySQLi statement for multiple databases

$
0
0

I have mySQLi statement that looks similar to this:

$sql = "SELECT  ID, FirstName, Last Name, Email, Mobile, PromoCode
            FROM table1
            WHERE (Email LIKE ?)
            OR (Mobile LIKE ?)
            OR (PromoCode LIKE ?)
            ";
    $stmt = $consd->prepare($sql);
    $stmt->bind_param('sss', $Search,$Search, $Search);

 

Works fine.  But what I cannot seem to find is what if I had two databases with all the same tables and I want to query both of them using mySQLi?

 

I've tried all types of things, but I *think* because it's older mysql code that I'm not getting the syntax quite right...

suggestions on cleaning up my coding

$
0
0

I'm working on my first real project that I coded (other than the user system). I could use some help to know what I could and should clean up in my coding. I am self taught. I know I need to add sanitize codes to the field inputs and that is in the works. Do you see something that would make more sense to be a function in the functions.php include?

Index.php

<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';

sec_session_start();
$PageTitle="Open Managment";
function customPageHeader(){?>
<script type="text/JavaScript" src="js/sha512.js"></script>
<script type="text/JavaScript" src="js/forms.js"></script>
  <!--Arbitrary HTML Tags-->
<?php }
include_once('includes/header.php');
if (isset($_GET['error'])) {
	echo '<p class="error">Error Logging In!</p>';
}
 if (login_check($mysqli) == true) : ?>
        <p>Welcome <?php echo htmlentities($_SESSION['username']); ?>! If you are done, please <a href="includes/logout.php">log out</a>.</p>
          <!--Arbitrary HTML Tags-->

<?php
$results = $mysqli->query("SELECT id, title, address, occupied FROM property");
?>
<div>
	<div class="propr">
	<div class="propc"><h2>Property Title</h2></div>
	<div class="propc"><h2>Address</h2></div>
	<div class="propc"><h2>Occupied</h2></div>
</div>
<?php
while($row = $results->fetch_array()) { ?>
<div class="propr">
	<div class="propc"><a href="list_prop.php?parent=<?= $row['id'] ?>"><?= $row["title"] ?></a></div>
	<div class="propc"><?= $row["address"] ?></div>
	<div class="propc"><?php if ($row["occupied"] == 1) {echo 'yes';} else { echo 'no'; }?></div>
</div>
<?php
}
print '</div>';

?>
  <p> Add a new property:</p>

   <form action="newprop.php" method="post">
        Property Name<input type="text" name="title">
        Address<input type="text" name="address">
        <input type="submit" value="Submit">
        </form>
<div>
<?php
$results = $mysqli->query("SELECT id, first_name, last_name, email, phone FROM tenant");

while($row = $results->fetch_array()) { ?>
<div class="propr">
	<div class="propc"><a href="list_tenant.php?parent=<?= $row['id'] ?>"><?= $row["first_name"] ?></a></div>
	<div class="propc"><?= $row["last_name"] ?></div>
	<div class="propc"><?= $row["email"] ?></div>
	<div class="propc"><?= $row["phone"] ?></div>
</div>
<?php
}


$mysqli->close();
?></div>
<p>Add tenant</p>

 <form action="new_tenant.php" method="post">
        First Name<input type="text" name="fname">
        Last Name<input type="text" name="lname">
        Email<input type="text" name="email">
        Phone Number<input type="text" name="phone">
        <input type="submit" value="Submit">
        </form>
        <?php
              else :
        	echo '<p> You are currently logged out. Please log in.</p>
        <form action="includes/process_login.php" method="post" name="login_form">
            Email: <input type="text" name="email" />
            Password: <input type="password"
                             name="password"
                             id="password"/>
            <input type="button"
                   value="Login"
                   onclick="formhash(this.form, this.form.password);" />
        </form>';
        endif;
   ?>
    </body>
</html>

List_tenant.php

<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';

sec_session_start();
$PageTitle="Open Managment";
function customPageHeader(){?>

  <!--Arbitrary HTML Tags-->
<?php }
include_once('includes/header.php');

?>

<?php if (login_check($mysqli) == true) :     ?>

<p>Welcome <?php echo htmlentities($_SESSION['username']); ?>! If you are done, please <a href="includes/logout.php">log out</a>.</p>
<span> You are veiwing:</span>
 <?php
//get tenant name and current var
 $a = intval($_GET['parent']);
 $results = $mysqli->query("SELECT id, first_name, last_name, current FROM tenant WHERE id = '$a'");
while($row = $results->fetch_array()) {
echo $row["first_name"], '&nbsp', $row["last_name"];
$current = $row["current"];
}
$results->free();


if(isset($_POST['submit'])) {

 $prop_id = $_POST["prop_id"];
 $tent_id = $_GET['parent'];
 $rent = $_POST["rent"];
 $late = $_POST["late"];
 $start_date = $_POST["start_d"];

 $mysqli->query("
		INSERT INTO tenancy (property_id, tent_id, rent, late, start_date, current)
		VALUES ('$prop_id', '$tent_id', '$rent', '$late', '$start_date', '1' );
		");
 $mysqli->query("
		UPDATE tenant SET current='1' WHERE id=' $tent_id';
		");
 $mysqli->query("
		UPDATE property SET occupied='1' WHERE id=' $prop_id';
		");
 $mysqli->close();
} elseif ($current == 0) {
?>

  <form action="list_tenant.php?parent=<?=$a?>" method="post">
  <select name="prop_id">
  <?php //get props for drop down
  $results = $mysqli->query("SELECT id, address FROM property");
  while($row = $results->fetch_array()) { ?>
  	<option value="<?= $row['id'] ?>"><?= $row["address"] ?></option>
  <?php
  }
  ?>
  </select>
  Rent Amount<input type="text" name="rent">
  Late Fee<input type="text" name="late">
  Move in date<input type="text" name="start_d">
 <input type="submit" name="submit" value="submit">
 </form>

 <?php
 $mysqli->close();
 }
 elseif ($current == 1){
 	echo 'they live somewhere';
 }

 ?>

 <p>tenancy info:</p>



<?php else : ?>
            <p>
                <span class="error">You are not authorized to access this page.</span> Please <a href="index.php">login</a>.
            </p>
        <?php endif; ?>
    </body>
</html>


functions.php

<?php


include_once 'psl-config.php';

function sec_session_start() {
    $session_name = 'sec_session_id';   // Set a custom session name
    $secure = SECURE;

    // This stops JavaScript being able to access the session id.
    $httponly = true;

    // Forces sessions to only use cookies.
    if (ini_set('session.use_only_cookies', 1) === FALSE) {
        header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
        exit();
    }

    // Gets current cookies params.
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);

    // Sets the session name to the one set above.
    session_name($session_name);

    session_start();            // Start the PHP session
    session_regenerate_id();    // regenerated the session, delete the old one.
}

function login($email, $password, $mysqli) {
    // Using prepared statements means that SQL injection is not possible.
    if ($stmt = $mysqli->prepare("SELECT id, username, password, salt
				  FROM members
                                  WHERE email = ? LIMIT 1")) {
        $stmt->bind_param('s', $email);  // Bind "$email" to parameter.
        $stmt->execute();    // Execute the prepared query.
        $stmt->store_result();

        // get variables from result.
        $stmt->bind_result($user_id, $username, $db_password, $salt);
        $stmt->fetch();

        // hash the password with the unique salt.
        $password = hash('sha512', $password . $salt);
        if ($stmt->num_rows == 1) {
            // If the user exists we check if the account is locked
            // from too many login attempts
            if (checkbrute($user_id, $mysqli) == true) {
                // Account is locked
                // Send an email to user saying their account is locked
                return false;
            } else {
                // Check if the password in the database matches
                // the password the user submitted.
                if ($db_password == $password) {
                    // Password is correct!
                    // Get the user-agent string of the user.
                    $user_browser = $_SERVER['HTTP_USER_AGENT'];

                    // XSS protection as we might print this value
                    $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                    $_SESSION['user_id'] = $user_id;

                    // XSS protection as we might print this value
                    $username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);

                    $_SESSION['username'] = $username;
                    $_SESSION['login_string'] = hash('sha512', $password . $user_browser);

                    // Login successful.
                    return true;
                } else {
                    // Password is not correct
                    // We record this attempt in the database
                    $now = time();
                    if (!$mysqli->query("INSERT INTO login_attempts(user_id, time)
                                    VALUES ('$user_id', '$now')")) {
                        header("Location: ../error.php?err=Database error: login_attempts");
                        exit();
                    }

                    return false;
                }
            }
        } else {
            // No user exists.
            return false;
        }
    } else {
        // Could not create a prepared statement
        header("Location: ../error.php?err=Database error: cannot prepare statement");
        exit();
    }
}

function checkbrute($user_id, $mysqli) {
    // Get timestamp of current time
    $now = time();

    // All login attempts are counted from the past 2 hours.
    $valid_attempts = $now - (2 * 60 * 60);

    if ($stmt = $mysqli->prepare("SELECT time
                                  FROM login_attempts
                                  WHERE user_id = ? AND time > '$valid_attempts'")) {
        $stmt->bind_param('i', $user_id);

        // Execute the prepared query.
        $stmt->execute();
        $stmt->store_result();

        // If there have been more than 5 failed logins
        if ($stmt->num_rows > 5) {
            return true;
        } else {
            return false;
        }
    } else {
        // Could not create a prepared statement
        header("Location: ../error.php?err=Database error: cannot prepare statement");
        exit();
    }
}

function login_check($mysqli) {
    // Check if all session variables are set
    if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
        $user_id = $_SESSION['user_id'];
        $login_string = $_SESSION['login_string'];
        $username = $_SESSION['username'];

        // Get the user-agent string of the user.
        $user_browser = $_SERVER['HTTP_USER_AGENT'];

        if ($stmt = $mysqli->prepare("SELECT password
				      FROM members
				      WHERE id = ? LIMIT 1")) {
            // Bind "$user_id" to parameter.
            $stmt->bind_param('i', $user_id);
            $stmt->execute();   // Execute the prepared query.
            $stmt->store_result();

            if ($stmt->num_rows == 1) {
                // If the user exists get variables from result.
                $stmt->bind_result($password);
                $stmt->fetch();
                $login_check = hash('sha512', $password . $user_browser);

                if ($login_check == $login_string) {
                    // Logged In!!!!
                    return true;
                } else {
                    // Not logged in
                    return false;
                }
            } else {
                // Not logged in
                return false;
            }
        } else {
            // Could not prepare statement
            header("Location: ../error.php?err=Database error: cannot prepare statement");
            exit();
        }
    } else {
        // Not logged in
        return false;
    }
}

function esc_url($url) {

    if ('' == $url) {
        return $url;
    }

    $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);

    $strip = array('%0d', '%0a', '%0D', '%0A');
    $url = (string) $url;

    $count = 1;
    while ($count) {
        $url = str_replace($strip, '', $url, $count);
    }

    $url = str_replace(';//', '://', $url);

    $url = htmlentities($url);

    $url = str_replace('&', '&', $url);
    $url = str_replace("'", ''', $url);

    if ($url[0] !== '/') {
        // We're only interested in relative links from $_SERVER['PHP_SELF']
        return '';
    } else {
        return $url;
    }
}

once I fix security issues I will upload my project to github. Im doing this as an open source property management app.

Array[] or array() or wha?

$
0
0

I dont understand arrays in PHP and its necessary to finally fess up and ask for help.

It seems so trivial,, but I've spent Whole DAYS trying to make sense of this.  (I came from assemble language programming).

 

I am receiving UDP packets of a known size. in this case, 4 bytes of binary data.  It gets unpacked ( I dont know why. I cut and pasted this simple parser from an example).   All I want is the array[0] byte.  I'm trying to avoid complex loops and pointers.

// First lets grab a data packet and put our few bytes into the variable $buf

        while(1)  {
           socket_recvfrom($socket, $buf, 16, 0, $from, $port);
           // Easy! but the UDP data in $buf is binary not useful like this.

           //Convert to array of decimal values
           $array = unpack("C*", $buf);    // 'C' tells unpack to make unsigned chars from the binary.

           //Convert decimal values to ASCII characters:

           $chr_array = array();          // wait a second. What is happening here?

           for ($i = 0; $i < count($array); $i++)
             {
              $chr_array[] = chr($array[$i]);    // Whats going on here?  Anyone?
             }

           //  So now I can assume the first byte of this $chr_array[] is my prize, right?

           $mychr = chr_array[0];

           //  Nope.  Looking at $chr_array[0] either reveals a zero or the actual word "Array", depending on how late I've stayed up.

           print_r($array);  //   This is my debugger. It shows SOMETHING is working.

           echo "Received $mychr from remote $address $from and remote port $port" . PHP_EOL;
        }

        socket_close($sock);

Output of above code... assuming the value read was 60 decimal:

Array
(
    [1] => 60
    [2] => 0
    [3] => 0
    [4] => 0
)
Received  0 from remote address nnn.nnn.nnn.nnn and remote port 8888

 

So print_r knows what to do, the last line of my code doesn't.   Any help would be appreciated, as this goes to the heart of my issue of being mystified by how PHP makes and processes arrays.   Its clearly not just a string of numbers.

 

I'm trying to pull ONE printable number from that buffer.  Halp!
 

Get user position in highscore, PDO

$
0
0

Hi! I´m learning PDO at the moment, but struggling a bit.. I want to get a specific users position in my highscore. I would lite the output to be like "your position is 14th of 200. I have tried to search, but i cant get it to work at all :/

Im using an uniqe string as udid, and want to get the rank of that udid based on score...

the connection works but something is wrong in my sql statement..

try {
    $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }

    $udid = $_GET['udid'];
    

    function getUserRanks($udid, $conn) {
    $sql =  "SELECT COUNT(udid) AS `rank` FROM myTable WHERE score > ( SELECT score from myTable WHERE udid = $udid )";

    $stmt = $conn->prepare($sql);
    $stmt->bindValue(1, $udid);
    $stmt->execute();
    $ranks = $stmt->fetchObject();
    return $ranks;
}
    
$ranks = getUserRanks($udid, $conn);    
echo $ranks;
?>

im getting this error:

"Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'myLongUdidStringHere'"

 

Would be very happy if someone could help me with my function or point me in the right way! Thanks a lot!

 

 

Php and Twitter

$
0
0
So i got the basis of this working here
what im trying to do is make it so it searches by not only username(complete) but also a certain hashtag (Duels)
And get it to display any media (photos)  in said tweet
 
 
<?php

require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "831981818408677377-FexWOmvCyaZYWt3TYwmodmx3gMmFIqx",
'oauth_access_token_secret' => "L1vwbaBjsUivKn5NYVmGgve6V1lSP5THvjBk3LiadHyOj",
'consumer_key' => "t31OianjtopHhDEdeBAjWPqj3",
'consumer_secret' => "zFZpwrMl31BShY6CluYapaZl0K1CQPpsagBjVCMkTs2GtWHhRm"
);
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";

$requestMethod = "GET";
$getfield = 'screen_name=MCoCTrucos&count=1';
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
if($string["errors"][0]["message"] != "") {echo "<h3>Sorry, there was a             problem.</h3><p>Twitter returned the following error message:</p><p>     <em>".$string[errors][0]["message"]."</em></p>";exit();}
foreach($string as $items)
{
    echo "Tweeted by: ". $items['user']['name']."<br />";
    echo "Screen name: ". $items['user']['screen_name']."<br />";
    echo "Tweet: ". $items['text']."<br />";
    echo "Time and Date of Tweet: ".$items['created_at']."<br />";
    echo "Tweet ID: ".$items['id_str']."<br />";
    echo "Followers: ". $items['user']['followers_count']."<br /><hr />";
}
{
echo $url;}
?>

 

Viewing all 13200 articles
Browse latest View live