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);
Related
How can i prevent that PHP converts a recognized part of a string to an html-entity?
So e.g. lets say i have to concat parts together to an url, like:
echo '&' . 'section=' . '<br>';
$a = '&a';
$b = 'mplitude=';
echo "{$a}{$b}" . '<br>';
echo sprintf("%s%s", '"e', '=');
the code above prints the following:
§ion=
&litude=
"e=
instead of:
§ion=
&litude=
"e=
how can this be prevented without throwing filters on it trying to convert the symbols back to an string again?
You need using htmlspecialchars function:
echo htmlspecialchars('&' . 'section=' . '<br>');
i need to convert decimals values into unicode and display the unicode character in PHP.
so for example, 602 will display as this character: ɚ
after referencing this SO question/answer, i was able to piece this together:
echo json_decode('"' . '\u0' . dechex(602) . '"' );
this seems pretty error-prone. is there a better way to do this?
i was unable to get utf8_encode to work since it seemed to want to start with a string, not a decimal.
EDIT: in order to do characters between 230 and 250, double prefixed zeros are required:
echo json_decode('"' . '\u00' . dechex(240) . '"' ); // ð
echo json_decode('"' . '\u00' . dechex(248) . '"' ); // ø
echo json_decode('"' . '\u00' . dechex(230) . '"' ); // æ
in some cases, no zero is required:
echo json_decode('"' . '\u' . dechex(8592) . '"' ); // ←
this seems strange.
While eval is generally to be avoided, it seems strictly-controlled enough to be fine here.
echo eval(sprintf('return "\u{%x}";',$val));
echo json_decode(sprintf('"\u%04x"',$val));
this ultimately worked for me, but i would not have found this without the answer from Niet the Dark Absol
normally, when i attempt to answer my own question, some SO wizard comes along and shows me a built-in function that i should have known about. but until that happens, this is all i can think of:
$leading_zeros = null;
if ( strlen(strval(dechex($val))) >= 4 ) {
$leading_zeros = '';
} else if ( ctype_alpha(dechex($val)[0]) ) {
$leading_zeros = '00';
} else if ( ctype_digit(dechex($val)[0]) ) {
$leading_zeros = '0';
}
echo json_decode('"' . '\u' . $leading_zeros . dechex($val) . '"' );
EDIT: when trying to something similar for javaScript, the documentation tells me the format is supposed to look like "\u####' four digits. i dont know if this is similar to PHP or not.
If you have IntlChar available I'd recommend using IntlChar::chr:
var_dump(IntlChar::chr(602));
Failing that, something like the following avoids any eval/json_decode trickery:
var_dump(iconv('UTF-32BE', 'UTF-8', pack('N', 602)));
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 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.
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)