Перейти к содержимому

Php как вставить переменную в строку

  • автор:

Как вставить значение переменной внутрь строки?

Пишу класс соединения с базой, в котором есть метод подключения, выборки из таблицы, вставки в таблицу новых данных. Со вставкой возникла проблема: появляется ошибка следующего характера:

Parse error: syntax error, unexpected ‘$rowNews’ (T_VARIABLE) in C:\xampp\htdocs\sait12.loc\controller.php on line 24

Я так понял, что это просто синтаксическая ошибка, что-то с кавычками, наверное. Пробовал и в двойных, и без них вообще — не помогает. Подскажите, в чём может быть дело, или научите как найти, что не так. Код класса:

class DB_connect < protected $host = 'localhost'; protected $baza = 'moya2'; protected $user = 'admin123'; protected $pass = '123'; protected function __construct() < $connect = mysql_connect($this->host, $this->user, $this->pass); mysql_query("SET NAMES 'utf8';"); mysql_query("SET CHARACTER SET 'utf8';"); mysql_query("SET SESSION collation_connection = 'utf8_general_ci';"); mysql_select_db($this->baza); > public function getArticles() < self::__construct(); $row_articles = mysql_query('SELECT * FROM articles'); return $row_articles; >public function insert($rowNews) < self::__construct(); $addNews = "INSERT INTO articles (title, title_en, text, author, hashteg) VALUES('"$rowNews['title']"', '"$rowNews['title_en']"', '"$rowNews['text']"', '"$rowNews['author']"', '"$rowNews['hashteg']"')"; $result = mysql_query($addNews) or die(mysql_error()); mysql_close(self::__construct()->$connect); > > 

Доработал немного код. попытался добавить некую фильтрацию данных на входе и воспользовался конкатенацией. Народ если у кого будет время и желание гляньте код. В правильном ли направлении я вообще двигаюсь? Есть конечно очень сильное ощущение что операции с базой типа выбрать, взять, вставить, обновить, удалить должны быть в отдельном классе. Так ли это?)) заранее спасибо за ответы.

class DB_connect < /*Задаю свойства класса*/ protected $host = 'localhost'; protected $baza = 'moya2'; protected $user = 'admin123'; protected $pass = '123'; private $connect = null; /*Правильно ли так задавать свойство для соединения с базой?*/ /*Конструктор для подключения к базе данных*/ public function __construct() < $this->connect = mysql_connect($this->host, $this->user, $this->pass); mysql_query("SET NAMES 'utf8';"); mysql_query("SET CHARACTER SET 'utf8';"); mysql_query("SET SESSION collation_connection = 'utf8_general_ci';"); mysql_select_db($this->baza); > /*Метод закрытия соединения с базой данных*/ public function Close() < if($this->connect) < mysql_close($this->connect); echo 'Соединение с базой данных закрыто'; > > /*Метод получения данных из таблицы articles*/ public function getArticles() < self::__construct(); $row_articles = mysql_query('SELECT * FROM articles'); return $row_articles; self::Close(); >/*Метод вставки статьи в таблицу articles*/ public function insert($rowNews) < $rowNews = filter_var_array($rowNews);/*Попытка фильтрации входных данных*/ self::__construct(); $addNews = "INSERT INTO articles (title, title_en, text, author, hashteg) VALUES('".$rowNews['title']."', '".$rowNews['title_en']."', '".$rowNews['text']."', '".$rowNews['author']."', '".$rowNews['hashteg']."')"; $result = mysql_query($addNews) or die(mysql_error()); self::Close(); >> 

strval

Возвращает строковое значение переменной. Смотрите документацию по типу string для более подробной информации о преобразовании в строку.

Эта функция не производит форматирование возвращаемого значения. Если необходимо привести числовое значение к строке с особым форматом, воспользуйтесь sprintf() или number_format() .

Список параметров

Переменная, которую необходимо преобразовать в строку.

value может быть любого скалярного типа, null или объектом ( object ), который реализует метод __toString(). strval() нельзя применить к массиву или объекту, которые не реализуют метод __toString().

Возвращаемые значения

Строковое значение ( string ) параметра value .

Примеры

Пример #1 Пример использования strval() с магическим методом PHP __toString().

class StrValTest
public function __toString ()
return __CLASS__ ;
>
>

// Выводит ‘StrValTest’
echo strval (new StrValTest );
?>

Смотрите также

  • boolval() — Возвращает логическое значение переменной
  • floatval() — Возвращает значение переменной в виде числа с плавающей точкой
  • intval() — Возвращает целочисленное значение переменной
  • settype() — Задаёт тип переменной
  • sprintf() — Возвращает отформатированную строку
  • number_format() — Форматирует число с разделением групп
  • Манипуляции с типами
  • __toString()

User Contributed Notes 9 notes

7 years ago

Some notes about how this function has changed over time, with regards the following statement:

> You cannot use strval() on arrays or on objects that
> do not implement the __toString() method.

In PHP 5.3 and below, strval(array(1, 2, 3)) would return the string «Array» without any sort of error occurring.

From 5.4 and above, the return value is unchanged but you will now get a notice-level error: «Array to string conversion».

For objects that do not implement __toString(), the behaviour has varied:

PHP 4: «Object»
PHP 5 < 5.2: "Object id #1" (number obviously varies)
PHP >= 5.2: Catchable fatal error: Object of class X could not be converted to string

16 years ago

As of PHP 5.2, strval() will return the string value of an object, calling its __toString() method to determine what that value is.

19 years ago

If you want to convert an integer into an English word string, eg. 29 -> twenty-nine, then here’s a function to do it.

Note on use of fmod()
I used the floating point fmod() in preference to the % operator, because % converts the operands to int, corrupting values outside of the range [-2147483648, 2147483647]

I haven’t bothered with «billion» because the word means 10e9 or 10e12 depending who you ask.

The function returns ‘#’ if the argument does not represent a whole number.

$nwords = array( «zero» , «one» , «two» , «three» , «four» , «five» , «six» , «seven» ,
«eight» , «nine» , «ten» , «eleven» , «twelve» , «thirteen» ,
«fourteen» , «fifteen» , «sixteen» , «seventeen» , «eighteen» ,
«nineteen» , «twenty» , 30 => «thirty» , 40 => «forty» ,
50 => «fifty» , 60 => «sixty» , 70 => «seventy» , 80 => «eighty» ,
90 => «ninety» );

function int_to_words ( $x ) global $nwords ;

if(! is_numeric ( $x ))
$w = ‘#’ ;
else if( fmod ( $x , 1 ) != 0 )
$w = ‘#’ ;
else if( $x < 0 ) $w = 'minus ' ;
$x = — $x ;
> else
$w = » ;
// . now $x is a non-negative integer.

if( $x < 21 ) // 0 to 20
$w .= $nwords [ $x ];
else if( $x < 100 ) < // 21 to 99
$w .= $nwords [ 10 * floor ( $x / 10 )];
$r = fmod ( $x , 10 );
if( $r > 0 )
$w .= ‘-‘ . $nwords [ $r ];
> else if( $x < 1000 ) < // 100 to 999
$w .= $nwords [ floor ( $x / 100 )] . ‘ hundred’ ;
$r = fmod ( $x , 100 );
if( $r > 0 )
$w .= ‘ and ‘ . int_to_words ( $r );
> else if( $x < 1000000 ) < // 1000 to 999999
$w .= int_to_words ( floor ( $x / 1000 )) . ‘ thousand’ ;
$r = fmod ( $x , 1000 );
if( $r > 0 ) $w .= ‘ ‘ ;
if( $r < 100 )
$w .= ‘and ‘ ;
$w .= int_to_words ( $r );
>
> else < // millions
$w .= int_to_words ( floor ( $x / 1000000 )) . ‘ million’ ;
$r = fmod ( $x , 1000000 );
if( $r > 0 ) $w .= ‘ ‘ ;
if( $r < 100 )
$word .= ‘and ‘ ;
$w .= int_to_words ( $r );
>
>
>
return $w ;
>

?>

Usage:
echo ‘There are currently ‘ . int_to_words ( $count ) . ‘ members logged on.’ ;
?>

18 years ago

I can’t help being surprised that

evaluates to true. It’s the same with strval and single quotes.
=== avoids it.

Why does it matter? One of my suppliers, unbelievably, uses 0 to mean standard discount and 0.00 to mean no discount in their stock files.

16 years ago

The only way to convert a large float to a string is to use printf(‘%0.0f’,$float); instead of strval($float); (php 5.1.4).

// strval() will lose digits around pow(2,45);
echo pow(2,50); // 1.1258999068426E+015
echo (string)pow(2,50); // 1.1258999068426E+015
echo strval(pow(2,50)); // 1.1258999068426E+015

// full conversion
printf(‘%0.0f’,pow(2,50)); // 112589906846624
echo sprintf(‘%0.0f’,pow(2,50)); // 112589906846624

18 years ago

It seems that one is being treated as an unsigned large int (32 bit), and the other as a signed large int (which has rolled over/under).

2326201276 — (-1968766020) = 4294967296.

16 years ago

As of PHP 5.1.4 (I have not tested it in later versions), the strval function does not attempt to invoke the __toString method when it encounters an object. This simple wrapper function will handle this circumstance for you:

/**
* Returns the string value of a variable
*
* This differs from strval in that it invokes __toString if an object is given
* and the object has that method
*/
function stringVal ($value)
// We use get_class_methods instead of method_exists to ensure that __toString is a public method
if (is_object($value) && in_array(«__toString», get_class_methods($value)))
return strval($value->__toString());
else
return strval($value);
>

17 years ago

In complement to Tom Nicholson’s contribution, here is the french version (actually it’s possible to change the language, but you should check the syntax 😉 )

function int_to_words($x) global $nwords;

if(!is_numeric($x))
$w = ‘#’;
else if(fmod($x, 1) != 0)
$w = ‘#’;
else if($x < 0) $w = $nwords['minus'].' ';
$x = -$x;
> else
$w = »;
// . now $x is a non-negative integer.

if($x < 21) // 0 to 20
$w .= $nwords[$x];
else if($x < 100) < // 21 to 99
$w .= $nwords[10 * floor($x/10)];
$r = fmod($x, 10);
if($r > 0)
$w .= ‘-‘. $nwords[$r];
> else if($x < 1000) < // 100 to 999
$w .= $nwords[floor($x/100)] .’ ‘.$nwords[‘hundred’];
$r = fmod($x, 100);
if($r > 0)
$w .= ‘ ‘.$nwords[‘separator’].’ ‘. int_to_words($r);
> else if($x < 1000000) < // 1000 to 999999
$w .= int_to_words(floor($x/1000)) .’ ‘.$nwords[‘thousand’];
$r = fmod($x, 1000);
if($r > 0) $w .= ‘ ‘;
if($r < 100)
$w .= $nwords[‘separator’].’ ‘;
$w .= int_to_words($r);

>
> else < // millions
$w .= int_to_words(floor($x/1000000)) .’ ‘.$nwords[‘million’];
$r = fmod($x, 1000000);
if($r > 0) $w .= ‘ ‘;
if($r < 100)
$word .= $nwords[‘separator’].’ ‘;
$w .= int_to_words($r);
>
>
>
return $w;
>

// Usage in English
$nwords = array( «zero», «one», «two», «three», «four», «five», «six», «seven»,
«eight», «nine», «ten», «eleven», «twelve», «thirteen»,
«fourteen», «fifteen», «sixteen», «seventeen», «eighteen»,
«nineteen», «twenty», 30 => «thirty», 40 => «forty»,
50 => «fifty», 60 => «sixty», 70 => «seventy», 80 => «eighty»,
90 => «ninety» , «hundred» => «hundred», «thousand»=> «thousand», «million»=>»million»,
«separator»=>»and», «minus»=>»minus»);

echo ‘There are currently ‘. int_to_words(-120223456) . ‘ members logged on.
‘;

//Utilisation en Francais
$nwords = array( «zéro», «un», «deux», «trois», «quatre», «cinq», «six», «sept»,
«huit», «neuf», «dix», «onze», «douze», «treize»,
«quatorze», «quinze», «seize», «dix-sept», «dix-huit»,
«dix-neuf», «vingt», 30 => «trente», 40 => «quarante»,
50 => «cinquante», 60 => «soixante», 70 => «soixante-dix», 80 => «quatre-vingt»,
90 => «quatre-vingt-dix» , «hundred» => «cent», «thousand»=> «mille», «million»=>»million»,
«separator»=>»», «minus»=>»moins»);

echo ‘Il y a actuellement ‘. int_to_words(-120223456) . ‘ membres connectés.
‘;

Вставка переменных в строки в PHP

В PHP одинарные и двойные кавычки для строк на самом деле не совсем эквиваленты. Дело в том, что в строки в двойных кавычках можно вставлять переменные — и вместо этих переменных подставится их значение.

Давайте попробуем на практике. Пусть у нас есть некоторая переменная:

Давайте для начала выполним вставку этой переменной в какую-нибудь строку через операцию конкатенации:

А теперь изменим кавычки нашей строки на двойные и выполним в нее вставку переменной:

Упростите следующий код:

Php как вставить переменную в строку

В PHP есть два оператора для работы со строками ( string ). Первый — оператор конкатенации («.»), который возвращает строку, представляющую собой соединение левого и правого аргумента. Второй — оператор присваивания с конкатенацией (‘ .= ‘), который присоединяет правый аргумент к левому. Подробно об этом рассказано в разделе «Операторы присваивания».

$a = «Привет, » ;
$b = $a . «Мир!» ; // $b теперь содержит строку «Привет, Мир!»

$a = «Привет, » ;
$a .= «Мир!» ; // $a теперь содержит строку «Привет, Мир!»

Смотрите также

  • Строки
  • Функции для работы со строками

User Contributed Notes 6 notes

11 years ago

As for me, curly braces serve good substitution for concatenation, and they are quicker to type and code looks cleaner. Remember to use double quotes (» «) as their content is parced by php, because in single quotes (‘ ‘) you’ll get litaral name of variable provided:

// This works:
echo «qwe < $a >rty» ; // qwe12345rty, using braces
echo «qwe» . $a . «rty» ; // qwe12345rty, concatenation used

// Does not work:
echo ‘qwerty’ ; // qwerty, single quotes are not parsed
echo «qwe $arty » ; // qwe, because $a became $arty, which is undefined

19 years ago

A word of caution — the dot operator has the same precedence as + and -, which can yield unexpected results.

echo «Result: » . $var + 3;
?>

The above will print out «3» instead of «Result: 6», since first the string «Result3» is created and this is then added to 3 yielding 3, non-empty non-numeric strings being converted to 0.

To print «Result: 6», use parantheses to alter precedence:

echo «Result: » . ($var + 3);
?>

18 years ago

» < $str1 >< $str2 > < $str3 >» ; // one concat = fast
$str1 . $str2 . $str3 ; // two concats = slow
?>
Use double quotes to concat more than two strings instead of multiple ‘.’ operators. PHP is forced to re-concatenate with every ‘.’ operator.

14 years ago

If you attempt to add numbers with a concatenation operator, your result will be the result of those numbers as strings.

echo «thr» . «ee» ; //prints the string «three»
echo «twe» . «lve» ; //prints the string «twelve»
echo 1 . 2 ; //prints the string «12»
echo 1.2 ; //prints the number 1.2
echo 1 + 2 ; //prints the number 3

1 year ago

Some bitwise operators (the and, or, xor and not operators: & | ^ ~ ) also work with strings too since PHP4, so you don’t have to loop through strings and do chr(ord($s[i])) like things.

See the documentation of the bitwise operators: https://www.php.net/operators.bitwise

15 years ago

Be careful so that you don’t type «.» instead of «;» at the end of a line.

It took me more than 30 minutes to debug a long script because of something like this:

The output is «axbc», because of the dot on the first line.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *