A php script I have is extracting data from an XML file to a MySQL database.
It is set-up as followed:
$sql = "INSERT IGNORE INTO `tablename` (columnname) VALUES ('text text text text text text $variablename text text $variablename2 text text')
$variablename and $variablename2 are both variables being extracted from the XML file, and have varying lengths.
So, I know, if I was just dealing with PHP I could use strlen or a variation of (see How to Truncate a string in PHP to the word closest to a certain number of characters? but 'columnname' in my sql database is not a variable.
And 'columnname' is what is limited to the characters.
I set this in mySQL to VARCHAR MAX=106 -- and that works --
But when re-outputting this to my web host it takes the data from the SQL database which is stopped at the maxlength cut-off mid-word.
I want it so that if it does reach the maxlength, the last word is just removed.
Could this be done, perhaps when inputting into the SQL table?
Or even perhaps in the PHP file outputting back to my web host?, such as here:
$rs->data_seek(0);
while($res = $rs->fetch_assoc()) {
$a_topic = array(
"columnname" => $res["columnname"]
or maybe in the $params here?
$params = array(
'status' => $share['columnname'],
Big thanks!
function cut($string, $maxLength)
{
$revertString = strrev($string);
$spaceRevertedPos = strpos($revertString, ' ', strlen($string)-$maxLength);
$revertedCutString = substr($revertString, $spaceRevertedPos);
return strrev($revertedCutString);
}
DEMO
Related
I've got a database search field where I want the user to be able to input simple boolean logic and have that translated to a mySQL search string.
So for instance if the user inputs: (php AND mysql) OR ajax
I'd like to convert that to:
((c.Skillset LIKE '%php%' AND c.Skillset LIKE %mysql%) OR c.Skillset LIKE '%ajax%')
Is there a fairly simple way of doing this? I'm having particular trouble coming up with a solution for the brackets, if it wasn't for that it would be quite straightforward.
The following assumes you have some constant called SQL_PREFIX_STRING defined.
$string = '(php AND mysql) OR java';
preg_match_all('/[a-z]+/', $string, $skills); // puts the skills in an array
$skills = $skills[0]; // shift array to get the matching values
array_walk($skills, function (&$skill) {$skill = '%'.$skill.'%';}); // add wildcards to parameters
$query_string = preg_replace('/[a-z]+/', 'c.Skillset LIKE ?', $string); // create the ? parameters for the SQL string
$pdoStatement = $pdo->prepare(SQL_PREFIX_STRING.$sql); // prepare
$pdoStatement->execute($skills); // execute
I'm encoding array of Image URLS into json string and store them in database. (utf8_general_ci).
When I insert data into table and retrive it, json_decode() is capable of decoding it.
However, when I copy data from one table to another (INSERT INTO ... SELECT statement) data after retrieving from database cannot be decoded anymore.
Instead, i get corrupted json ENCoded string. Even empty array [] cannot be properly decoded.
It converts from http://pl.tinypic.com/r/fwoiol/8
into http://pl.tinypic.com/r/bgea05/8
(had to make images since those squares cannot be copied as text).
Edit, After checking a bit more i tried to bin2hex() both strings from database.
Both seem to be exactly same.
However, one decodes and one does not. The
5b22687474703a5c2f5c2f7777772e
changes into
0022687474703a5c2f5c2f7777772e
So, json_decode only changes 5b into 00 in string.
It's like It's losing encoding somewhere?
Edit 2
static public function jsonDecodeFieldsArray($entries, $fields = array('features','images')){
foreach($entries as $key => $entry){
$entries[$key] = self::jsonDecodeFields($entry, $fields);
}
return $entries;
}
static public function jsonDecodeFields($entry, $fields = array('features','images')){
foreach($fields as $field){
if(isset($entry[$field])){
$entry[$field] = json_decode((string) $entry[$field], true);
}
}
return $entry;
}
I'm using code above, to decode keys of array specified by $fields. However, it not only decodes wrongfully. But also affects keys that are not listed in $fields. Corrupting their encodings.
More to add. If I dont use those functions and use only json_decode on fields json_decode($array[0][images], true) it works fine.
To Clarify that I found answer/solution I write this Answer
The reason behoind this error was not SQL error and data was proper. I had an example array of:
$many_entries = array(
array(
'features' = > 'json_encoded_string'
'images' = > 'json_encoded_string'
),
array(
'features' = > 'json_encoded_string'
'images' = > 'json_encoded_string'
)
);
// And
$one_entry = array(
'features' = > 'json_encoded_string'
'images' = > 'json_encoded_string'
);
Now I had 2 functions. One to Parse $many_entries (jsonDecodeFieldsArray) array and one to Parse $one_entry array structure (jsonDecodeFields).
The problem was I used jsonDecodeFieldsArray on $one_entry which made jsonDecodeFields iterate on strings.
It is odd that the character encoding is changing through the transmission. I would say check your charset(s) in PHP but you said the issue is only occurring in a table => table SQL transfer. I would still check the charset of the column / table.
You can fix the issue by running a str_replace() upon decoding. For example:
$DB_ARRAY = $DB_QUERY->fetch_array();
$CORRECT_ENCODING = json_decode(str_replace('0x93', '[', $DB_ARRAY['urlstring']), true);
You would, of course, need to know what the wrongly encoded character is. Or its ASCII code equivalent.
I have a column within my MySQL database which stores a product description that includes non-alphanumeric characters. I'm trying to run a PHP dump of various fields within the datebase using my Apache Server - and I would like to remove all of the non-alphanumeric characters from the product description before being returned.
// load all stock
while ($line = mysql_fetch_assoc($result) ) {
?>
<?
$size = '3';
// check if size is available
if($line['quantity_size_'.$size.''] > 0 ) {
?>
<?=$line['product_id']?>,
<?=$line['code_size_'.$size.'']?>,
EAN,
<?=$line['title']?>,
<?=$_GET['brand']?>,
<?=$_GET['brand']?>,
**<?=$line preg_replace('/[^\da-z]/i', '', ['amazon_desc']),**
<?=$size?>,
<?=$line['colour']?>,
....
I've emboldened the relevant line above - this seems to return a T_String error.
Any body help?
Thanks
A
<?=$line preg_replace('/[^\da-z]/i', '', ['amazon_desc']),
should be:
<?=preg_replace('/[^\da-z]/i', '', $line['amazon_desc']) ?>
This basic function calling syntax, I don't know where you got the idea that you could be the array name before the function, and the index inside the arguments.
I want to store strings in a TEXT column in MySQL.
The strings mostly consists of which is the main problem, MySQL (and CodeIgniter) converts them to spaces. And they are important because the string only makes sense with the appropriate amount of spacing.
I considered converting to <div class='whitespace'></div> so that I can style with CSS, but it will make the MySQL column bigger.
So how can I efficiently store such a string in MySQL database?
Thanks for any help !
Use htmlentities (http://www.php.net/htmlentities)
echo htmlentities('Hi there');
// outputs
// Hi there
echo 'Hi there';
// outputs
// Hi there
If you want to decode instead (the reverse) you can use html_entity_decode().
http://www.php.net/manual/en/function.html-entity-decode.php
Consider tobase64_encode the data before inserting it in mysql.
$bigstr = base64_encode($bigstr);
/* insert to database */
Remember to base64_decode when fetching the string back.
Create two functions:
function getRawString($str) {
return strtr($str, array(" " => " "));
}
function getDisplayString($str) {
return strtr($str, array(" " => " "));
}
Store the raw string in the database:
$str = file_get_contents('html_file.html');
$query = "INSERT INTO table_name (my_text) VALUES ('" . getRawString($str) . "')";
// Execute query...
Fetch it from the database and display it:
echo getDisplayString($strFromDB);
I have some columns in my table, descriptions column contains some information like;
a1b01,Value 1,2,1,60|a1b01,Value2,1,1,50|b203c,Value 1,0,2,20
with a SQL command, i need to update it.
In there, I'll use a PHP function for updating, if first and second parameters exist in current records (in description column) together.
Eg: if user wants to change the value of description that includes a1b01,Value 1 I'll execute a SQL command like that;
function do_action ($code,$value,$new1,$new2,$newresult) {
UPDATE the_table SET descriptions = REPLACE(descriptions, $code.','.$value.'*', $code.','.$value.','.$new1.','.$new2.','.$newresult)";
}
(star) indicates that, these part is unknown (This is why i need a regex)
My question is : how can i get
a1b01,Value 1,2,1,60|
part from below string
a1b01,Value 1,2,1,60|a1b01,Value2,1,1,50|b203c,Value 1,0,2,20
via regex, but a1b01 and Value 1 should be get as parameter.
I just want that; when I call do_action like that;
do_action ("a1b01","Value 1",2,3,25);
record will be : a1b01,Value 1,2,3,25|a1b01,Value2,1,1,50|b203c,Value 1,0,2,20(first part is updated...)
You don't necessarily need to use a regular expression to do this, you could use the explode function since it is all delimited
So you could do as follows:
$descriptionArray = explode('|', $descriptions); //creates array of the a1b01,Value 1,2,1,60 block
//then for each description explode on ,
for($i = 0; i < count($descriptionArray); $i++){
$parameters = explode(',', $descriptionArray[$i]);
do_action ($parameters[0],$parameters[1],$parameters[2],$parameters[3],$parameters[4]);
}