I am dealing with long queries in PHP, so that I need to write it on multiple lines, but I don't know if their any line continuation character is available in PHP.
I used the same in VB.NET as furnished below:
sql = "SELECT stoks,srate,prate,taxp," & _
"iname,suplier,icod FROM stock where iname='" & item_name.Text & "'" & _
"and suplier ='" & suplier.Text & " '"
Is there any similar operation available in PHP, for denoting line continuation?
In PHP, once you don't close the quotation, you can write your code on multiple lines. Example:
$sql = "select stoks,srate,prate,taxp,
iname,suplier,icod from stock where iname='".$item_name."'
AND suplier ='".$suplier." '";
mysql_query($sql);
PHP is different from the various versions of VB in that it uses a line termination character. (http://php.net/manual/en/language.basic-syntax.instruction-separation.php) As such there is no line continuation character required. Your long strings can just continue from line to line with no need to close the quotation.
$sql = "select stoks,srate,prate,taxp,
iname,suplier,icod from stock where iname='".$item_name."'
AND suplier ='".$suplier." '";
Or you can close the quotation block and connect it to another one using the period concatenation operator "."
$sql = "select stoks,srate,prate,taxp," .
"iname,suplier,icod from stock where iname='" . $item_name . "'" .
" AND suplier ='" . $suplier . " '";
A third way to accomplish the same goal is to use the concatenation assignment operator. (http://php.net/manual/en/language.operators.string.php)
$sql = "select stoks,srate,prate,taxp,";
$sql .= "iname,suplier,icod from stock where iname='".$item_name."'";
$sql .= " AND suplier ='".$suplier." '";
There are other ways to accomplish the same idea, but these seem to be the most popular.
PHP doesn't require it, but you can also concatenate strings in a similar fashion:
$myString = "Hello my name is john I am a super cool dude that likes cheese" .
"I also like milk" .
"I also like the number 8";
Current answers explain how to continue a concatenation. But what about any other expression, like a + b + c + ... ;?
You can use parenthesis to achieve expression continuation (which includes the concatenation). So, you can write expressions like:
# A chain of conditions
$apply = (
$condition1
&& $condition2
&& $conditionn);
# your example sql expression
$sql = (
"select stoks,srate,prate,taxp,"
. "iname,suplier,icod from stock where iname='"
. item_name.Text
. "'"
. "and suplier ='"
. suplier.Text
. " '");
Another solution is to use output buffering, you can collect everything that is being outputted/echoed and store it in a variable.
line1
line2
line3<?php
$xml = ob_get_clean();
Please note that output buffering might not be the best solution in terms of performance and code cleanliness for this exact case but worth leaving it here for reference.
Related
The SQL field that I try to add is TIME format.
My table looks like this:
table example
The code that I use looks something like this:
<code>
$sql = mysql_query("SELECT sec_to_time(sum(durata)) as durata FROM invoiri WHERE inginer= '" . $inginer."' and data between '" . $data1."' and '" . $data2."'");
$assoc = mysql_fetch_array($sql);
echo "Total time by ".$inginer." in period (".$data1.")-(".$data2.") is: ".$assoc[durata]." hours";}}
</code>
And the output that I get is " 05:33:20 " when it should be " 02:00 "
You almost have the right solution there. The problem is that the durata column is also a TIME column, and SUM() works on integers not TIME.
To get the correct result you can use:
$sql = mysql_query('SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(`durata`))) AS `durata` FROM `invoiri` WHERE inginer= "' . $inginer. '" AND `data` BETWEEN "' . $data1 . '" AND "' . $data2 . '"';
$assoc = mysql_fetch_array($sql);
echo 'Total time by ' . $inginer . ' in period (' . $data1 . ')-(' . $data2 . ') is: ' . $assoc[durata] . ' hours';
Also, a few of other things that you can improve about your code:
Stop using the MySQL extension for PHP. It has been deprecated since PHP 5.5 and completely removed in PHP 7. Instead have a look at MySQLi or PDO.
Don't use " for strings where you don't use string interpolation. You can see how I replaced all of your " (double quote) with ' (single quote). String processing is faster if you use just single quotes as PHP isn't trying to find something to interpolate every time.
Try to have your MySQL code more organized and use backticks for column names, and capitalize all of the MySQL syntax. I have modified your code as an example.
I am using Notepad++ to do some HTML and PHP. At one point, I have the following code:
$strUserEmail = $_SESSION["userLoggedIn"];
$strSQL = "SELECT * FROM customer WHERE Email = '$strUserEmail'";
$rsUser = mysql_query($strSQL)
or die($db_name . " : " . $strSQL . " : " . mysql_error());
$rowUser = mysql_fetch_array($rsUser);
$strUserName = $rowUser["FirstName"] . '.' . mb_substr($rowUser["LastName"], 0);
What should come out of that is, for instance, Tom S (Tom being the first name, and S being the first letter of the last name). However, it simply gives me the full last name.
As a second issue, I am using $strUserName to seed a text box in a form following this, but whenever a space is encountered, is ignores the rest as some sort of delimiting value.
You ommited length param in mb_substr() function. Read the doc.
You shouldn't be using mysql_* functions any more as they are deprecated and very unsafe, please learn & use mysqli_* : http://www.php.net/manual/en/book.mysqli.php
Secondly, you have to supply a length to mb_substr, passing the default Null will be interpreted as 0.
try:
$strUserName = $rowUser["FirstName"] . '.' . mb_substr($rowUser["LastName"], 0, 1);
You can also achieve that by using substring method.
$strUserName = $rowUser["FirstName"] . ' ' . substr($rowUser["LastName"], 0, 1);
echo $strUserName;
Edit. Thanks to # czachor making me notice about this.
If you working with unicode charachters, the above function may not work perfectly for you, because the substr() function is not mutli-byte aware. For instance if you are in German, there are umlauts, like Ä,ö ß and so son. So you can better use the mb_substr() like the following.
$strUserName1 = $rowUser["FirstName"]. ' ' . mb_substr($rowUser["ÖLastName"], 0, 1,'UTF-8');
echo utf8_decode($strUserName1);
I need help with my PHP, I'm using str_ireplace() and I want to filter something out and replace it with what I have.
I find it hard to explain what I am talking about so I will give an example below:
This is what I need
$string = "<error> " . md5(rand(0, 1000)) . time() . " </error> Test:)";
then I want to remove and replace the whole <error> .... </error> with nothing.
So the end outcome should just print 'Test:)'.
Your question is not perfectly clear, but I believe I may understand what you are asking. This code may do the trick:
$string = " " . md5(rand(0, 1000)) . time() . " Test:)";
$newstring = preg_replace("/.*?\ /i", "", $string);
This uses regular expressions to filter out everything that comes before the space (and also removes the space)
I have a PHP echo statement:
echo "stores[".$row['BarID']."] = [". $row['BarName'] . ", " . $row['Address']. ",". $row['City']. "," . $row['State']. " 0". $row['ZipCode']. "," . $row['PhoneNumber']. ",". $row['Lattitude']. ",".$row['Longitude']. "]". ";<br>";
which outputs:
stores[0] = [The Ale 'N 'Wich Pub , 246 Hamilton St ,New Brunswick,NJ 08901,732-745-9496 ,40.4964198,-74.4561079];
BUT I WOULD LIKE THE OUTPUT IN DOUBLE QUOTES SUCH AS:
stores[0]=["The Ale 'N 'Wich Pub", "246 Hamilton St, New Brunswick, NJ 08901", "732-745-9496 Specialty: Sport", "40.4964198", "-74.4561079"];
I Have looked at the PHP String Functions Manual on PHP site but still don't understand how i can implement it. Your help is appreciated.
The keyword you miss is "escaping" (see Wiki). Simplest example:
echo "\"";
would output:
"
EDIT
Basic explanation is - if you want to put double quote in double quote terminated string you MUST escape it, otherwise you got the syntax error.
Example:
echo "foo"bar";
^
+- this terminates your string at that position so remaining bar"
causes syntax error.
To avoid, you need to escape your double quote:
echo "foo\"bar";
^
+- this means the NEXT character should be processed AS IS, w/o applying
any special meaning to it, even if it normally has such. But now, it is
stripped out of its power and it is just bare double quote.
So your (it's part of the string, but you should get the point and do the rest yourself):
echo "stores[".$row['BarID']."] = [". $row['BarName'] . ", " . $row['Address'] .
should be:
echo "stores[".$row['BarID']."] = [\"". $row['BarName'] . "\", \"" . $row['Address']. "\"
and so on.
The following code gives me the following:
$getexpenses = "SELECT sum(expense_amount) FROM projects_expense WHERE project_id=$project_id";
$showexpenses = #mysqli_query ($dbc, $getexpenses); // Run the query.
echo ' . $showexpenses . ';
Gives me a result of
' . $showexpenses . '
instead of the actual sum...
I'm sure it's something simple I'm missing... thanks!
echo " . $showexpenses . " will work for you. You need double quotes, not single.
I added a call to mysqli_fetch_assoc($showexpenses)to make it fully functional.
I also sanitized $project_id to avoid injections and used an alias to make the sum accessible through an associative array.
$getexpenses = "SELECT SUM(`expense_amount`) as `sum_amount` FROM `projects_expense` WHERE `project_id`= ".intval($project_id);
$showexpenses = mysqli_query ($dbc, $getexpenses);
$sums = mysqli_fetch_assoc($showexpenses);
$sum = $sums['sum_amount'];
echo $sum;
We could also have used mysqli_fetch_row like this:
$getexpenses = "SELECT SUM(`expense_amount`) FROM `projects_expense` WHERE `project_id`= ".intval($project_id);
$showexpenses = mysqli_query ($dbc, $getexpenses);
$sums = mysqli_fetch_row($showexpenses);
$sum = $sums[0];
echo $sum;
The alias is not needed anymore since we know the first column (0) is a match.
NB: you probably also need to GROUP BY project_id if you want to use SUM()
use
echo $showexpenses;
or
echo "My query is: {$showexpenses}";
Further to Nik's response, PHP treats strings differently based on whether you use Single Quotes or Double Quotes around them.
Single-Quotes interpret text as literal text except for '\'' which would output a single quote mark and '\' which would output a slash mark. For this reason, using single quotes would output your variable name instead of the value.
Examples:
CODE | OUTPUT
-----------------+------------------
echo '\t'; | \t
echo '\r'; | \r
echo '$foo'; | $foo
Double-Quotes interpret certain escape sequences for special characters and also interpret variables. For instance, "\n" ouputs a linefeed and "\r" outputs a carriage return. For this reason, echoing "$myvariable" outputs the value instead of the variable name.
Examples:
CODE | OUTPUT
-----------------+------------------
echo "\t"; | {tab space}
echo "\r"; | {carriage return}
echo "$foo"; | bar
More reading: http://www.php.net/manual/en/language.types.string.php