Write double quotes in square brackets to mySQL - php

How can I write this into my database field (varchar):
["TEXT"]
I have tried escaping the quotes with backslashes and using double double quotes.
Update
I am using Laravel.
I tried this:
$user = User::create(['email'=> $userEmail,
'name'=> $name,
'customer_id'=> $customer->id,
'things'=> '["TEXT"]'
]);
and this was the result in the db:
"[\"TEXT\"]"

This is how I got I working:
$user = User::create(['email'=> $email,
'name'=> $name,
'email'=> $email,
'customer_id'=> $customer_id,
'things'=> ["TEXT"]
]);

Not really sure what do you mean here.. but simply
INSERT INTO test(varchar_field) VALUES('["TEXT"]'); should help

That's the correct data. When displaying something with double quotes the inner double quotes will need to be escaped with the backslash character. That is:
"[\"TEXT\"]"
Is equivalent to:
'["TEXT"]'
Where no escaping is required because the quotes don't conflict.
This is an artifact of how PHP strings work.
When you test the insertion you should see the result of:
SELECT HEX(things) FROM users WHERE email=?
As showing the actual raw hex data for that column which should be:
5B2254455854225D
Where 5B represents a [ and 5D represents ]. If you're getting 22 at the front and end then for some reason double quotes are actually getting into your column and not just the way PHP displays strings.

Related

Postgresql query returns string values between quotation marks " if it contains any space character or without quotation if it had no space char

so I got this strange issue and I have no idea what's causing it. We are using Charts.js in PHP to plot some charts. We store the arguments needed to create a chart into a PSQL table to load when needed.
My issue lies with the title, group and label parameters which are all string arrays. They are stored in a text[] table. The issue is, when I query a graph's parameter, if a string in the array has any space, it is returned between quotation marks if not it is returned as the string itself.
I have an associative array $graph which stores the graph's parameters and is used to insert the values into the database:
$cursor = $this->query("
INSERT INTO data.graphs(region,title,type,section,label,group,values,colors,id_sample)
VALUES(
'".$graph['local']."',
'".$graph['title']."',
'".$graph['type']."',
'".$graph['section']."',
'".$graph['label']."',
'".$graph['group']."',
'".$graph['values']."',
'".$graph['colors']."',
'".$_SESSION['id_sample']."'
)
");
The string arrays inserted into the DB are like this:
$graph1['label'] = "{Não há material presente,Material presente, mas crianças não usaram,Crianças usaram os materiais}";
$graph2['label'] = "{Boa vista, Rural, Urbana, Indigena}";
$graph3['label'] = "{Boa vista, Ru ral, Urb ana, Ind igena}";
If I query my labels in the database they look like this:
Now to query the data we do a 'SELECT *' for the parameters of each graph needed and store they values associative array again (used as parameter for the Charts.js plotter).
$aux = pg_fetch_array($cursor))
print_r($aux['label']);
This is how my labels look like for each of my 3 graphs:
{"Não há material presente","Material presente, mas crianças não usaram","Crianças usaram os materiais"}
{"Boa vista",Urbana,Rural,Indigena}
{"Boa vista","Urb ana","Ru ral","Ind igena"}
So in the DB the strings have no quotations and if a qstring has a space it is returned between quotation marks which isn't all bad because I want my string in quotation marks.
Is there any way to force each string returned in the array to be inside all quotation marks?
I already tried inserting into the DB an array like this:
$graph['label'] = "{
\"Boa vista\",
\"Urbana\",
\"Rural\",
\"Indigena\"
}";
If I look into the DB the strings have no quotation, they are returned just like above yet again.
That's the default text output for type text[]. The manual:
The array output routine will put double quotes around element values
if they are empty strings, contain curly braces, delimiter characters,
double quotes, backslashes, or white space, or match the word NULL.
Double quotes and backslashes embedded in element values will be
backslash-escaped.
[...] for textual data types one should be prepared to cope with either the presence or absence of quotes.
If you prefer a text representation with all elements double quoted, you could use a simple expression like:
SELECT '"' || array_to_string('{"Boa vista",Urbana,Rural,Indigena}'::text[], '", "') || '"'
If you need it a lot, consider a (simplistic) function:
CREATE OR REPLACE FUNCTION f_array_to_string_with_quotes(_arr text[], _quote text = '"')
RETURNS text LANGUAGE sql IMMUTABLE PARALLEL SAFE AS
$func$
SELECT $2 || array_to_string($1, $2 || ', ' || $2) || $2
$func$;
Call:
SELECT f_array_to_string_with_quotes('{"Boa vista",Urbana,Rural,Indigena}', '"');
| f_array_to_string_with_quotes |
| :----------------------------------------- |
| "Boa vista", "Urbana", "Rural", "Indigena" |
db<>fiddle here - with more examples
Note that the resulting type is now text, not text[]! And it does not properly escape anything, hence "simplistic".

How do I remove quotation from csv?

How do I remove quotation from csv?
Code
use Goutte\Client;
$client = new Client();
$response = $client->request('GET', 'http://c-manage.herokuapp.com/login');
$login_form = $response->filter('form')->form();
$login_form["account"] = '1';
$login_form["password"] = 'rpa1001';
$client->submit($login_form);
$client->request('GET', 'http://c-manage.herokuapp.com/client/download?searchQuery%5Bstatus%5D=1&searchQuery%5BregisterStartDate%5D=2010-01-01&searchQuery%5BregisterEndDate%5D=2020-01-01');
$csvResponse = $client->getResponse()->getContent();
return $csvResponse;
response is ...
ID,ステータス,分類,名前,名前(カナ),誕生日,郵便番号,住所,メールアドレス,電話番号,FAX,メモ,登録日,更新日\r\n
213,契約中,個人,"鶴田 秀夫","ツルタ ヒデオ",2000/07/24,1508207,神奈川県吉田市北区佐々木町小林7-4-5,hiroshi.nakatsugawa#yamaguchi.net,0310-282-609,0730-327-581,,"2010-01-25 00:00:
00","2010-01-25 00:00:00"\r\n
221,契約中,個人,"桑原 彩羅","クワハラ サイラ",2008/04/03,8103797,青森県杉山市西区石田町浜田3-4-10,vwakamatsu#kiriyama.jp,090-5710-4350,03849-5-5746,,"2010-01-09 00:00:00","2010-0
1-09 00:00:00"\r\n
237,契約中,個人,"堤 悟志","ツツミ サトシ",2001/04/29,6875750,栃木県佐々木市東区中島町浜田6-6-6,xtsuda#suzuki.com,022-557-4260,0573-01-2822,,"2010-02-07 00:00:00","2010-02-07 00:0
0:00"\r\n
273,契約中,個人,"富永 圭三","トミナガ ケイゾウ",2003/03/16,6314524,静岡県若松市東区廣川町青山10-9-6,yamaguchi.takuma#kondo.com,0020-062-493,06-3862-0779,,"2010-02-13 00:00:00","2
010-02-13 00:00:00"\r\n
.
.
.
What I want to do
I want to remove quotation from csv.
not
213,契約中,個人,"鶴田 秀夫","ツルタ ヒデオ",2000/07/24,1508207,
but
213,契約中,個人,鶴田 秀夫,ツルタ ヒデオ,2000/07/24,1508207,
※This personal information is fake.
What I did
str_replace(""", "", $csvResponse);
str_replace("\xEF\xBB\xBF", '', $csvResponse);
but, not working
The quotes serve a purpose here so you shouldn't be removing them haphazardly. The quotes prevent columns from breaking when they need to contain text that can also contain the delimiter. Like "Foo, bar, baz" for example. Removing the quotes turns this one column into 3 columns, which is obviously wrong.
Though, if you did want to remove them str_replace would certainly not be the way to go, because the quotes can be escaped to be literals inside the column. For example, using str_replace on this column: "He said \"this is crazy\", and left." would strip literals from the column value.
Instead you should load the CSV data with fgetcsv() or str_getcsv() and rebuild the CSV without the quotes like so...
foreach (str_getcsv($csvData) as $row) {
echo implode(",", $row), "\n";
}
This will give you back the literal values of each row without the quotes. Though any literal quotes inside those values will become quotes.

Joining variable to strings fails in PHP

I'm sorry that this is basic. When I use this PHP code it works fine:
$data = '{"reportID":1092480021}';
However, when I run my URL like this:
http://localhost:8000/new/reportget.php?type=1092480021
and use this PHP code:
$reportref = $_GET['type'];
$data = '{"reportID:".$reportref."}"';
I get the error
Error_description:reportID is required
I think it's an error with how I am joining my variable to the string but I can't understand where I am going wrong.
Your string is improperly quoted. To match the format in your first example use:
$data = '{"reportID":' . $reportref.'}';
Note there are no double quotes on the last curly.
Even better:
$reportref = 1092480021;
$data = [ 'reportId' => $reportref ];
var_dump(json_encode($data));
Output:
string(23) "{"reportId":1092480021}"
For simple view and understanding, can you try out:
$data = "{\"reportID\":$reportref}";
Think that should sort it out
Use it like this
data = '{"reportID:"'.$reportref.'"}"';
It isn't working because you wrap all the value within single quote and when it come to concatenate the $reprtref you put directly .$reportref without closing the first single quote and after putting the value to concatenate you forget to open another single quote
'{"reportID:".$reportref."}"';
the correct value is
'{"reportID:"' . $reportref . '"}"';
and to match the way you specify your $data value It must be like this
'{"reportID":' . $reportref . '}';

Enclose PHP output in quotation marks

we have a PHP script that exports orders to .csv files. The system we are exporting too requires each field to be encapsulated in quote marks.
Here is the code where we set each field.
$order_data = array(
'type' => "H",
'order_type' => 'HOME',
'order_date' => $order->order_date,
'account_code' => "REAL",
'document_reference' =>'',
'reference1'=>'',
'reference2'=>'',
'delivery_addess_code'=> '',
'billing_first_name' => $order->billing_first_name ." ".$order->billing_last_name,
'billing_address_1' => $order->billing_address_1 ." ".$order->billing_address_2,
'billing_postcode' => $order->billing_postcode,
'delivery_tel_no'=> $order->billing_phone,
'delivery_contact'=> $order->billing_first_name,
This outputs;
H,HOME,"2015-05-13 13:19:46",REAL,,,,,"Ben Bull","Address 1 Address2",
Some are surround by "" and some aren't how do we get them all to be?
For CSV output, you need to enclose all the values with double quotes. In addition, if the values have double quotes inside them you need to escape those double quotes by using two consecutive double quotes. That's how CSV works.
Check this PHP function below.
function makeCSV($value) {
//Encloses each token (Before and after)
$CSV_TOKEN_ENCLOSER = '"';
//Used to escape the enclosing character if inside the token
$CSV_TOKEN_ENCLOSER_ESCAPER = '""';
//Escape the encloser inside the value
$csv_value = str_replace($CSV_TOKEN_ENCLOSER, $CSV_TOKEN_ENCLOSER_ESCAPER, $value);
//Enclose the value
$csv_value .= $CSV_TOKEN_ENCLOSER . $csv_value . $CSV_TOKEN_ENCLOSER;
//Return
return $csv_value;
}
This does the job as I've explained in the first paragraph. You can use it as such in your case:
$order_data = array(
'type' => makeCSV("H"),
'order_type' => makeCSV('HOME'),
'order_date' => makeCSV($order->order_date),
...
);
However, it looks like you have code that's enclosing the values from your order objects within quotes automatically for you. I suggest you avoid that code, replace that with the usage of the makeCSV function presented above, and then finally just use a standard PHP implode call to get your CSV like this:
$comma_separated_csv = implode(",", $order_data);
Hope this helps.
Cheers.
Try to force all types to string like:
'order_type' => (string) 'HOME'

PHP making an URL link work inserting the $variables the right syntax way

I have this link that works.
echo '<a href="?country=Estonia&from_language=Russian&into_language=Latvian&submitted=true&
page='.$x. '">'.$x.'</a> ';
But I need the nouns Estonia, Russian and Latvian replaced by scalar variables like $country, $from_language, $into_language.
I have tried all possible combinations of dots and single and double quotes. I always get syntax errors. I don't know how the embed the variables there.
Anybody knows?
thank you
Do yourself a massive favour and use http_build_queryDocs:
<a href="?<?php echo http_build_query(array(
'country' => $country,
'fromLanguage' => $fromLanguage,
'somethingElse' => $somethingElse,
'...' => '...'
), '', '&'); ?>">Link</a>
use something easy one like sprintf or printf.
eg:
printf('<a href="?country=%s&from_language=%s&into_language=%s&submitted=true&
page=%s">%s</a>', $country, $fromLanguage, $toLanguage, $pageID, $dispText);
You could also use something like encoding with double quote sign like:
echo "<a href=\"?country={$country}&from_language={$fromLanguage}&into_language={$toLanguage}&submitted=true&
page={$pageID}\">{$dispText}</a>"
Avoid to put variables directly into string when not extremely simple. Use concatenation instead, and escape string if you want to make something good:
echo '<a href="?country=' . htmlentities($country) .
'&from_language=' . htmlentities($from_language) .
'&into_language=' . htmlentities($into_language) .
'&submitted=true&page=' . intval($x) . '">' . htmlentities($x) . '</a> ';
Anyway, if you really want it the complex way, you have to consider that you need doble quotes for HTML attributes, but double quotes are needed to wrap the PHP string because you want to put variables in it. So, you must escape HTML double quotes. Try:
echo "' . $x . ' ';
Combining the answers of Corbin and KoolKabin gives you this easy-to-read snippet:
printf('%s',
htmlspecialchars(
http_build_query(array(
'country' => $country,
'from_language' => $from_language,
'into_language' => $into_language,
'submitted' => 'true',
'page' => $x
))
),
htmlspecialchars($x));
Parametrization
printf and sprintf are very useful for adding parameters to strings. They make it easy to add escaping or complex values without making the string itself unreadable. You can always see at a glance what string it is by the first parameter.
http_build_query is also a way of parametrizing, but for the querystring. The main use is that you don't need to focus on the syntax of querystrings at all.
Escaping
htmlspecialchars makes sure that the data is fit for insertion into HTML code. It's similar to escaping in SQL queries to avoid SQL injections, only here we want to avoid HTML injections (also called XSS or cross-site scripting).
http_build_query will automatically make sure that all values are escaped for insertion as an URL in the address field in a browser. This does not guarantee fitness for insertion into HTML code. htmlspecialchars is therefore needed for the querystring as well!
If you scripts output HTML, consider to configure the output setting for argument separators arg_separator.output:
ini_set('arg_separator.output', '&');
You can then simply create the URI query info path by using http_build_query:
$country = 'de';
$fromLanguage = 'en_EN';
?>
Link
Which will give you a perfectly validly encoded output, which is immune to injections:
Link
Full Demo
$country = 'Estonia';
$from_language = 'Russian';
$into_language = 'Latvian';
echo ''.$x.' ';
OR
echo "$x";
OR
echo "{$x}";

Categories