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 want to check for the presence of a substring within a string using a PHP variable. Something like this:

<?php 

$something="A string that contains the word script";

?>

<!DOCTYPE html>
<html lang="en">
<head>
<title>JQuery Text Exchange</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>

<script>

var testStr = <?php echo $something;?>

if ($(testStr:contains("check")).length > 0)
{
	 alert("String Found");
}
	

</script>
</body>
</html>

Open in new window


So, tell me if the word "check" shows up in the PHP variable $something. How can I do this?
0
Technology Partners: We Want Your Opinion!
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

So I've got a function in PHP. If no records are found as a result of a SELECT statement, then right now, the syntax I'm working on has this:

echo "We were unable to match the info you provided.";

I want to instead, load some text via JQuery into a div. Right now, I've got this:

echo "<script>$('#header_text').html('We were unable to match the information you provided.\n Please try again.');</script>";

It's not working. I think I know why in that what I've got currently is something that's put in motion by an action of some kind. A click, a button - something. Without that "event," I don't have anything.

Let me know if that's accurate and, if you would, also tell me how I can use JQuery to load some new text into the <div> rather than simply echoing a message.

Thanks!
0
Here's what the programmer prior to me has in place:

$out .= <<<OUT
                              <script>
                              var text=$('#header_text').text();
                              $('#header_text').text('Click on the "Yes" button if the name listed below is you. Otherwise, click "No."');            
                              
                              $('#verifyUseryes').click(function(){
                                    window.location='$portalLink';
                              });
                              $('#verifyUserno').click(function(){
                                    $('#header_text').text('Please enter your personal information and click on "submit!"');            
                                    $('#step_1').show();
                                    $('#window').html('');
                              });
                              </script>
OUT;

They used HEREDOC, which is fine, but the challenge I'm running into is that when I try to do this:

$('#header_text').text('Click on the "Yes" button if the name listed below is you.\nOtherwise, click "No."');

or this...

$('#header_text').text('Click on the "Yes" button if the name listed below is you. <br>Otherwise, click "No."');

I get the actual characters ("\n" or "<br>") rather than the actual line break.

I want to maintain the HEREDOC dynamic, at least for now. Any suggestions on how to get that line break happening?
0
See my php code below. You will see the two functions are virtually the same, but select different field names. I have a few more functions to add that are similar too. Instead of duplicating the code each time can I create a foreach loop to dynamically create each function? i.e. A variable of the function name and field names? If so can you please show me an example using my code?

public static function find_all_media_type_compats() {
		return self::find_by_sql("SELECT DISTINCT media_type_compat FROM ".self::$table_name." WHERE type = 'Media' AND media_type_compat != '' ORDER BY media_type_compat ASC");
  }
	
  public static function find_all_media_applications() {
		return self::find_by_sql("SELECT DISTINCT media_applications FROM ".self::$table_name." WHERE type = 'Media' AND media_applications != '' ORDER BY media_applications ASC");
  }

Open in new window

0
A MySQL  database has three  levels of subtable.
project->snapshot->layer  

Need to duplicate a project record along with all subrecords from snapshot and layer
a project can have many snapshots, a snapshot can have many layers

Would prefer to do this in PHP but stored procedure is OK
All comments and advice welcome and appreciated
0
Hi Experts,

I cannot find this quickly, but can anyone give me an example of file upload form, with I guess PHP on where to save the file?

Thank you
0
On my php page I have a select statement.  I copied the SQL to SQL Server to test and modify it.

The results are returning in SQL Server and also on the php without the modification.

I added the below to the sql select in PHP (after testing it works in SQL Server).

Original Code
CONVERT(VARCHAR(10), [I].[shipDate], 101),

Open in new window

Modified Code
CASE RIGHT((
		SELECT TOP 1 INV.Name AS InvoiceName 
		FROM SO_Shipment SHIP  
		INNER JOIN SO_Invoice INV ON INV.id_invoice = SHIP.id_invoice
		INNER JOIN SO_Items ITEMS ON ITEMS.id_order = SO.id_order
								  AND ITEMS.id_shipment = SHIP.id_shipment
		WHERE 
		SO.id_order = SO.id_order
		AND RIGHT (INV.Name, 1) = 'B'
		AND ITEMS.Name1 = I.Name1 
		), 1)
	WHEN 'B' THEN
		CONVERT(VARCHAR(10), [I].[shipDate], 101)
	ELSE
		CASE RIGHT([SO].[name], 1)
			WHEN 'B' THEN
				'1/1/3000'
			ELSE
				CONVERT(VARCHAR(10), [I].[shipDate], 101)
			END
	END AS [shipDate]
,

Open in new window

The above SQL returns the desired results.  However, when added to the php page and running I receive my headers but no values.
I modified the Select Case to
'3/1/2017' AS shipDate,

Open in new window

and it returns data in PHP.

I also attempted to create a Stored Procedure in SQL SERVER with the SQL code including the CASE Statement.  It works in SQL Server.

I added the below code to PHP
	$itemsTable = ms_select_table("EXEC [MyDbase].[dbo].[Get_Items];");

Open in new window

Below code shows "0" results with the SQL and SPROC.
	ECHO(COUNT($itemsTable)." unique results.<br />");

Open in new window

Why is the Select Case NOT working in PHP?  How do I get this to work?
0
I need to fetch the results in column but my results are in row how can i modify my code ???
<?php
 $dbhost = "localhost";
 $dbuser = "GCSADMIN";
 $dbpass = "123456";
 $db = "employee_db";

    $conn = mysql_connect($dbhost, $dbuser, $dbpass,$db);

   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }

   $sql = "SELECT EmployeeID,FirstName,MiddleName,LastName,FatherName,SpouseName,MotherName,DOB,Age,BloodGroup,MaritalStatus,Gender,ContactNumber,EmergencyContactNumber,Email,DateOfJoiningatGemini,TotalYearOfExperience,ReleventYearOfExperience,PANnumber,PassportNumber,UANnumber,AadharNumber,PresentAddress,PermanentAddress
      FROM employee_information WHERE EmployeeID = 'GI1005'";

   mysql_select_db('employee_db');
   $retval = mysql_query( $sql, $conn );
   if(! $retval ) {
      die('Could not get data: ' . mysql_error());
   }
   
   echo "<table border='5px solid block', width='50%' padding='12px 20px' >";
?>
<tr>
    <th>First Name</th>
    <th>Middle Name</th> 
    <th>Last Name</th>
    <th>Father Name </th>
   </tr>
<?php

   while($row = mysql_fetch_assoc($retval, MYSQL_ASSOC)){

   	 ?>

      <tr>
            <td><?php echo $row['FirstName']; ?></td> 
            <td><?php echo $row['MiddleName']; ?></td> 
            <td><?php echo $row['LastName']; ?></td>
            <td><?php echo $row['FatherName']; ?></td> 
      </tr>

        <?php 
        }
         echo "</table></br></br>";  

Open in new window

Untitled.png
0
I'm trying to figure out what the correct way is to modify a date format before inserting when using Laravel 5.4.

I have:
public function store(){

        $trip = new Trip;
        $trip->tripName = request('tripName');
        $trip->departing = request('departing');
        $trip->returning = request('returning');
        $trip->save();

        return $trip;

        //return redirect('/home');
    }

Open in new window


My database mySQL field in datetime, but the date that's passed in the variable is '07/17/2017 3:20 PM'.  How/where would I update that before insertion?
0
I am creating a small site and using procedural PHP for my controller:

if(isset($_GET['page']) == 'about-us') {

    include("views/about-us.php");

}

Open in new window


My URL then looks like:

http://example.com/?page=about-us

I just want that to read:

http://example.com/about-us

but I am not sure how to do this. When not using this approach, this worked for such simple tasks but not in this instance.

I tried something like this which would have .html on the end but would look like a better url .This however doesn't seem to work

RewriteEngine On
RewriteRule ^([^-]*)\.html$ /?page=$1 [L]

Open in new window

0
Creating Instructional Tutorials  
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

The following data is returned from my laravel coded controller:

data object
[{"id":1,"name":"View","createdDate":"2017-07-12 14:54:05","lastUpdate":"2017-11-07 13:52:27"},{"id":2,"name":"Read","createdDate":"2017-07-12 14:54:05","lastUpdate":"2017-11-07 13:52:27"},{"id":3,"name":"Write","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27"},{"id":4,"name":"Update","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27"}]

Open in new window


try object
[{"id":1,"name":"Dashboard","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","permission":[{"id":1,"name":"View","createdDate":"2017-07-12 14:54:05","lastUpdate":"2017-11-07 13:52:27","pivot":{"module_id_fk":1,"permission_id_fk":1}},{"id":3,"name":"Write","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","pivot":{"module_id_fk":1,"permission_id_fk":3}}]},{"id":2,"name":"Employee","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","permission":[{"id":3,"name":"Write","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","pivot":{"module_id_fk":2,"permission_id_fk":3}}]},{"id":3,"name":"Report","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","permission":[]},{"id":4,"name":"Access Right","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","permission":[]}]

Open in new window



In my angularjs controller I have the following line of code:

	$scope.compare = function(a,b){
		$scope.tmp = [];	
		for(var outer in a[0]){
			if(b.length>0){
				for(var inner in b){
					if(b[inner].name === a[0][outer].name){
						$scope.tmp.push({"name":a[0][outer].name,"status":true});
					}
				}
			}else{
				$scope.tmp.push({"name":a[0][outer].name,"status":false});
			}
		}
		return $scope.tmp;
	};

	$scope.init = function(){
		
		$scope.dfperm = [];
		$scope.modperm = [];
		$scope.counter = 0;
		
		$http({
			method: 'GET',
			url: "/api/v1/module/list"
		}).then(function successCallback(response){
			//console.log(response.data);
			//$scope.module = response.data;
			$array = response.data;				
						
			angular.forEach($array, function(outer, key) {			
				if(key==='data'){					
					$scope.dfperm.push(outer);
					//$scope.counter++;
				}
				if(key==='try'){
					angular.forEach(outer, function(outerItem, key){ 
						 var tmp = $scope.compare($scope.dfperm,outerItem.permission);
						 $scope.modperm.push({"name":outerItem.name,"permission":tmp});
					});
				}
			});
		}, function errorCallback(response) {
			console.log('intention error',response.data);
		});
		
	}

Open in new window


What I am attempting to do is to create a new permission object that has the status true or false.

As shown the data object contains a list of default permission.

The try object on the other hand shows that each module has permission. A module can have 0 or more than 1 permission.  

Now i'm trying to reconstruct the information so that each module has equal number of default permission but based on the try object conditioning (permission) is done to set the status either true or false.

However my code above doesn't do so. Rather a module with is set based on the try object conditioning (permission) and others are set with the default permission and status false.

Your help is kindly appreciated.
0
Hello,
  I have a profile update page that is displaying the changes after the update button is clicked but it is not updating the actual table data. Here is what I have
if(isset($_POST['Update'])) {
	mysql_connect('xxxxxx', 'xxx', 'xxx') or
    die("Could not connect: " . mysql_error());
	mysql_select_db("xxx");
	
	if(!empty($_POST[FirstName]))  {
    $first_name = $_POST['FirstName'];
}
if(!empty($_POST[LastName]))  {
    $last_name = mysql_real_escape_string($_POST['LastName']);
}
if(!empty($_POST[Email]))  {
    $email = mysql_real_escape_string($_POST['Email']);
}
if(!empty($_POST[Password]))  {
    $password = mysql_real_escape_string($_POST['Password']);
}
if(!empty($_POST[Add1]))  {
    $address_1 = mysql_real_escape_string($_POST['Add1']);
}
if(!empty($_POST[Add2]))  {
    $address_2 = mysql_real_escape_string($_POST['Add2']);
}
if(!empty($_POST[City]))  {
    $city = mysql_real_escape_string($_POST['City']);
}
if(!empty($_POST[County]))  {
    $county = mysql_real_escape_string($_POST['County']);
}
if(!empty($_POST[State]))  {
    $state = mysql_real_escape_string($_POST['State']);
}
if(!empty($_POST[Zip]))  {
    $zip_code = mysql_real_escape_string($_POST['Zip']);
}
if(!empty($_POST[PhoneNumber]))  {
    $phone_num = mysql_real_escape_string($_POST['PhoneNumber']);
}
	$sql = "UPDATE 'users' SET 
       FName = '.$first_name.', 
       LName = '.$last_name.', 
       Email = '.$email.', 
       city = '.$city.', 
       state = '.$state.',
	   Zip = 

Open in new window

0
I want to fetch the data but while fetching the data i'm getting the whole data but i want only single employee details.
for example if employee id's are GI1006,Gi1007,GI1008 are in my database but i want only GI1008 so how can i chnage my code ??

<?php
 $dbhost = "localhost";
 $dbuser = "root";
 $dbpass = "Gemini@123";
 $db = "employee database";

    $conn = mysql_connect($dbhost, $dbuser, $dbpass,$db);

   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }

   $sql = 'SELECT EmployeeID,FirstName,MiddleName,LastName,FatherName,SpouseName,MotherName,DOB,Age,BloodGroup,MaritalStatus,Gender,ContactNumber,EmergencyContactNumber,Email,DateOfJoiningatGemini,TotalYearOfExperience,ReleventYearOfExperience,PANnumber,PassportNumber,UANnumber,AadharNumber,PresentAddress,PermanentAddress
      FROM employee_inforamtion';

   mysql_select_db('employee database');
   $retval = mysql_query( $sql, $conn );
   if(! $retval ) {
      die('Could not get data: ' . mysql_error());
   }

   while($row = mysql_fetch_assoc($retval, MYSQL_ASSOC)){

   echo "<tr>";
   
   
      echo " <tr>";
      echo  "Employee ID :{$row['EmployeeID']}</br></br> ";
      echo "<tr>";
      echo  "First Name :{$row['FirstName']}</br></br> ";
      echo "<tr>";    
      echo  "Middle Name :{$row['MiddleName']}</br></br>";
      echo " <tr>";
      echo  "Last Name :{$row['LastName']}</br></br>";
      echo " <tr>";
      echo     "Father Name :{$row['FatherName']}</br></br>";
      

Open in new window

0
Hi Experts,

I have a client that did a mail blast using mailchimp and says that those emails went to Junk or Promo folders.

If I was to do the blast using PHP and loop one by one email, would this be avoided?

Thanks,
0
Who can explain what is happening:

Using the code like this it works fine,

<?php
if  (isset($_SESSION['id'])) {
echo $_SESSION['uid'];
} else { echo "<form action='signup.php'>
                         <button class=' button button1'>SIGN UP</button>
                        </form>";
                  }

Open in new window


Add tags to first echo out put and it crash error "the page isn't working".

example:

<?php
if  (isset($_SESSION['id'])) {
echo "<tag>$_SESSION['uid'];</tag>"
} else { echo "<form action='signup.php'>
                         <button class=' button button1'>SIGN UP</button>
                        </form>";
                  }

Open in new window


Any help is welcome
0
Hi,

I have a contact form with an XML that loads the contact information in the contact form. I am busy adjusting this. Instead of a dropdown, I want to build an ajax life search. Can someone help with that? I like to hear it

Thanks
test.xml
test3.php
0
I have an angular UI application of two pages where one page takes user input details and insert the values on click of button into MySql DB through an API call and redirects to second page where details entered in first page must be displayed to user.

After inserting the values in first page, the values are stored in DB where it is recorded in php logs but in second page when I want to show the details of user entered, data row doesn't exist in DB.

The insert query is a single row insert and is not under any transaction. However even after implementing transactions same issue persist.

I have records of mysql logs also where there is only the insert log but no delete logs for the same inserted values.

I have kept a count of data before inserting and after inserting, the count got reduced by one when I have made a second API call to get details to second page to display the user details and throwing an exception of 400 bad request.
0
I have a custom post type called manu-color for Manufacturer Colors. Each manufacturer color, there are four custom fields called primary color, secondary color, third color and fourth color.

So basically if manufacturer color is British Racing Green then primary color will be olive green, secondary color will be red, third color will be silver and fourth will be black

I am displaying all the manufacturer colors in a select box, but where I am stuck is when a color is selected I have want to show the primary, secondary, third and fourth colors of the selected manufacturer color in a radio button and make them checked

Here is my code for my select box

<?php
$args = array( 
    'post_type' => 'manu-color', 
    'posts_per_page' => -1,
    'orderby' => 'title',
    'order' => 'ASC',

);

$manu_colors = get_posts( $args );   
echo '<div id="manu-colors-content"><select id="manu-colors">';
 echo '<option class="default" value="-1">select manufacturer color</option>';
 foreach ( $manu_colors as $post ) {
     $manu_color_slug = $post->post_name;
     echo '<option class="'. $manu_color_slug .'">'. get_the_title() . '</option>';
 }
echo '</select></div>';
?>

Open in new window


here are my four radio button

<label for="primary_color"><input id="primary_color type="radio" name="primary_color" value="need to pass primary color here"><span>primary color name</span></label>
<label for="secondary_color"><input id="secondary_color type="radio" name="secondary_color" value="need to pass secondary color here"><span>secondary color name</span></label>
<label for="third_color"><input id="third_color type="radio" name="third_color" value="need to pass third color here"><span>third color name</span></label>
<label for="fourth_color"><input id="fourth_color type="radio" name="fourth_color" value="need to pass fourth color here"><span>fourth color name</span></label>

Open in new window


I am open to any advice as I have to display those 4 colors other wise customer won't know what a manufacturer color is

Thanks
0
Hello Experts,

I am working on a CF application and need a CF function equivalent to exit(); (PHP).

I am trying to addess this particular fix
Acunetix reference

This is what I am doing, but not sure if t works.  

<cfset GetPageContext().getCFOutput().clear()>
   <CFLOCATION URL="Login.cfm?Message=Logon ID must be 5 digits." ADDTOKEN="no">
	<CFABORT>

Open in new window


- Dan
0
Industry Leaders: We Want Your Opinion!
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

I need to paginate excerpts from all the articles that I have written which is 200+ articles. These excerpts need to be split into different pages. Do I need a database for this or should I stick with client side? Which one would be faster?

I'm talking about something like this.

https://www.techpowerup.com/reviews/
0
I'm trying to trace the logic of a page that's using Blitz.

The index.php has several functions at the top, but it's the bottom that I'm thinking represents the answer to my questions.

if (!empty($subDomain) && file_exists(REG_ROOT.'templates/'.$subDomain.'.tpl')) {
    
    if($_GET['resetSession']){
        resetSession();
    }
    
    $T = new Blitz(REG_ROOT.'templates/'.$subDomain.'.tpl');

    $_POST['subdomain'] = $subDomain;
    $out = array_merge($_GET, $_POST);

    if(!empty($_POST['verifyUser'])){
        if(verifyUser($_POST)){
            $out['usrVerified'] = 1;
            unset($_POST['findUser']);
        } else {
            unset($_POST['verifyUser'],$out['usrID']);
            $_POST['findUser'] = 1;
        }
    } 

    if(!empty($_POST['findUser'])){
        $usrArray = findUser($_POST);
        if(is_array($usrArray)){
            $out = array_merge($out,$usrArray);
        } else {
            $out['usrMsg'] = $usrArray;
        }
        echo $T->parse($out);
        return false;
    }
    
     if(!empty($_POST['findCoachingSessions']) && is_numeric($out['usrID'])){
        $out['event_list'] = findCoachingSessions($out['empID'], $out['usrID'], $subDomain);
        if(is_array($out['event_list'])){
            foreach($out['event_list'] as &$event){
                $event['guid'] = buildGUID(array('empID'=>$out['empID'],'evID'=> 

Open in new window

0
Server windows 2012 with MYSQL 5.7 standard version.

Want to backup my database using the following schedule, Full backup ones a week and differential on daily basis.

So far got a script running a full backup using MySqldump schedule to run on a weekly basis.

Now I would like to add a differential to it.
0
Before submitting the page i need some alert at the password atleast one special cheracter message . How can i write the code.
<?php 

	include 'connect.php';
	include 'fun.php';
	
	$error = "";
	
	if(isset($_POST['savepass']))
	{
		$password = $_POST['password'];
		$confirmPassword = $_POST['passwordConfirm'];
		
		if(strlen($password) < 5)
		{
			$error = "Password must be greater than 5 characters";
		}
		else if($password !== $confirmPassword)
		{
			$error = "Password does not match";
		}
		else if (!preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $password))
		{
			$error = "Atleast one special character in the Password";
		}

		else
		{
			/*
			$password = password_hash($password,PASSWORD_DEFAULT);
			*/
			
			$emp_id = $_SESSION['emp_id'];
			if(mysqli_query($con, "UPDATE users SET password='$password' WHERE EmployeeID='$emp_id'"))
			{
				$error = "Password Changed Successfully, <a href='login2.php'>click here</a> to Log In";
			}
			
		}
	}
	
	
	if(logged_in())
	{
		
		
	?>
		
		<?php echo $error; ?>

Open in new window

0
Hello experts,

I am trying to check if the post data obtained for 'fields' is empty. I have tried different conditions to check if the array is empty or not. Even if the 'fields' is empty, the if condition executes. It would be great if someone could suggest me as to how to go about with this.

View:
<h4>Alternatives</h4><input type="text" style="width:700px;display: inline" id="fields" name="fields[]" placeholder="Enter Method Name" class="form-control method_list_list"/> <input type="button" name="addmore" id="addmore" class="btn btn-success" value="Add More"/>

Model:
public function addmethodtotask(){
	 $conn= mysqli_connect("localhost","root","","cognitivewalkthrough");
	 $taskid=  $_POST['taskid'];
	$description =  $_POST['reason'];
	$action = $_POST['action'];

//if (isset($_POST['fields']) && $_POST['fields'] != "") {
	if (isset($_POST['fields']) && $_POST['fields'] != NULL) {
	// if (count($_POST['fields'])>0 && !empty($_POST['fields'])) {
		 echo "whey am i here";
				foreach ( $_POST['fields'] as $key=>$value ) {
					$sql_website = sprintf("INSERT INTO method (methodname,description,action) VALUES ('%s','%s','%s')",mysqli_real_escape_string($conn,$value),mysqli_real_escape_string($conn,$description),mysqli_real_escape_string($conn,$action) );
					$this->db->query($sql_website);
					$inserted_method_id = $this->db->insert_id();
				}
	}
        

Open in new window

0
Any good software that can analyze coding of websites offline?
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.