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

I need help with why this woo commerce function is returning duplicate values.

add_action ('woocommerce_review_order_after_cart_contents', 'display_item_qv', 10);

function display_item_qv () {

	global $wpdb;
	
	//$wpdb->show_errors = TRUE;
//$wpdb->suppress_errors = FALSE;
	
	$val = 0;
	
	foreach( WC()->cart->get_cart() as $cart_item ) {
   $product_in_cart = $cart_item['product_id'];
   

$item_qv = $wpdb->get_row("
SELECT DISTINCT
    p.id AS 'Product ID',
    p.post_title AS 'Product Name',
    t.name AS 'QV'
FROM 
	wp_posts AS p
INNER JOIN
    wp_term_relationships AS tr ON p.id = tr.object_id
INNER JOIN
	wp_term_taxonomy AS tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
INNER JOIN
    wp_terms AS t ON t.term_id = tt.term_id
WHERE 
	tt.taxonomy='pa_qv'
AND 
	p.post_type = 'product'

AND id=$product_in_cart", ARRAY_N);
	

		
		
$val += $item_qv[2] * $cart_item['quantity']; 
	//echo $item_qv[2];
	/*echo "<pre>";
	print_r($item_qv);
	echo "</pre>";*/
	
	}
echo "The total is ". $val;
	//print_r($item}
}

However, it is giving duplicate values and I have been unable to remove the duplicate value.  Please tell me what I need to change to just get one value.  

Here is a screenshot
https://gyazo.com/a442f57ffba799a48417d65a260217a0 - the 12.1 12.1 at the top of the image on the right side should only be 12.1 once. 

If this can't be fixed, please tell me how to use Class WC_Product_Attribute instead.

Open in new window

0
Cloud Class® Course: Microsoft Exchange Server
LVL 12
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

I am hard coding my site title at the moment but want to make it dynamic as every page requires header.php so every page has the same title tag. I currently define it in the config file like this:

define('SITENAME', 'My Website');

Open in new window


But for example, on the contact page I might want it to just say 'My site | Contact us'. Obviously this is a contrived example but I am trying to keep this simple.

Not sure if I should store page titles and meta description etc. in the database or just use a switch statement in the config file to say if the page is this then the title is this, or if the page is that then the title is that etc.

Any suggestions welcome!
0
How can I read the value from a cookie previously set using php. I have set the cookie using :

<?php
$fromUser = htmlspecialchars($_GET["uname"]);
$cookie_name = "user";
$cookie_value = $fromUser;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");   //    86400 = 1 day
?>

Now I want to read the value of that cookie when I goto a different page, within the same domain.  

Tnx for your help
0
Hi:
I am getting the error "Unknown column 'cr_tags.tag' in 'field list'" when executing the code.
I first built the code for two tables and I got the results that I expected; however, when I added the third table I got this result.
Any ideas why this is, and how to resolve 'cr_tags.tag' in the code?

MySQL version: 5.7.19
PHP version: 7.0.27
APACHE: 2.4.25

Table: cr_name
Columns: id (int 10), name (varchar 70)
Values:
id      name
---------------------
424     name 1
425     name 2
426     name 3
427     name 4
428     name 5
429     name 6

Table: cr_notes
Columns: id (int 10), notes (varchar 500)
Values:
id      notes
---------------------
424     notes 1
425     notes 2
426     notes 3
427     notes 4

Table: cr_tags
Columns: id (int 10), tag (varchar 30)
Values:
id      tag
------------------
424     tag 1
425     tag 2
426     tag 3
428     tag 5

Desired output:
id        name     notes        tag
--------------------------------------------
424     name 1
425     name 2  notes 2
426     name 3  notes 3     tag 3
427     name 4  notes 4
428     name 5                    tag 5
429     name 6

Actual output:
"Unknown column 'cr_tags.tag' in 'field list'"

$sel = "(SELECT cr_name.id AS rank, cr_name.name, cr_notes.notes, cr_tags.tag
FROM cr_name
LEFT JOIN cr_notes
ON cr_name.id = cr_notes.id
WHERE cr_name.id > 423)

UNION

(SELECT cr_name.id AS rank, cr_name.name, cr_notes.notes, cr_tags.tag
FROM cr_notes
RIGHT 

Open in new window

0
I am storing image names in an array from DB and then encode it with json encode function to receive it in my ajax success method:

Here is the code"

$sql_gallery = "SELECT * FROM map_projects_gallery ";		
$gallery_result = mysqli_query($conn, $sql_gallery);
while( $gallery_row = mysqli_fetch_assoc($gallery_result) )
{					
$gallery_image_name[] = $gallery_row["img_name"];			
}		

echo json_encode(array("map_gallery" =>$gallery_image_name ));		

Open in new window



Note: In ajax success function it returns all the image names. Now I want to display all images in a div and then later display them in a slider.


And here is my Code of jQuery Ajax
jQuery.ajax({
	url:"project.php",
	type: "POST",	
	data:  {"country_id":country_id,"lang_name":langname_val,"node_id":node_id,"fullurl":'<?php echo base_path();?>'},
	dataType: "json",								
	success: function(data)
	{
		alert(data.map_gallery);
		jQuery('#project-list').html(data.message1);  
	        jQuery('#paginations').html(data.message_2); 
		  
		
		  ///jQuery('.pr-cont-gallery').html('<img src=files/'+project_details.project_image+' width=200px>');	  
		  
		  jQuery('.pr-cont-gallery').append('<img src="' + data[0].map_gallery + '" />');

		  
		  data.forEach(function (data) {
				jQuery('.pr-cont-gallery').append('<img src="aaaaa.jpg" />');
		   });
	},
  }); 

Open in new window


Problem:  I am unable to display all images separately in a div. Need help to fix this issue
0
<?php


if(!empty($_FILES)){
    
    //database configuration
    $company = $_GET['company'];
    $dbHost = 'localhost';
    $dbUsername = 'root';
    $dbPassword = 'billadmin2006';
    $dbName = 'inventas';
    //connect with the database
    $conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
    if($mysqli->connect_errno){
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }
    
    $targetDir = "uploads/";
    $fileName = $_FILES['file']['name'];
    $fileSize = $_FILES['file']['size'];
    $targetFile = $targetDir.$fileName;
    
    if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
        //insert file information into db table
        $conn->query("INSERT INTO documents (companyName, f_name, d_date, f_size) VALUES('".$company."','".$fileName."','".date("Y-m-d H:i:s")."','".$fileSize."')");
    }
    
}
?>

Open in new window


The $company = $_GET['company']; is just not getting added to my database. The url is fine - the GET value is correct. If I set the $company = 'test'; it works. I am only using GET to test - I would usually use POST
Could I use a session variable - if so how do I set a session variable that can be used in multiple pages as a variable for database input
0
PHP - How can I convert a large hexadecimal value to a binary value?

<?php
   $hexString = "100000000000000000";
   echo base_convert( $hexString, 16, 2 );
?>

Open in new window

Is returning a 64 character long string of zeros "0000000000000000000000000000000000000000000000000000000000000000"
0
I'm a few months away from starting to take on Freelancing gigs.

I was wondering how to do my books/bill clients.

I had a fantasy about using Laravel to create a separate site on a subdomain that would bill clients and export a CSV. But I've been thinking about using Freshbooks.

I will probably offer subscription services (hosting/maintenance) which I want to bill using the web.

My website will be WordPress.

I'm not sure how to handle billing, and I want to have a good system down when I start. I know that Freshbooks has an API.

What would be the best way to handle this?
0
Hi,

I'm using TCPDF/PHP/MySQL to produce picking slips for my orders. I want to highlight orders where the quantity is greater than 1 so that the background is black and the text is white to make it stand out from a standard white background with black text for single unit orders.

I presume that this must be possible - does anyone have any pointers?

J
0
I am trying to find an online software or API that I can use to create PDFs online

I need something server side. I have a base PDF to work with.
I am using PHP, but that can be negotiable.
I need to mail merge the fields and generate a completed PDF for my client to view.

Any suggestions on software out there?
0
Cloud Class® Course: SQL Server Core 2016
LVL 12
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

I used form maker to create a form that pops up after 15 seconds on certain pages. The problem is when I click to close the box, it automatically take me to a page that says OOPs that page can't be found. It's directing it to a website that's in my footer link, after my domain. In other words my site is 101realestateinvesting.com but it redirects it to the link in my footer as part of my domain 101realestateinvesting.com/www.linkinfooter.com
0
Hi Experts

Could you point what's needed to show all the shop categories by using Woocommerce?

I'm using "Storefront" theme
img003
It seens it's limited to show only 03 categories, accordingly to:
img001
But I need to show more categories...
img002
Any suggestion or workaround?

(another more adequated them to use f.e.)

Thanks in advance
0
I have hundreds of already uploaded photos and want to compress their size. Without having to download them all, compress them and upload them again, is there some way of compressing all images in a particular folder already on a live server?
0
I have created a table in my database that literally has one field and the value will either be 0 or 1. In the admin section I have a toggle switch that when I turn on, changes the value to 1 and off turns the value to 0.

In my constructors in the front end I check the database to see if 1 or 0. If 0 then the page shows normally but if 1 then I use die and just kill the page with a maintenance message.

My question is, will this database call in the constructor effect page load speed and performance? This functionality is really handy for me but I don't want my convenience to negatively impact users.
0
Hi,

I am trying to make a submission via PHP Curl.

I need to submit a csv file as part of the body (using a bearer token for security)

I am having issues getting it to submit being told that my data has to be an array, -= Could anyone please advise where I am going wrong?

I did have an issue where I was getting a 0 status, returned, but once I encoded the variable $fielddata - I am now getting back an error from the API basically saying that I need to provide data in an array.  The only thing I can think of is the curl_file might be wrong?

basically I am just trying to submit the file that is in the same directory as the php file I am running.

$template = "Hi {{name}}! Click here {{url}} to enter our portal({{amount}}).";
$cfile = new CURLFile('meekimoney.csv','text/csv','meekimoney');
//$cfile = curl_file_create('meekimoney.csv','text/csv','meekimoney.csv');
// Assign POST data
echo "<br><br>";
$fielddata = array('file' => $cfile, 'name' => $nameofcampaign, 'template' => $template );
$data_json = json_encode($fielddata);
$headers = array();
$headers[] = "Authorization: Bearer ".$Bearer;
//$headers[] = "Cache-Control: no-cache";
//$headers[] = "Postman-Token: 202fee3b-9efd-48fe-9d98-483b7f9ebb64";
$headers[] = "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW";
//$headers[] = "Content-Type: application/json; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW";
//boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW";
$ch = 

Open in new window

0
Page title shows up on some pages but not all pages. How can I make them show up on all pages or none at all?
0
I want to add a link in my footer but it prints out the <a href=""> in the footer. How can I add a link in my footer?

This is the contents of my footer.php file:
<?php
/**
 * The template for displaying the footer.
 *
 * Contains the closing of the #content div and all content after
 *
 * @package wpre
 */
?>

	</div><!-- #content -->

	<?php get_sidebar('footer'); ?>

	<footer id="colophon" class="site-footer" role="contentinfo">
		<div class="site-info container">
			
			<span class="sep">
                			<?php echo ( get_theme_mod('wpre_footer_text') == '' ) ? ('&copy; '.date_i18n(__('Y','wp-real-estate')).' '.get_bloginfo('name').__('. All Rights Reserved. ','wp-real-estate')) : esc_html( get_theme_mod('wpre_footer_text') ); ?>
            </span>
		</div><!-- .site-info -->
	</footer><!-- #colophon -->
	
</div><!-- #page -->


<?php wp_footer(); ?>

</body>
</html>

Open in new window

How can I add a link in the file?
0
I had earlier posted about the PHP undefined variable issue i was facing, but i managed to solve it somehow and after that there is a small element that is not working if i could be helped with. So it is an online noticeboard system for a school and it has a users dashboard, teachers, and the admin. So the users dashboard is okay except when a user uploads a picture, it says not found technically i was having issues regarding the image as a undefined variable, and now it says not found. Earlier it was all working well.  also there is something about the user's updating password, when they update a password, says successful then when u log out and log in with the old password, i yet manage to log in with both old and new passwords. what could be the issue there?
Below is attached a screenshot for how the user dashboard looks like.
so here is the user's view for dashboard_header page:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Online Notice Board User Dashboard</title>

    <!-- Bootstrap core CSS -->
    <link href="<?php echo 

Open in new window

0
I have Magento 1.9 website with PHP 5.6.31 running on Windows IIS. Intermittently the website would have server 500 error, and more than 20 PHP CGI/FastCGI background processes running. The website will recover if its application pool restarted. I found there was Application Error in Event Viewer when the server 500 error first happened.
Faulting application name: php-cgi.exe, version: 5.6.31.0, time stamp: 0x595dca20
Faulting module name: php_wincache.dll, version: 1.3.7.12, time stamp: 0x58234af4
Exception code: 0xc0000005
Fault offset: 0x00015147
Faulting process id: 0x29d8
Faulting application start time: 0x01d432075ec736f9
Faulting application path: C:\Program Files (x86)\PHP\v5.6\php-cgi.exe
Faulting module path: C:\Program Files (x86)\PHP\v5.6\ext\php_wincache.dll
Report Id: 022fa75d-9dfd-11e8-80cb-000d3aa18ac6
Faulting package full name: 
Faulting package-relative application ID: 

Open in new window


Could it be the Application Error is the issue that caused server 500 error? How to fix this issue?
0
Cloud Class® Course: C++ 11 Fundamentals
LVL 12
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

This is a follow-on to this question - https://www.experts-exchange.com/questions/29113292/Need-To-Know-Syntax-To-Display-Attribute-On-Checkout-Page.html

I need to know how to make this show attributes dynamically to whatever is in the shopping cart on the checkout page.

Thanks,
0
Hi'

I'm experiencing difficulty importing fields in a CSV File that include german characters or umlauts e.g. Ü

The CSV contains a number of columns with one in particular named "itemTitle" which contains the word SCHÜTZEND which changes to SCHÃœTZEND, after the import has finished. I only noticed that SCHÜTZEND had changed to SCHÃœTZEND when I tried to perform an update query based on the field "itemTitle" as part of a data clean up.

What I mean by that is the HTML page correctly renders the word as SCHÜTZEND, however, when I examined the table via terminal I can see the actual value stored is "SCHÃœTZEND".

The field collation for itemTitle is the default: latin1_swedish_ci and the type is varChar(255). Just so that you know I've changed the collation to UTF-8 and many other varieties to no avail.

I'm using a LAMP setup and a snapshot of the import routine is shown below: -

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

{
         
$file = $_FILES['file']['tmp_name'];
        
$handle = fopen($file,"r");
fgets($handle);
        
while(($fileop = fgetcsv($handle,10000,",")) !== false)
        
{
$UserId = $mysqli->real_escape_string($fileop[1]);
$itemTitle = $mysqli->real_escape_string($fileop[12]);

$UserId = mb_convert_encoding($UserId, "UTF-8", "Windows-1252");
$itemTitle = mb_convert_encoding($ItemTitle, "UTF-8", "Windows-1252");
           				
$query = "INSERT into holding_csv
                                        
(userID ,itemTitle)  

Open in new window

0
Hi,

Could someone please help me.

What i need to do, is convert the below to a proper snippet I can use in my php to do the curl post and post up different field values as required.  I exported this from postman.


your help is very much appreciated!!
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://someapi.com",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"template\"\r\n\r\nHi {{name}}! Click here {{url}} to pay your outstanding account.\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"file\"; filename=\"C:\\xampp\\htdocs\\test.csv\"\r\nContent-Type: text/csv\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\nTESTUPLOAD-1\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer XYZ",
    "Cache-Control: no-cache",
    "Postman-Token: 137a61fa-24dc-493e-9686-5e455d4d8a78",
    "content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

Open in new window

0
Wordpress PHP to show certain content not working all of the time.

I have a block of PHP IF code to show a certain form on certain pages.  Some pages it works on but others it does not.
The very first one: is_page(15361) // Messages does ot work and I have double checked that it is the correct ID number.  It is a child of another page but most of the below are.  I have moved that OR statement around and if I try to add any additional OR statements they won't work either and I have confirmed the page ID
<?php
if (
        is_home() // blog
        || is_page(15361) // Messages
        || is_page(18835) 
        || is_page(17880) // solutions
        || is_page(13339) // approach
        || is_page(17956) // create-value
        || is_page(15501) // resources
        || is_page(17973) // capture-value
        || is_page(17967) // elevate-value
        || is_archive('cv_case_study') // customers
        || is_page(15471) // books
        || is_page(15718) // customers
        || is_page(15845) // results
        || is_page(15467) // community
        || is_page(15288) // about
        || is_page(19553) //  Expand Value
) {
    ?>


    <div class="row row-bleed footerform">
        <section class="cta cta_contact" style="background-image:url('/wp-content/uploads/2017/11/Full-Bubble.png')">
    <?php $cta_contact_headline = "Let&rsquo;s Have a Conversation"; ?>
    <?php $cta_contact_subhead = "We exist to help you win."; ?>
    <?php $cta_contact_description = 

Open in new window

0
I'm looking for a PHP bootcamp but mostly I find Ruby. Is there any good online PHP bootcamps that arent Udemy or some other video-only school?
0
Need to create a page in WordPress that would connect to the API and display a search form and list of items from an external API:

Example that needs to be achieved:

http://www.pharmachoice.com/health-advice/medical-conditions

Info about Webservices:

Conditions
Specification: http://webservice.mediresource.com/mridisease.asmx?WSDL

URL: http://webservice.mediresource.com/mriDisease.asmx?op=GetDiseaseInfo

Changeable Variables:
•      strDiseaseInput – any text string (ie. cancer, blood, nose, etc.)
•      intDiseaseID – disease id
•      strAlpha – letter of the alphabet (ie. a, b, c, etc.)

Set Variables
•      intChannelID = 0
•      intLanguageId = 0 (English) / 1 (French)
•      intCountryID = 0
•      strWsKey = {removed}
•      intCaptureOne = 0
•      intCaptureTwo = 0
•      intCaptureThree = 0
•      intCaptureFour = 0
•      intCaptureFive = 0

I have not had the chance to work with API's in the past, so any insight will be very helpful.

Thank you very much!
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.