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

How to Program html form

$
0
0

I’m working on building a web (html) form for a vehicle maintained app.

I think most of it will be pretty straight forward but the first problem is building the dropdown list for Make & Model. I have found some info on doing this with javascript but I’m wondering if there is a way to do this with PHP. Basically I need to make a dropdown list of Automobile brands / makes i.e. Ford, Chevy, Dodge, etc. Next I need a second dropdown list of models. The models need to be dependent on the Make selected in the first, “Make” dropdown.  So if Ford is selected on the “Make” dropdown then the options shown in the “Model” dropdown will be appropriately, Mustang, Taurus, Focus, F50, etc.

The Javascript I’ve found looks like this…

function populate(s1,s2){
s2.innerHTML = "";
if(s1.value == "Chevy"){
  var optionArray = ["|","camaro|Camaro","corvette|Corvette","impala|Impala"];
} else if(s1.value == "Dodge"){
  var optionArray = ["|","avenger|Avenger","challenger|Challenger","charger|Charger"];
} else if(s1.value == "Ford"){
  var optionArray = ["|","mustang|Mustang","shelby|Shelby"];
}
for(var option in optionArray){
  var pair = optionArray[option].split("|");
  var newOption = document.createElement("option");
  newOption.value = pair[0];
  newOption.innerHTML = pair[1];
  s2.options.add(newOption);
}
}
</head>
<body onload="process()">
<h2>Choose Your Car</h2>
<hr />
Choose Car Make:
<select id="slct1" name="slct1" onchange="populate(this.id,'slct2')">
  <option value=""></option>
  <option value="Chevy">Chevy</option>
  <option value="Dodge">Dodge</option>
  <option value="Ford">Ford</option>
</select>
<hr />
Choose Car Model:
<select id="slct2" name="slct2"></select>
<hr />

</body>
</html>

This code does in fact work though I’m not actually seeing how to capture and use the selected values from the second list. Actually that’s why I’m looking to see if there is a PHP approach to this. This code kind of loses me at the end where its creating newOptions and where it’s storing the selected values.


Relinquishing memory in WHILE loop

$
0
0

I get the following error:  PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 4096 bytes)

 

The script is being run on the CLI.  I will be inserting the data in another database it the while loop and it is a one time task application, and I don't care about performance.  Typical count values are less than 10.

 

How can I relinquish memory to prevent this.

 

Thanks

$stmt=$pdoTemp->query('SELECT timestamp, GROUP_CONCAT(measurement) measurement, GROUP_CONCAT(field) field, GROUP_CONCAT(value) value, COUNT(value) count FROM allpoints GROUP BY timestamp');
while($rs=$stmt->fetch()) {
    $measurements=explode(',',$rs->measurement);
    $field=explode(',',$rs->field);
    $value=explode(',',$rs->value);
    syslog(LOG_INFO,count($measurements).' '.count($field).' '.count($value).' '.$rs->count);
}

 

REMOVE MIME VERSION FROM MAIL HEADER

$
0
0

How to remove MIME VERSION from header of mail sent from my website. my code goes as below

$headers = 'From: ' . strip_tags($_POST['Name']) .''; 
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\n";
 
IN HEADER OF MY MAIL IT LOOKS LIKE THIS
 
PrashanthMIME-Version: <1.0@p3plcpnl0914.prod.phx3.secureserver.net>
 
Please suggest me 

If statement displays for most, but not others

$
0
0

I've got some code that works well until I hit Sept listing.

$sql = "SELECT * FROM LPV_boatSchedule ORDER BY syear, smonth, sday";
$result = $conn->query($sql);

if ($result->num_rows > 0) {

     // output data of each row
     while($row = $result->fetch_assoc()) {
$IDENT=$row['ID'];
$SDAY=$row['sday'];
$SYEAR=$row['syear'];
$STIME=$row['stime'];
$SNAME=$row['sname'];

	echo "
	  <tr valign\"top\" bgcolor=\"#FFD2A6\">
	   <td width=\"18%\"><font face=\"Verdana, Arial, Helvetica, sans-serif\" size=2>";
	    if ($row['smonth'] == 01){echo "January";}
	    if ($row['smonth'] == 02){echo "February";}
            if ($row['smonth'] == 03){echo "March";}
	    if ($row['smonth'] == 04){echo "April";}
	    if ($row['smonth'] == 05){echo "May";}
	    if ($row['smonth'] == 06){echo "June";}
	    if ($row['smonth'] == 07){echo "July";}
	    if ($row['smonth'] == 08){echo "August";}
	    if ($row['smonth'] == 09){echo "September";}
	    if ($row['smonth'] == 10){echo "October";}
	    if ($row['smonth'] == 11){echo "November";}
	    if ($row['smonth'] == 12){echo "December";}
	   echo  " $SDAY, $SYEAR</font></td>

Displays all months with their names EXCEPT August & September. Data is correct in the database. This has confounded me for days. Any suggestions as to the cause?

Is there security flaw in this design?

$
0
0

I apologize if it's the wrong section, I don't  know which other section  this question would belong in and it is the most popular section on the forum. 

 

Say I have a site where users are can purchase "packages" and to do so, they are sending payments directly to the company using a payment processor. The company tracks all the payments in the back-end. The users are also able to see their earnings, balance and withdrawals. 

 

Normally a user can make a withdrawal request and the company will send that user his earning balance.  After the user receives his earnings in his bank account, he can go back to the site and purchase a new package.  

 

That's all great. But what if I want to give an option to the users where they can use the earnings in their account on the site to purchase a new package, instead of going through a payment processor?  

For e.g. I have $100 as my earning balance in my site's account. And the package I want to purchase is $50. I can simply purchase that package using the $100 I have in my account, instead of making a withdrawal request and wait for the $100 to show up in my bank account and then I go back to the site and purchase that package using a payment processor, as I did originally.

 

I am wondering, if I give users that option, do I need to worry about anything security wise? Is that a wise option to give or should I just stick to payment processor for all user payments?

 

*note I am not asking how to code it. 

Why Did Session Object Destruction Failed ?

$
0
0

Hi All,
A few weeks ago, as part of a logout process, I implemented Jacques1's "Terminating the session correctly" procedure (https://forums.phpfreaks.com/topic/287744-secure-login-strongest-session-ids-and-secure-site-navigation/).
Anytime I used it, it worked perfectly. But today I once got the warning "Session object destruction failed in .... on line XX", "XX" being the line for "session_destroy();".
Since then, I tried to reproduce the error, but the logout process works again as expected.
1. Any idea of the reason for this "single" failure ?
2. Would inserting "session_regenerate_id();" before "session_destroy();" really be a solution, as suggested here?
Thanks !

Is there something fundamentally wrong with PHP?

$
0
0

Honestly I’ve hit this wall more times than I can count. It typically turns out to be something seemingly arbitrary like single or double quotes and only maters sometimes and sometimes not.

OK enough with the ranting. Here is the code that is making me pull my hair out…

It’s a PDO connection string that I’m getting from a Youtube video.

$host = "127.0.0.1";
$user = "root";
$pass = "r00t";
$db = "cars";
try{
conn = new PDO ("mysql:host=$host;dbname=$db", "$user", "$pass");
conn -> setAttrabute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
echo "Oh happy day we have connected to our database";
} Catch (PDOException $e) {
die("Well, that didn't work at all");
}

It’s giving me this error…

Parse error: syntax error, unexpected '=' in C:\Apache24\htdocs\PDO\conn.php on line 10

Line 10 is the line with the new PDO.

 

I’ve been staring at the example code and comparing it to my code till my eyes are about to cross and I can’t find what it is that’s causing the problem.

I’ve tried it with double quotes as well as single quotes. No help. I only say that because it’s been an issue on other occasions

php code not executing from html page

$
0
0

I am trying to run the following php code in the attached file.  I am attempting to connect to a mssql server to run a query. I receive no error messages but the query dies not work. There is another problem, if I include a line such as:

 

 

 

if( $conn === false") <p>no connection<p>;   all code following the <p> is treated as text. If I omit the <p> nothing is echoed.

 

 

Attached Files


How to Update user balance automatically?

$
0
0

i am creating a investment type website. where user deposit money and i will provide them 10 % profit. my question is.

 

How i can update user balance automatically after 24 hours of deposit ?

Check data / Write Data to a text file

$
0
0

Sorry guys, I'm just learning, i'm sure this is simple....

My script is basically, submit your email address, write the email address to a text file... simple!  I want to check the email address submitted against the text file and if the email address is already located in the text file... display a message "already added"... Here is what I have so far... very simple....

<?php
if(isset($_POST['submit']))
{
    $email = $_POST['email'] . PHP_EOL;
    $file = fopen("emails.txt","a+");
    fwrite($file,$email);
    fclose($file);
    print_r(error_get_last());
}
?>


<form action= "" method="post" name="form">
<input type="text" name="email">
<br>
<br>
<input type="submit" name="submit" value="submit"><br>
</form>

any thoughts on how to make this happen?

Both fields update automatically?

$
0
0

Hi everyone! In my Ticket _form.php. When I create ticket it gets the current time and fills in the time_start field automatically, in order to fill in the field time_end I need to update the ticket which also gets the current time when you update it. My problem is when I update it the time_start also updates and now they have the same value which supposed to be different.

 

I have this in my form:

<?= $form->field($model, 'time_start')->textInput(['readOnly' => true]) ?>


<?= $form->field($model, 'time_end')->textInput(['readOnly' => true]) ?>

Which automatically gets the current time of the system

 

In my TicketController.php

public function actionCreate()
{
$model = new Ticket();

if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
$model->time_start = date('y-m-d h:i:s');
return $this->render('create', [
'model' => $model,
]);
}
}

/**
* Updates an existing Ticket model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);

if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
$model->time_end = date('y-m-d h:i:s');
return $this->render('update', [
'model' => $model,
]);

}
}

PHP doesn't output error from mysql query for non-existent rows for autocomplete

$
0
0
I have a form that currently is able to auto complete base on user input, it queries the MySQL database and successfully lists all possible matches in the table and give suggestions. Now I want to handle rows that do not exist (when user enters a name that does not exist in the table). I am having trouble to get my PHP file to echo the error.  
 
Does anyone know why? Is it cause i am using GET?
 
 
Here is what I have so far:
 
search.php

    <?php
    //database configuration
    $host = 'user';
    $username = 'user';
    $password = 'pwd';
    $name = 'name';
    
     //connect with the database
    $dbConnection = new mysqli($host,$username,$password,$name);
    


    if(isset($_GET['term'])){
                //get search term
        $searchTerm = '%'.$_GET['term'].'%';


        //get matched data from skills table
        if($query = $dbConnection->prepare("SELECT * FROM nametbl WHERE name LIKE ? ORDER BY name ASC")) {


            $query->bind_param("s", $searchTerm);
            $query->execute();
            $result = $query->get_result();


            //$row_cnt = $result->num_rows;
            //echo $row_cnt;
            if($result -> num_rows){
                while ($row = $result->fetch_assoc()) {
                    $data[] = $row['name'];
                }


                //return json data
                echo json_encode($data);
                mysqli_close($dbConnection);
            }
            else { echo '<pre>' . "there are no rows." . '</pre>'; }
        }
        else {
            echo '<pre>' . "something went wrong when trying to connect to the database." . '</pre>';
        }
       
          
    }
    ?>
main.php
 
  
  <div id="gatewayInput">
    <form method="post">
          <input type="text" id="name" name="name" placeholder="Name..."><br><br>
          <?php 
            include("search.php"); 
          ?>    
    </div>


    ...
    ...
    ...


    <script src ="../../../jqueryDir/jquery-3.2.1.min.js"></script>
    <script src ="../../../jqueryDir/jquery-ui.min.js"></script>
    <script type="text/javascript">


    //auto search function
    $(function() {
          $( "#name" ).autocomplete({
              source: 'search.php'
          });
    });

Parsing JSON data and inserting to MySQL

$
0
0

Hey, so basically i want to parse a JSON file in PHP and insert the data into specific tables/columns. At the moment i have a working script but requires me to modify the JSON largely until it works. Which might be a pain because the JSON data I'm collecting can vary in size having more data rows. The JSON file is structured differently to most i have seen , maybe because its output data from sensor units. I want to insert the data and the serial number into the data table, and have an error_log table where i can store the serial number and error messages as strings. 

 

JSON File -  https://puu.sh/xtmzy/15585e6ae8.json

 

PHP :

<?php
    //connect to mysql db
  $myConnection= mysqli_connect("localhost","root","******", "ii") or die ("could not connect to mysql");

    //read the json file contents
    $jsondata = file_get_contents('test.json');

    //convert json object to php associative array
    $data = json_decode($jsondata, true);


    $id = $data['device']['sn'];
     $ts = $data['data']['$ts'];
    $RH = $data['data']['RH'];
  $AT = $data['data']['AT'];
    $MINVi = $data['data']['MINVi'];
    $PTi = $data['data']['PTi'];
    $SDB = $data['data']['SDB'];
    $LWS = $data['data']['LWS'];
    $WSAV = $data['data']['WSAV'];
    $WSMX = $data['data']['WSMX'];
    $WSMN = $data['data']['WSMN'];
    $PR_TOT = $data['data']['PR_TOT'];
    $RAIN = $data['data']['RAIN'];
    $FDI = $data['data']['FDI'];
    $DT = $data['data']['DT'];
    $LAT = $data['data']['LAT'];
    $LON = $data['data']['LON'];
     $WD = $data['data']['WD'];
    $P1 = $data['data']['P1'];
    $AVGCi = $data['data']['AVGCi'];



    //insert into mysql table
    $sql = "INSERT INTO test(sn, date, RH, AT, MINVi, PTi, SDB, LWS, WSAV, WSMX, WSMN, PR_TOT, RAIN, FDI, DT, LAT, LON, WD, P1, AVGCi)
    VALUES('$id', '$ts', '$RH','$AT', '$MINVi', '$PTi', '$SDB', '$LWS', '$WSAV', '$WSMX', '$WSMN', '$PR_TOT', '$RAIN', '$FDI', '$DT', '$LAT', '$LON', '$WD', '$P1', '$AVGCi')";


 $query=mysqli_query($myConnection, $sql) or die(mysqli_error($myConnection));
?>

MySQL Tables:

 

Data Table

 

afc5c35cd7.png

 

        Error_Log Table

 

bba127d9c7.png

 

Any help would be greatly appreciated!

 

(P.S After I have the general gist of things I'm planning on incorporating PDO)

Discounts! 2017 best makeup products

$
0
0
Discounts! beauty products best

progect12.jpg
Products which fall under this return policy can be returned domestically, as long as they are unused and in the original packaging. No questions asked!
If a product that falls under this guarantee is found to be counterfeit, you will get a full refund (shipping costs included).

buy.png

READ MORE
Best selling vestidos 2016 elegant lace patchwork solid sleeveless a-line fashion dress sexy slim party dresses vestido de festa ( 31.99 $)
Small view crossbody bag wchain ( 508.20 $) Jil Sander
Cheap 8a grade brazilian glueless silk top full lace wigs ponytail natural hairline human hair full lace wigs for black women ( 109.67 $)
Polkadot Twill Silk Pocket Square ( 45.60 $)
3 pcsset vintage handbags women messenger bags female purse solid shoulder bags office lady casual tote 2015 new top-handle bag ( 45.88 $)
«Kogda holoda nastupayut…»
DHK HOBBY 8384 18 4WD Off-road RC Racing Truck — RTR-331.00 $
Fashion ombre silver grey bodywave synthetic lace front wig glueless long natural blackgray heat resistant hair wigs for women ( 44.99 $)
2016 Neck Fleece Breathable Balaclavas Hat Headgear Winter Skiing Ear Windproof Warm Mask Motorcycle Bicycle Scarf HA120 ( 3.52 $)
1x car styling car auto led t10 194 w5w canbus 10 smd 5630 led light bulb ( 0.80 $)
For Samsung Galxy S7 S7 Edge S6 A3 2016 A5 S4 S5 J3 J5 J7 Grand Prime Case Cover Painting Soft TPU Phone Cases coque Fundas ( 2.49 $)
Sorrento low black leather mens sneaker ( 121.32 $) Ylati
Sisjuly Asymmetric Black Coat Stand Collar Long Sleeve Women Overcoat Elegant Single-Breasted Long Sleeve Slim Fall Winter ( 46.00 $)
Thick knit british wool mens beanie hat ( 59.91 $) Paul Smith
2016 New Girls Clothing Sets Dress + Short T shirt 2 Pcs Set Summer Kids Clothes Fashion Girls Clothes Knitted Children Clothing ( 9.48 $)


99bb.png

Can You Have More Than One Delimiter/Combiner In A Function ?

$
0
0
Php Gurus,
 
Is there a way how you could have more than one delimiter in the following functions ?
 
explode
implode
 
Tutorials always shows one. But let us say, we need more than one. In that case, what would you do without coding separately one by one for each delimiter ? If regex then I'd like to see some code samples.
Remember, a code sample would be appreciated by all present & future newbies. :)
 
 
 
Explode
Imagine I want to explode this:
 
'The "quick brown" fox jumps over the \'lazy dog\'.'
 
To this:
 
'
The 
"quick brown"
fox 
jumps 
over 
the 
\'lazy dog\'
.
'
 
As you can see, we need 3 delimiters:
 
Space
"
'
 
Now, imagine I need to implode this:
 
"
The 
'quick brown'
fox 
jumps 
over 
the 
\"lazy dog\"
.
"
 
To this:
 
"The 'quick brown' fox jumps over the \"lazy dog\"."
 
As you can see the combiners are the same in this case like they were in the other case's delimiters.
 
I don't want to be coding 3 separate snippets to use each delimiter/combiner. Hence the question.
Imagine, I got millions of html files and I need to deal with millions of lines of content like the examples shown above (which was just one line each).
 
Ok, I was about to post this now and a thought just crossed my mind. Maybe the delimiters/combiners can be placed in an array and then on each loop the delimiter/combiner can change ? But how do I call the delimiters/combiners from each array key ? Dump the array values to a variable ? Any sample would be appreciated. Saying all this, I will try myself to build 2 snippets from one of the codes from one of my previous threads but don't hold your breath and I prefer your feed-back if it's possible to do things with array like I'm pondering.
 
@requinix,
 
Yes, I am creating my own terminology again: Combiner/Joiner. ;)

A Function Parameter That Takes In A Constant, Can It Always Take In A Variable Unless It Needs A Handle ?

$
0
0

Folks,

 

Q1. A function parameter that takes in a constant, can it always take in a variable, unless it needs a handle ?

 

While going through the Explode function tutorial, I did not come across anything that states the 3rd parameter (explode limit) in the Explode function has to be a string or a constant. Like so:

<?php
 
//Tutorial: http://www.tizag.com/phpT/php-string-explode.php
 
echo "Script 1"; //Using a Constant as 3rd parameter in the Explode function. Using FOR function.
 
$phrase = "Please don't blow me to pieces.";
$words = explode(" ", $phrase);
print_r($words);
 
for($i = 0; $i < count($words); $i++){
echo "Piece $i = $words[$i] <br />";
}
 
$explode_limit = 4;
$words = explode(" ", $phrase, 4);
for($i = 0; $i < count($words); $i++){
echo "Limited Piece $i = $words[$i] <br />";
}
 
print_r ($words);
 
?>

Accessing values from associative php array

$
0
0

I have a php MySQL script which fetches information from MySQL database and stores them in an array with the latter working fine.

Now the issue comes when i want to access those values outside of the foreach loop. When inside, it displays them all but on doing a dump outside, only the last value is displayed.

 

  $db  = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

 if(!empty($_GET['sales_receipt2'])){
 
   
    $sales_rec2 = $_GET['sales_receipt2'];
    $_SESSION['sales_receipt2'] = $sales_rec2;
    
}
        $fetch_onhold_list = mysqli_query($db,"select prod_code as prod_code,
                                                        sales_name as prod_name,
                                                        sales_qty as prod_qty,
                                                        sales_unit_cost as prod_unit_cost from sales_history where
                                            
                                            sales_code='".$_SESSION['sales_receipt2']."'");


    $data_array = array();
    
    while ($salesByCode = mysqli_fetch_assoc($fetch_onhold_list)) {    
        $data_array[]    =    $salesByCode;
    }    
 
    foreach($data_array as $kp=>$pn){
    
        $_SESSION['onhold_cart_items'] = array($data_array[$kp]["prod_code"]=>array('prod_name'=>$data_array[$kp]["prod_name"], 'prod_code'=>$data_array[$kp]["prod_code"], 'prod_qty'=>$data_array[$kp]["prod_qty"], 'prod_unit_cost'=>$data_array[$kp]["prod_unit_cost"]));
    
    }
    
    var_dump($_SESSION['onhold_cart_items']);

 

PHP Zip Extract to client machine

$
0
0

Hi,

 

I am running the PHP server on my laptop. So, far I am able to create a zip file and extract too, but when i extract i gave path to my c:/ folder.The issue is it extracts to the C:/ folder on my laptop where the php server is running and if a user extracts from a different machine I don't think it will extract to the client C:/folder or does it ? or is there any other way to specify the client path ?

 

Also client can use linux system then i cannot use this path. So, I would like to know is there any way to achieve this ?

 

Note: I have multiple CSV files which i have zipped and It is a must that I have to extract and provide the files to the user.

 

Thanks.

how do I exit script if there is no sql results and echo "no Results Found"

$
0
0

I need to check and see if there are any results if so run the script if no results then echo "no Results Found"

<?php
$connect = odbc_connect("removed");
if (!$connect) {
    exit("Connection Failed: " . $connect);
}

$sql      = "


SELECT distinct
	ltrim(rtrim(SO.ompCustomerOrganizationID))as customer
	,ltrim(rtrim(left(cmoName,30))) as name
	,left(ltrim(rtrim(cmoAddressLine2)),30) as address1
	,ltrim(rtrim(cmoCity)) as city
	,ltrim(rtrim(cmoState)) as state
    ,ltrim(rtrim(cmoPostCode)) as postal
	, ltrim(rtrim(REPLACE(REPLACE(REPLACE(cmoPhoneNumber, '(', ''), ')', ''), '-', ''))) as phone

FROM m1_kf.dbo.SalesOrders SO
LEFT JOIN m1_kf.dbo.Organizations ON cmoOrganizationID = SO.ompCustomerOrganizationID
WHERE ompCreatedDate >='06-11-2017' and ompPaymentTermID in ('CN30','CTN30')
and UOMPSCHEDULENUMBER !=1 and ompOrderTotalBase > 1

";

$result = odbc_exec($connect, $sql);

if (!$result) {
    exit("Error in SQL");
} else (
	echo "<table><tr>";
	echo "<th>CustID</th>";
	echo "<th>OrderId</th>";
	echo "<th>Amount</th>";
	echo "<th>TotalAmount</th>";

while ($row = odbc_fetch_array($result)) {

    $cust_num   = $row['customer'];
    $name    = $row['name'];
    $city    = $row['city'];
    $state   = $row['state'];



	echo "<tr><td>$cust_num </td>";
    echo "<td>  $name </td>";
    echo "<td>   $city </td>";
    echo "<td> $state  </td></tr>";

}}

?>

Having trouble with Array value saying "null"?

$
0
0

Hi All,

 

My concept:

i'm trying to select age and salary from my database. i want to get the SUM of salaries of each age group. Then i want to convery it to JSON, so i can display it in a chart.

 

Output:

[{"label":"20","value":"null"},{"label":"30","value":"null"}]

 

 

Thanks in advance.

 

 

Viewing all 13200 articles
Browse latest View live