PHP

118K

Solutions

32K

Contributors

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.

Share tech news, updates, or what's on your mind.

Sign up to Post

i am finding it difficult to get radio button value in php using jquery ajax. every thing work fine if i comment the radio button variable in the php file  below, but if i remove the comment , nothing works. i have been on this for more then a day now. thanks for the help!!!

here is the html and jquery file :
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Form Validation</title>
	<style>
		.error{
			color:red;
		}
		
		.emai{
			border: solid 2px green;
		}
		
		.error2{
			color: green;
		}
		.textBoxError{
			border: solid 2px red;
	       color: red;
		
		}
	</style>
</head>
<body>



<form method="POST" id="form" name="form" action="">
    <label for="email" >Enter your email</label>
    <input id="email" class="emai" name="email">
	<p id="result"></p>
	<label for="email">Enter your first name</label>
	<input id="firstname" name="firstname">
	<label for="address">address</label>
	<input id="address" name="address">
	 Yes: <input type="radio" name="opt" value="yes">
    No: <input type="radio"  name="opt" value="No" checked="checked">
	<p id="result2"></p>
    <button id="submitform">Submit</button>
	<p id="result3"></p>
</form>

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
$( document ).ready(function() {
    $(function(){
        $('#submitform').on('click',function(e){
            e.preventDefault();  // do not allow the default form action
            var 

Open in new window

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE
LVL 4
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

I'm pulling data from a table using PHP.  The data goes into a form with inputs.  The data in the form is good on the page, but when I click the 'submit' button, the only data that's posted is the last record.

I uploaded a test page here...

http://testregister.cenational.org/admin/commitment/test.php

that goes to a page that echos the POST.  It must be something simple I'm missing, so any ideas are appreciated.

Here's the code of test.php

<?php 
	$id_commitment='testCommit';
	$id_event='mo14420';

	//Store registrants into array_registrations
    try {
		$qry_registrants = new PDO("mysql:host=$xxxxx=$xxxxx",$xxxxx,$xxxxx);
	
		$sth = $qry_registrants->prepare("SELECT 
				table1.fm_lname,
				table1.fm_fname,
				table1.id_family_member,
				table2.f_city,
				table2.f_state
			FROM
				table1, table2, table3
			WHERE 
				table2.id_family=table1.id_family AND
				table3.id_family_member=table1.id_family_member AND
				table3.id_event='$id_event' 

				");

			$sth->execute();

			$qry_registrations = null;
				} 
				catch (PDOException $e) {
				print "Error!  Please email steve@cenational.org";
				die();
			}

			/* Fetch all of the remaining rows in the result set */

			$array_registrations = $sth->fetchAll(PDO::FETCH_ASSOC);
?>
<form action="test_code.php" method="post" enctype="application/x-www-form-urlencoded" id="form1">
    <table border="1" align="center">
        <tr>
            <td colspan="3" align="center"><h2>&nbsp;</h2></td>
        

Open in new window

0
Hello, Experts,

I built a PHP script that queries a database and outputs the results in JS/HTML form. If you could review the code below, I need help how to make the result field URL clickable.

Example:

Name: John Doe
URL: http://google.com

When results display for John, he is able to see the result set for his name and click on http://google.com

Let me know if you need further clarification.

<?php
//fetch.php
$connect = stuff
$output = '';
if(isset($_POST["query"]))
{
 $search = mysqli_real_escape_string($connect, $_POST["query"]);
 $query = "
  SELECT * FROM emp_details 
  WHERE dept LIKE '%".$search."%'
  OR fname LIKE '%".$search."%' 
  OR lname LIKE '%".$search."%' 
  OR pkid LIKE '%".$search."%' 
  OR url LIKE '%".$search."%'
 ";
}
else
{
 $query = "
  SELECT * FROM emp_details;
 ";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
 $output .= '
  <div class="table-responsive">
   <table class="table table bordered">
    <tr>
     <th>pkid</th>
     <th>fname</th>
     <th>lname</th>
     <th>department Code</th>
     <th>url</th>
    </tr>
 ';
 while($row = mysqli_fetch_array($result))
 {
  $output .= '
   <tr>
    <td>'.$row["pkid"].'</td>
    <td>'.$row["fname"].'</td>
    <td>'.$row["lname"].'</td>
    <td>'.$row["DEPT"].'</td>
    <td>'.$row["url"].'</td>
   </tr>
  ';
 }
 echo $output;
}
else
{
 echo 'Data Not Found';
}

?>

Open in new window

0
I googled but i was only able to get top n rows or random rows is that possible to fetch it % of rows for every customers .
0
Thank you for looking at my question,

I have a user input form (php) that has some javascript validation which should, if the conditions are met, assign a value to a hidden form element but it isn't working and I can't see why.
	<form name="Form1" action="Forms/Section1.php" method="GET" onSubmit="return jsValidate()">
		<input type="hidden" name="StockItem" />

Open in new window


The javascript validation looks like this
if (z.length == 23){
	if (z.slice(0,2) == "VE" || z.slice(0,2) == "SE"){
		
		//alert("So Far So Good");
		
		document.getElementById("StockItem").value = 1; //Full Build
		alert (document.getElementById("StockItem").value);
	} else {
		errorcount++;
		document.getElementById('VECO').style.color='#FF0000';
	}
} else if (checknum==1){
	
	//alert("So Far So Good");
	
	document.getElementById("StockItem").value = 0; //Component
	alert ("Assembly Stock Item: " + document.getElementById("StockItem").value);
} else {
	errorcount++;
	document.getElementById('VECO').style.color='#FF0000';
}

Open in new window


If either of the conditions are met (z == 23 characters starting VE or SE, or checknum == 1)  then, when it's not commented out, the "So Far So Good" alert appears on the screen but the following
alert(document.getElementById("StockItem").value);

Open in new window

doesn't
and no value is assigned to the StockItem element - as can be seen in the address of the php page the data should pass to
http://xx.xx.xx.xx/ed1/Forms/Section1.php?StockItem=&Meter=1000&ProdnOrder=553456789&SalesOrder=9999&SerialNo=&VECode=VE884S05E0G0T01D0004000

Open in new window


What am I missing?
0
I had this question after viewing Need If Logic Help That Assigns Different Unique Values.

On the earlier question
// simulate your post
$post = array('illness','fruits');

Open in new window

 these questions are selected manually but I need them to be dynamic based on the users form input.

I have read that if a checkbox isn't selected no values are transmitted but it seems I have something miscoded in my code.  

I thought this line for the immune column
// simulate your post
$post = array('illness','difficulty','odor','antibiotics');

Open in new window

would only produce the value of 3 if I checked the illness question.  Instead it gives a value of 7.  3 for illness + 3 for antibiotics and 1 for difficulty.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Count Checks</title>
</head>
<body>
<h1>Count Checks</h1>
<form method="post">
General Health & Vitality<br />
Please check all that apply<br />
Illness More Than Twice A Year:<input type="checkbox" name="illness[]" value=""><br />
Monthly Female Concerns:<input type="checkbox" name="female[]" value=0><br />
Difficulty Digesting Certain Foods:<input type="checkbox" name="difficulty[]" value=""><br />
Body Odor and/or Bad Breath:<input type="checkbox" name="odor[]" value=""><br />
Recent Or Frequent Use Of 

Open in new window

0
I'm trying to be 100% sure that I get responses from AJAX regarding the current state of the process.

I wrote the following as a simulation and its waiting and showing both success and complete at the same time.

$(function() {

	$('#submit').click(function(e){
		e.preventDefault();

		$.ajax({
			
			type: "POST",
			url: "ajaxPost.php",
			data: $("#aiForm").serialize(), // serializes the form's elements.

			success: function(){
				console.log('imStartingNow');
			},

			error: function(jqXHR, textStatus, errorThrown) {
				alert(errorThrown);
			},

			complete: function(){
				alert('im all done!');
			}

		});

	});

});

Open in new window


This all looks fine on the surface.  I am receiving the post variables as expected, however in real life, this post request does some processing that takes awhile so I want to know when it starts and when its done so I made my php script look like this to simulate a wait

<?php 
         sleep(5);
          echo "OK DONE";
?> 

Open in new window


What happens is that NOTHING occurs for the 5 second wait and then both success and complete fire off at the same time.

I was thinking it might be the sleep simulation that is causing the issue, but on my real page where its an actual post with some long processing afterward, it too will hang until done and show both success and complete.  I need some education on the proper way to set up this request where I can separate and identify the success vs the complete.
0
This is my first foray into JSON and I'm trying to develop an autocomplete field with JSON, php and sql.  I've got it working on a single field (employee Name) but would like to add a second field that gets populated by the employee title when the employee name is selected.  

So far, my test page looks like:
<!DOCTYPE html>
<html>
<head>
    <title>Autocomplete Textbox Demo | PHP | jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

    <script type="text/javascript">
        $(function() {
            var availableTags = <?php include('fetchEmpName.php'); ?>;
            $("#empName").autocomplete({
                source: availableTags,
                autoFocus:true
            });
        });
    </script>
</head>
<body>
<label>Department Name</label></br>
<input id="empName" type="text" size="50" />
<input id="empTitle" type="text" size="50" />
</body>
</html>

Open in new window


And the fetchEmpName.php file is like:
<?php
require('i_PDOConnection.php');
$query = "SELECT empFName + ' ' + empLName as [empName], empTitle FROM tbl_CouncilStaff WHERE active = 1 AND display = 1 AND (empFName LIKE '%".$search."%' OR empLName LIKE '%".$search."%') ORDER BY empLName";
$stmt = $dbh->prepare($query);
$stmt->execute();
$data = $stmt->fetchAll();
foreach ($data as $row) {
    $empName[] = $row['empName'];
    $empTitle[] = $row['empTitle'];
}
 $arrData = array($empName,$empTitle);
 echo json_encode( $arrData );
?>

Open in new window


The code is working if I only use the $empName or $empTitle array and encode that ($data = $empTitle or $data=$empName.  

However making an array of both arrays causes the empName box to return two blank lines instead of any names or titles when I type.  I get that, but I don't know what to do about it to access the underlying data and have the names list in text box one and populate the employee title to text box two upon a selection.

As always, thanks in advance for any help offered.
0
I am trying to get the id value in the url via ajax like this but don't know how to get the url parameter (id value in this case) via jquery.

$.ajax({
		url: 'functions/selected-cat.php',
		type: 'GET',
		dataType: 'json',
                data: {}
	})

Open in new window


When I try to console.log() the request I get a console error that says the id is an undefined index.


$safe_url = filter_var($_GET['id'], FILTER_SANITIZE_URL);

Open in new window


I put that into an array and json_encode it so that part is right. Is it not possible to get a url value in this way? Does it have to be done using javascript/jquery as opposed to php?
0
Apache2 quit working when I was messing with the config files and when I purged it and installed it, it quit working.

After I got it working again PHP wasn't working, so I removed it and reinstalled it and it's still not working.

Then I tried to remove PHP and then remove Apache2. I installed Apache2 then installed PHP and it's not working.

From the terminal

Setting up libapache2-mod-php7.1 (7.1.8-2+ubuntu16.04.1+deb.sury.org+4) ...
dpkg: error processing package libapache2-mod-php7.1 (--configure):
 subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
 libapache2-mod-php7.1
E: Sub-process /usr/bin/dpkg returned an error code (1)
0
Free Tool: Port Scanner
LVL 9
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

I have a page that generates this json output
{"address":"1234 East Main Street","city":"Anywhere"}

Open in new window


I created it using this PHP function on an index.php page
$address="1234 East Main Street";
$city="Anywhere";
echo json_encode(array('address'=>$address,'city'=>$city));

Open in new window


I then have the script shown below attached to the top of the index page that includes this ajax script that should be parsing and returning the values in my console.  I only get error messages

$(function() {

    $.ajax({
        url : 'index.php',
        type : 'POST',
        data : {"address":"address","city":"city"},
        dataType : 'json',
        success : function (result) {
           alert(result['address']); // alert box
           console.log(result['city']) // city in console
        },
        error : function () {
           alert("error");
        }
    });
});

Open in new window


Im very new to ajax so I'm hoping im just overlooking something simple but if there is a better way to do it altogether im open to that too. Thanks!
0
I am getting an error that i cannot fix.  I have changed the database to UT8MB4 and have used every script in my arsenal to fix the problem and still get the same error.  Please advise how to fix.

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's 2-Handset Cordless Answering System is packed with features. There's a 50-name' at line 1' in /home/electronics/download.php:347 Stack trace: #0 /home/electronics/download.php(347): PDO->query('UPDATE `Do...') #1 {main} thrown in /home/electronics/download.php on line 347


$query68 = $conn->query('SELECT DISTINCT Sku, Title, DescriptionBottom  FROM `ProductScrape` WHERE Sku IN (SELECT VENDORSKU FROM Download)');



while ($row68 = $query68->fetch(PDO::FETCH_ASSOC))
    {

	

$NewTitle = $row68['Title'];
$NewFullDesc = $row68['DescriptionBottom'];

//$NewFullDesc = w1250_to_utf8($NewFullDesc);
//$NewTitle = w1250_to_utf8($NewTitle);
$NewImage = $row68['Sku']."-0.jpg";
$Sku = $row68['Sku'];

$NewTitle = preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($NewTitle, ENT_COMPAT, 'UTF-8'));
$NewTitle = preg_replace('/[\x00-\x08\x10\x0B\x0C\x0E-\x19\x7F]'.
 '|[\x00-\x7F][\x80-\xBF]+'.
 '|([\xC0\xC1]|[\xF0-\xFF])[\x80-\xBF]*'.
 

Open in new window

0
HI am using stored procedure to convert row value to column header . but while trying to convert it works fine if the column header has less words and it fails if it has more than 5o

BEGIN

SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(questions= ''',
questions,
''', yes_no, NULL)) AS ''',
questions,''''
)
) INTO @sql
FROM tbl_main where task=in_task;
SET @sql = CONCAT('SELECT case_id,audited_by,resolved_by, ', @sql, ' FROM  tbl_main WHERE task IN  (''',in_task,''') and audited_date   between(''',from_date,''') and (''',to_date,''') GROUP BY   case_id,audited_by,resolved_by');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


END

Can anybody assist me to overcome this
0
Hi Experts

Could you point how can I avoid a full table scan on this mysql query?

Acordingly with this query profiler statistics:
img001

SELECT
		dt_output
	,	COALESCE(SUM(assistencias),0) AS assistencias
	,	COALESCE(SUM(services),0) AS services
	,	COALESCE(SUM(connectionsoffered),0) AS connectionsoffered
	,	COALESCE(SUM(acdconnections),0) AS acdconnections
	,	COALESCE(SUM(abnconnections),0) AS abnconnections
	,	COALESCE(SUM(connectionsoffered_fake),0) AS connectionsoffered_fake
	,	COALESCE(SUM(med_wait_time),0) AS med_wait_time
	,	COALESCE(SUM(med_acd_talk_time),0) AS med_acd_talk_time
	,	COALESCE(SUM(percent_serv_lvl_spl),0) AS percent_serv_lvl_spl
	,	COALESCE(SUM(percent_abnconnections),0) AS percent_abnconnections
	FROM
	(
		SELECT
			DATE_FORMAT(Initial_Date, "%Y-%m") AS dt_output
		,	NULL AS assistencias
		,	NULL AS services
		, 	SUM(_receivedconnections) AS connectionsoffered
		,	SUM(_acdconnections) AS acdconnections
		, 	SUM(_abdconnections) AS abnconnections
		,	SUM(_abdconnections + _acdconnections) AS connectionsoffered_fake
		, 	ROUND(SUM(_TMEFormula1)/SUM(_TMEFormula2)) AS med_wait_time
		, 	ROUND(SUM(_TMAFormula1)/SUM(_TMAFormula2)) AS med_acd_talk_time
		, 	ROUND((SUM(_SLAFormula1)/SUM(_SLAFormula2)*100),1) AS percent_serv_lvl_spl
		,	ROUND((SUM(_abdconnections)/SUM(_abdconnections + _acdconnections)*100),1) AS percent_abnconnections
		FROM project_reports.yearly_table
			 AS `csd`
		INNER JOIN `project_reports`.`list_skill` AS

Open in new window

0
There is  a form with "post" that in the action it says:

(I run it with get and the line reads http://domain.com/test/?(variables))

http://domain.com/test

It doesn't specify the script that takes the form data to process and returns a result

I dont know in what language it is programmed in

I tried index.php (domain.com/test/index.php

the same for index.asp, default.php and default.asp but those scripts dont exist in the server.

I use chrome developers tools but it only returns  (index) which could be anything

Any ideas?
0
Hi Experts


Could you point the better manner on extend a timeout in PHP?

My sessions timing out too quickly.

Thanks in advance.
0
can some please show me how to use mysql database as data source for nv.d3 chart library. i want to use data from mysql database as values for the chart. please see nv.d3 sample chart, but the values are not from database.
nv.addGraph(function() {
  var chart = nv.models.discreteBarChart()
      .x(function(d) { return d.label })    //Specify the data accessors.
      .y(function(d) { return d.value })
      .staggerLabels(true)    //Too many bars and not enough room? Try staggering labels.
      .tooltips(false)        //Don't show tooltips
      .showValues(true)       //...instead, show the bar value right on top of each bar.
      .transitionDuration(350)
      ;

  d3.select('#chart svg')
      .datum(exampleData())
      .call(chart);

  nv.utils.windowResize(chart.update);

  return chart;
});

//Each bar represents a single discrete quantity.
function exampleData() {
 return  [ 
    {
      key: "Cumulative Return",
      values: [
        { 
          "label" : "A Label" ,
          "value" : -29.765957771107
        } , 
        { 
          "label" : "B Label" , 
          "value" : 0
        } , 
        { 
          "label" : "C Label" , 
          "value" : 32.807804682612
        } , 
        { 
          "label" : "D Label" , 
          "value" : 196.45946739256
        } , 
        { 
          "label" : "E Label" ,
          "value" : 0.19434030906893
        } , 
        { 
          "label" : "F Label" , 
          "value" : -98.079782601442
        }

Open in new window

0
I am successfully using a basic mvc pattern for static pages but am now trying to use it for dynamic page. I want the url to for now be mysite.com/products/4    or whatever the product id is. my php page is called product-detail.php


if(isset($_GET['page']) && $_GET['page'] == "product-detail") {
		
		include("views/header.php");
		include("views/product-detail.php");
		include("views/footer.php");
		
	}

Open in new window


This is the link to the product
<a href="products/{$id}">{$product_name}</a>

Open in new window


The .htaccess
RewriteRule ^products/([0-9]+)$ ?page=product-detail.php?id=$1 [NC,L]

Open in new window



To expand, my static pages route like this:

if(isset($_GET['page']) && $_GET['page'] == "about") {
    include ("views/header.php");
    include ("views/about.php");
    include ("views/footer.php");

} else {

    if(isset($_GET['page']) && $_GET['page'] == "contact-us") {

        include ("views/header.php");
        include ("views/contact-us.php");
        include ("views/footer.php");

    }

Open in new window


And the navigation looks like:

<li class="">
 <a href="about-us">About Us</a>
</li>

Open in new window


The .htaccess:

RewriteRule ^about-us$ ?page=about [NC,L]

Open in new window


I am trying to achieve the same thing but with products showing from the database which all have unique id's. If I click on a product, instead of going to product-detail.php?id=4

I would want it to go to mysite.com/products/4

I don't know which part is wrong, the rewrite rule or the controller part. (or both)
0
Is it possible to block a state via htacess?  Hypothetical, I am not allowed to business in CA so I want to block the state of CA?
Are there instructions on how to block all countries except the USA via htaccess?
0
What does it mean to be "Always On"?
LVL 4
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

I am working on an AJAX application and I had the basic parts working.  However when I started thourough testing I started receiving HTTP/1.1 414 Request-URI Too Long.  I tried to convert it to use POST instead of GET but it is not working.    I have tried looking for examples online but I have not found one that makes it clear to me

The attached code works if I use:
 if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
         handleupdaterec();
     }
var myParams = "updaterec.php?acctNBR=" + tableID + "&recID=" + recID + "&myXML=" + myXML;
xmlHttp.open("get", myParams , true);
xmlHttp.send(null)


but not if I use:
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        handleupdaterec();
    }
var myParams="acctNBR="+myAcct+"redID="+recID+"&myXML="+myXML2 ;
xmlHttp.open("post", 'trans.txt' , true);    
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send(myParams);


In all the examples I saw 'trans.txt' was a url or filename.   What does this refer to?   I tried a non-existent file, an empty file and the calling web page.  Do I need to set special permissions on the file?  

I am receiving no error messages in the debugger or in the apache2/error_log.  I walk through the debugger line by line i see it executing xmlHttp.open,  xmlHttp.setRequestHeader and xmlHttp.send(myParams); but nothing happens.   one of the first lines in updaterec.php writes a record to the error log to let me know it got…
0
I have a select menu which values are populated via jquery/ajax/php. They are category names. I also have a single text field where users can add new categories on the same page. This is also done via jquery/ajax/php. When the user adds a new category, I want it to then show that newly added category on the dropdown menu without the user having to refresh the page.

This is the current php code I have which is called via ajax. I get the last inserted id and just to test it, I put it in the success message and alert that via jquery after inserting. This works fine.

// validation here. $message indicates that there was an error and validation fires

if($message) {
		
		$response['success'] = false;
		$response['message'] = $message;
		
	} else {
		
		$stmt = $link->prepare("INSERT INTO `product_cat` (`cat_name`) VALUES (?)");
		$stmt->bind_param("s", $_POST['category']);
		$stmt->execute();
		$stmt->close();
		
		$last_id = $link->insert_id;
		
		$stmt = $link->prepare("SELECT `cat_name` FROM `product_cat` WHERE `id` = ?");
		$stmt->bind_param("i", $last_id);
		$stmt->execute();
		$result = $stmt->get_result();
		if($result) {
			$row = $result->fetch_assoc();
			$cat_name = $row['cat_name'];
			
		}
		
		$response['success'] = true;
		$response['message'] = $cat_name;
		
		
	}
	
	echo json_encode($response);

Open in new window



The jQuery/ajax

function add_category() {

    $("#cat_error").hide();

    $("#add_category").on("click", function() {

        var 

Open in new window

0
php date() returns the server time
even if the timezone is changed through script  the date() function returns the time set
database being on another server have timestamps stored as per gmt
m trying to extract data between a particular interval on the basis of epoch timestamp
0
I'm having a very difficult time comparing / subtracting dates using PHP v5.5.33.  

I've been referencing this example .. which works fine as-is:

<?php
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>

Open in new window


However .. I'm getting errors when attempting to compare dates that are retrieved from a MySQL database .. where the dates are in the format of "2016-05-04 10:20:42".  Here's what I've been experimenting with:

<?php
$reg_temp = strtotime($row->registered);        
$registration_date = date("Y-m-d", $reg_temp); 
$exp_temp = strtotime($row->expires);        
$expiration_date = date("y-m-d", $exp_temp);    
$diff=date_diff($registration_date,$expiration_date);
echo $diff->format("%R%a days");
?>

Open in new window


The error message that I'm getting is as follows:

PHP Fatal error:  Call to a member function format() on boolean ...

I'm just trying to correctly re-format these 2 dates so they can be compared and return a number of days value ... similar to the working example (which instead uses the "date_create()" method).  How do I accomplish this?

Thanks,
- Yvan
0
Hi Experts

Could you point how to obtain programatically  by via PHP these dates?

first day of year
last day of current month

In numerical way (f.e.)  20170101  /  20170831

Thanks in advance
0
Hello guys,

I have a website in PHP I want when my client will closed browser I get this event and close "SESSION" on PHP, and call function for do update in mysql where I will change status of client.

How do that this?
0

PHP

118K

Solutions

32K

Contributors

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.