PHP

120K

Solutions

33K

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

Hi experts,

I need SQL syntax help please.

Here is my business scenario; I need to get a count by distinct employee type of 4 different measures. If the count of employees by each measure does not equal zero/null then show the total count. If the count of employees by each measure equals zero or null, show zero.

I'd like to use PHP to echo the results in a table that would take the following format:

distinct_type | MeasureA | MeasureB | MeasureC | MeasureD
Emp Type X | 1 | 0 | 1 | 1
Emp Type Y | 0 | 1 | 0 | 1
Emp Type Z | 1 | 1 | 0 | 0

Something like...I know I am way off...

(SELECT DISTINCT employee.type AS  'distinct_type' FROM mydatabase ORDER BY employee.type)
UNION ALL
(SELECT employee.type, COUNT(*) AS 'MeasureA' FROM my database WHERE employee.type=distinct_type AND measures.a=1 GROUP BY employee.type ORDER BY employee.type ASC)
UNION ALL
(SELECT employee.type, COUNT(*) AS 'MeasureB' FROM my database WHERE employee.type=distinct_type AND measures.b=1 GROUP BY employee.type ORDER BY employee.type ASC)
UNION ALL
(SELECT employee.type, COUNT(*) AS 'MeasureC' FROM my database WHERE employee.type=distinct_type AND measures.c=1 GROUP BY employee.type ORDER BY employee.type ASC)
UNION ALL
(SELECT employee.type, COUNT(*) AS 'MeasureD' FROM my database WHERE employee.type=distinct_type AND measures.d=1 GROUP BY employee.type ORDER BY employee.type ASC)
0
OWASP: Avoiding Hacker Tricks
LVL 13
OWASP: Avoiding Hacker Tricks

Learn to build secure applications from the mindset of the hacker and avoid being exploited.

Thank you for looking at my question,

The IT department have installed Webmin on a MySQL server. I have written a bit of php code and saved it to the correct place on the server.

The code is a simple table and begins like this:
<?php # Script 1.0 - Section1.php
      require_once $_SERVER['DOCUMENT_ROOT'] . '/CESTrack/Includes/configinc.php';
      //require_once $_SERVER['DOCUMENT_ROOT'] . '/CESTrack/Includes/mysql_connect.php';
      
      $Page_Title = "KLTD E-D1";
      include($_SERVER['DOCUMENT_ROOT'] . '/CESTrack/Includes/CESTrack_Header.html');
      
      echo '<h2>CES Tracker</h2>';
      
      echo '<table width="100%">';
            echo '<tr>';
                  echo '<td align="center">';
                        echo '<table width="80%" border="2">';
                              echo '<tr>';
                                    echo '<td colspan="16">';
                                          echo '<h2>HONKER LTD CES DASHBOARD</h2>';
                                    echo '</td>';
                              echo '</tr>';
                              
                              echo '<tr>';
                                    echo '<td width="13%" align="left">';
                                          echo'<h2>Activity</h2>';
                                    echo '</td>';
                                    
                                    echo '<td width="13%" align="center" colspan="3">';
                                          echo'<h2>Queries</h2>';
                                    echo '</td>';
                                    
                                    echo '<td width="13%" align="center" colspan="3">';
                                          echo'<h2>SENQ Enq/Quotations</h2>';
                                    echo '</td>';
                                    
                                    echo '<td width="13%" align="center" colspan="3">';
                                          echo'<h2>SENQ Orders</h2>';
                                    echo '</td>';
                                    
                                    echo '<td width="13%" align="center" colspan="3">';
                                          echo'<h2>Projects</h2>';
                                    echo '</td>';
                                    
                                    echo '<td …
0
Problem with my query, when adding a value that has a single quote to a database field.

eg. //-- values
        $value1 = "Peter";
        $value2 = "O'Leary";
        $value3 = "Contact Person";
     //-- query
        $stmt = $mysqli->prepare("INSERT INTO table1 (field1, field2, field3) VALUES (?,?,?)");
        $stmt->bind_param('sss',  $value1, $value2, $value3);
        $stmt->execute();
        $newId = $mysqli->insert_id;
        $stmt->close();

This does not insert anything, and $newId has no value.

So it seems I have a really silly question... I'm sure it's something really obvious, but I'm dead tired and can't figure it out.

I've tried...
$value2 = htmlspecialchars("O'Leary", ENT_QUOTES, 'UTF-8');
$value2 = mysqli_real_escape_string($mysqli, "O'Leary");
0
There are two buttons in PHP. If user click button 1, it will go to action1.php. If user click button2, it will go to action2.php

Any idea how to code it ?

Thx
0
Is there a way to embeeded the HTML form into the PHP code below ?

HTML Form
echo "
                  <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
                  <input type="text" name="number1" />
                  <input type="text" name="number2" />
                  <br /><br /><br />
                  <input type="submit" name="submit" value="Submit"/>
                  <input type="reset" name="reset" value="Clear" />
                  </form>
            ";


<!DOCTYPE HTML>  
<html>
<head>
</head>

<body>  

<?php
      //$filePath = $_SERVER['PHP_SELF'];       // find URL of current file without the hostname
      extract($_POST);                                       //array to variable conversion, $_POST("number1") => $number1
            
      if (isset($number1) && isset($number2)) {
            // perform type casting to variables
            $number1 = (int) $number1;  
            $number2 = (int) $number2;  
            $sum = $number1 + $number2;
            if ($number1 > $number2)
                  print("number1 is greater than number2 <br />");
            else if ($number1 < $number2)
                  print("number1 is less than number2 <br />");
            else
                  print("number1 is equal to number2 <br />");

            print("The sum of the 2 numbers is $sum<br />");
      } else {
            //show the html form
            
      }
?>
</body>
</html>
0
Hi Experts,

Firstly thank you for taking a look at my question.

I am trying to access the details of xml where the attribute = Yes.

I am trying this but it is not quite correct:

$bestmatchIndAddress = $xml->soapBody->Response->BestMatch->IndividualDetail->ContactDetails->AddressDetails['Current=Yes'];

many thanks for your help!!
0
Hi Experts!

Firstly thank you for taking a look at my question.  I am having a shocking morning and can't for the life of me work out how to get the details out of the XML data.

given this XML:

  ["soapBody"]=>
  object(SimpleXMLElement)#2 (1) {
    ["Response"]=>
    object(SimpleXMLElement)#3 (5) {
      ["@attributes"]=>
      array(2) {
        ["Version"]=>
        string(3) "1.0"
        ["Environment"]=>
        string(1) "T"
      }

How do I access the Version and Environment data?

This is what I am trying -

        $xml = new SimpleXMLElement($response);
      $consumer = $xml->xpath('//Response/Version');
      echo "<br><Br>Consumer:".$consumer;

I have worked with this before but am having a brain block this morning.

This is the current response.

Notice: Array to string conversion in C:\xampp\htdocs\illion\illion v2.php on line 55
Consumer:Array

many thanks for you help!!!
0
Hi All,

I use laravel. I want to update database using

$data = DB::connection('sqlsrv2')->statement('exec [spname] ?, ?',  [$empcode, $pwd])';

The response is ok, but it does not update database.

What is the problem?

Thank you.
0
Hi, I have a PHP script which calls another PHP script via a jQuery ajax call.  I can see that the call is successful and that there is a proper response from the network activity.  However I am having trouble processing that response in the calling PHP/JavaScript code.

Here's my attempt:

demo.html

From the network activity I see the response is:

["data1","data2"] and this is what I am expecting (actual data not shown)

But I cannot 'see' nor process these data in the success data in the calling code shown above.  The alerts do not fire.

Any guidance will be most appreciated and thank you in anticipation.
0
I can't believe I have to ask this, but I can't seem to find anything on the subject (probably not searching for the right term, but using PhpSpreadsheet, how can I simply Select a Cell.  I've completed my work and simply want to set the focus back to A1 so when the user opens the workbook the selected cell is A1.
0
CompTIA Cloud+
LVL 13
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Hi Experts,

Firstly thank you for taking a look at my question!

Using PHP i need to access the xml body inside a soap packet.

the soap response looks like this:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
        <Response   Version="1.0" Environment="T" xmlns="http://www.dnb.com.au/Schema/CCB/1.0">
            <ConsumerHeader SegId="ERHD01" InternalReference="M20190912095903-023-000238" EnquiryType="1" UniqueCustomerReference="Test" ConsumerId="2190130" Country="AU" ProductCode="AMD3" NewFileCreated="0" IsMinor="0" HasSummary="1" HasJudgment="1" HasBankruptcy="1" HasSummons="1" HasOtherPublicRecord="0" HasDirector="0" HasFileNote="0" HasDefault="1" HasEnquiry="1" HasError="0" HasWarning="0">
                <EnquiryDate Year="2019" Month="9" Day="12" />
                <PersonName>
                    <FirstName>FirstTest</FirstName>
                    <Surname>LastTest</Surname>
                </PersonName>
            </ConsumerHeader>
            <BestMatch MatchScore="768">
                <IndividualDetail SegId="ERID01">
                    <DateFirstRecorded Year="2003" Month="6" Day="10" />
                    <Person Sex="U">
                        <PersonName>
                            <FirstName>FirstTest</FirstName>
                            

Open in new window

0
I think this is going to be a very difficult one for me to explain, but I'm going to try.

The server has to be updated to php 7, so this has been done but not visible yet. I changed all mysql calls to mysqli. I "think" the problem is in the below code - it's maybe not in the correct format for mysqli calls? I did a test separate of everything with just basic code and I do get a positive that it's correctly connecting to the database. But I can't even figure out how to get it to respond to something in the below code to tell me anything. It's not giving any errors to me on screen.

The server tech only showed this in logs:
> [Thu Sep 12 10:41:31.223508 2019] [php7:warn] [pid 6093]
> > > > > [client 73.15.109.72:45414] PHP Warning:  mysqli_error()
> > > > > expects exactly
> > > > > 1 parameter, 0 given in
> > > > > /home/atra/public_html/couplings/connection.class.php on line
> > > > > 36,

Which is what is leading me to think it's there in the connection call in the below code.

I'd appreciate any help/insight. I know it's difficult since I can't show a link or attach all the files. I can definitely say all include files are being included and the config file with database details is correct.
<?php

class connection
{
	var $db;
	var $tables;
	var $domain;
	var $user;
	var $password;
	var $connection;
	
	function connection()
	{
		$tables = array();
	}
	
	function makeConnection($d_base, $ip, $user, $password)
	{
		$ip = 'localhost';
		

Open in new window

0
Hello everyone,

I am having trouble sending my form.
Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/..... on line 23
foreach($_POST as $var=>$val){
	if(!is_array($val)){
		$$var=strip_tags($val);
	}else{
		while(list($arvar,$arval)=each($val)){
			$$var[$arvar]=strip_tags($arval);
		}
	}
}

Open in new window

On some form this same code works but on other no.
If I delete this line, the form sends out without worries but I was advised to keep it some time ago.
What's the use of this line, no idea ... except that it cleans the inputs ... but I understand nothing!

I ask your help to understand it and correct it please.

Thank you in advance
0
I had this working for custom post type called episode. But had to switch to posts.

I no longer have the term id of 173 which is why it's commented out.

Right now I'm not getting the term premium swapped out for Free once I hit the 11th post. It still says Free for the last 11 posts and if I add a new one it just keeps the Free term and not Premium.

/*Add terms to chapters */

add_action( 'save_post_episode', 'total_set_default_object_terms', 11, 2 );
function total_set_default_object_terms( $post_id, $post ) {
  if ( 'publish' === $post->post_status) {
    $position = 1;
    $args = [
      'numberposts' => -1,
      'order' 			=> 'DESC',
      'orderby' 		=> 'date',
      'post_type' 	=> 'post',
      'taxonomy' => 'episode_type',
      //'tax_query' => array(
					//array(
					//'taxonomy' => 'episode_type',
					//'field' => 'id',
					//'terms' => array( '173' ),
					//'operator' => 'NOT IN',
					//),
					//),
						];
						
						
    $posts = get_posts( $args );// query posts that are episodes in descending publish date order
    foreach($posts as $post) {
      if ($position > 10) {
        wp_set_object_terms($post->ID, 'premium', 'episode_type', false);
      }
             
      $taxonomies = get_object_taxonomies( $post->post_type );
      
      $position++;
     }
  }
}

Open in new window


Halp!
0
I have a couple of PHP modules that include JS and jQuery logic.  One is chat.php and the other is fetch_user.php.  chat.php does a jQuery ajax call to fetch-user.php  and fetch_user.php returns an HTML table to chat.php which is then inserted into chat.php's DOM.  All this works perfectly.

In the data returned from fetch_user.php there is an HTML button which has some attribute data which the ajax  'success' function has access to and I can extract this data OK.

My issue is that I have a JS array which as far as I am aware has global JS access.  I want to first empty the existing data in that array (which is named logged_in_array) and the add the extracted attribute data to that array.  In my code the logged_in_array.length = 0 does not empty the array, nor does the logged_in_array.push work.

So my specific issues are that the array is not being emptied nor is the attribute datum being added to the array.

I will attach extracts of the code:

demo-code.html
0
Hi,

I have added the line $wgExternalLinkTarget = '_blank' to LocalSettings.php so that external links open in a new windows and this works fine.  I also want to open internal links, e.g. PDF links in the same way.  Is there an easy solution to this, similar to external links?
0
Hi All,

I have application that created using laravel.
When idle the current screen still appear.
Could we set it back to login form at idle time is reached without user interference?

Thank you.
0
Hi Experts,

I was given access to production server (admin) thru SSH/SFTP.

Tried changing something on a PHP file (using Core FTP LE), was able to edit/override and it got saved as well, however don't see them affecting my site.
Guess I'm missing something just don't know what...
Tried clearing app cache but didn't help.

In addition, when right clicked on a JavaScript file and selected Edit, did not gave me an option to open with Notepad, just threw some error, as though I was trying to execute it.
How can I accomplish that?

Thanks
0
Hi Guys
I have an e-commerce website using classic ASP and running with  Microsoft platform
I do not use PHP in my code at all but  my hosting company  is using PHP  for its mail handling
In other words I cannot disable The PHP  interpreter in my Plesk
My website  however all of a sudden is being bombarded with php script  files.  thousands  of them each 24 hours
So far I've had no problems  But......
I am a strong believer that a hacker will not  waste all this time and effort without expecting a reward.
My question is:
Is there anything I can do to combat this situation?
Thanks
Dory
0
Bootstrap 4: Exploring New Features
LVL 13
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

This portfolio plugin here is fine, but I want to customize the link on the detail button.  http://146.66.113.175/~techgard/products/

For instance, on the IX details button, instead of going to http://146.66.113.175/~techgard/portfolio/ix-systems/, I would like it to go to http://146.66.113.175/~techgard/ix-storage 

1. Can I update that in the database?
2. Or can I just do a permanent redirect with htaccess?
3. If I do, will it get overwritten if I update the plugin?
4. Any other way to do this?

Plugin is: https://wordpress.org/plugins/filterable-portfolio/ on WP 5.2.3. Thanks!
0
PHP, how do  Write "If any of the following != Something then skip"?

<?php
if ($main_cant_miss != 'yes') {
                            if ($cant_miss != 'yes') {
                                if ($challenge_miss != 'yes') {
RUN SOME CODE
} 
}
}

Open in new window

I know there is a clean way to write this.
0
I have this in PHP
       $results['News'] = [
           'Channel8' => [
               'News' => 'Walter Cronkite',
               'Weather' => 'Robert Blizzardo',
               'Sports' => 'Jane Goalie'
           ],           
           'Channel10' => [
               'News' => 'James Newsworth',
               'Weather' => 'Mary Storm',
               'Sports' => 'Joe Puck'
           ],
           'Channel13' => [
               'News' => 'Helen Worldview',
               'Weather' => 'Mary Rainer',
               'Sports' => 'Joe Gridiron'
             ]           
           ];

Open in new window

I want to echo "Mary Storm"

How do I do it and can somone give me a good PHP tutorial on Objects and Arrays in PHP
0
I have OpenSSL encrypt / decrypt working on a sales form. The OpenSSL code is specific in order to decrypt old MCRYPT data as well as encrypt/decrypt new data with OpenSSL, due to a move from PHP 5.6 to 7.2.

The issue now is that the return data has extra "hidden" characters and isn't being "trimmed" properly with a simple trim($data).
This in itself isn't terrible for display, but when our users resubmit the sales form after making other changes, the fields with the returned, decrypted data, now gets re-encrypted with the extra "hidden" characters. This effects things, such as "last four" of a number saved and displayed, since now, the last 4 are hidden.
By hidden, I mean ASCII / hex characters that don't normally display like backspace, EOT - End of Transmission, SOH - Start of Header, etc.
These are seen in a bin2hex of the data which looks like this:

On a 16 digit number, I get 16 (hex) characters added to the end of the returned number - 20202020202020200808080808080808
These happen to be a space(20) and backspace(08).

With 4 or 3 digits, its a little different:
0620 (<--Actual Number) 3036323004040404 <- Hex return of EOT- End of Transmission
495 (<--Actual Number)  3439352020030303 <- Hex return of Spaces and ET - End of Text

I have been able to mitigate the display and re-encryption issue by adding to the trim function, i.e. $result = trim($decrypt, "\x00.. \x20");

However, I'm hoping to nip this in the bud at the encryption /…
0
I am trying to use the PHP database session feature as detailed in the book "PHP Advanced" by Larry Ullman except that I am using PDO rather than MySQLi.

I have this working perfectly in localhost on a different website but on the current website it is not working.  

The code to establish the database session: db_sessions.inc-PDO-.php

The attempted usage code: login.php

This works fine until about line 100.  The session is in PHPSESSID but not in the database table 'sessions'.

The only difference that I can see is that I am using jQuery validator remote (in login.php) which connects to the same database OK (without sessions) and that code all works OK.  In the AJAX-called module I do delete the PDO before returning out of the AJAX-called module.

I am mystified why sessions variables are being set but not in the database sessions table.

Any advice will be most appreciated.

Thanks, Eric.

P.S., just noticed an error message:
Fatal error: Call to a member function prepare() on a non-object in C:......................\db_sessions.inc(PDO).php on line 118
Line 118 is $r1 = $pdo123->prepare($q1); in function write_session
But this error does not appear in the other website I mentioned with identical session-establishment code??
So that probably explains why the database sessions table has no data in it but it does not explain why this fatal error is occurring.
Again, looking forward to any advice and thanking you in anticipation.
0
Hello everyone.
Im trying to create Stripe payment, well rather Checkout session page. Nothing unclear about their API, well documented and everything.
However, I have a form with 3 fields, one required, other two are not
Now this is when everything is filled in (and it works)
$session = \Stripe\Checkout\Session::create([
            'payment_method_types' => ['card'],
            'billing_address_collection' => 'required',
            'client_reference_id' => $_SESSION['account_id'],
            'customer' => getUserData($link, $_SESSION['account_id'], 'stripe_id'),
            'subscription_data' => [
                'items' => [[
                    'plan' => $_POST['plan']
                ]],
                'metadata' => [
                    'fingerprint' => $fingerprint,
                    'local_account' => $_SESSION['account_id'],
                    'computer_id' => $computerid (this should be removed if field 1 is not posted)
                ],
                'trial_period_days' => '365' (this should be removed if field 2 is not posted)
            ],
            'success_url' => $stripe['success_url'],
            'cancel_url' => $stripe['cancel_url']
        ]);

Open in new window

without making all of the combinations depending on the values from field one used for defining trial_period_days and field two defining stuff in metadata?

Thanks
0

PHP

120K

Solutions

33K

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.