PHP issues with explode() and SQL query - php

I have a code in PHP like the next:
//$menutype is defined in this point, and no problem with it
$sql = "SELECT struct FROM menutype WHERE id=$menutype;";
$result = mysql_query($sql);
list($struct) = mysql_fetch_row($result);
$menu = explode("\n", $struct); //Explode to make an array with each line
foreach ($menu as $index => $value)
{
//$barid is defined in the top of the document and no issue with it
creatabla($barid, $value);
}
function creatabla($barid, $tipo)
{
$tipo = trim($tipo, ' '); //trim to delete unwanted spaces
$sql = "SELECT name FROM products WHERE tipo LIKE '%$tipo%' AND restaurante='$barid';";
$result = mysql_query($sql);
while(list($name) = mysql_fetch_row($result))
{
echo "$name";
}
}
Similar 'struct' row struct:
Line1
Line2
Line3
Line4AndLastLine
No car return after Last Line.
Well, the code usually works fine, but If I modify the 'Struct' row, some lines won't be read fine, so I usually need to edit the struct row in the advaced editor of the phpmyadmin.
What can I do to solve this issue? Can I try other kind of filter in the sql statement? What can I do to improve the trim or the explode function to solve this issue?
Thanks you to all in advance.

I think I'm starting to understand the issue and I'm guessing you're right - I'm guessing there is a \r character on the end.
Right now you are calling this:
trim($tipo, ' ');
That deletes ONLY spaces. If you change it to simply:
trim($tipo);
Then it will delete a lot more types of whitespace, including (but not limited to) the \r character.
See HERE for more information on the trim() function.

Related

Writing into csv with php problems

I have a problem. I'm trying to get some data from a database into a .csv table.
$fn=fopen($path.$filename, "w");
$addstring = file_get_contents($path.$filename);
$addstring = 'Azonosito;Datum;Ido;Leiras;IP-cim;allomasnév;MAC-cim;Felhasznalonev;Tranzakcioazonosito;Lekerdezes eredmenye;Vizsgalat ideje;Korrelacios azonosito;DHCID;';
/*$addstring .= "\n";*/
$sql="select * from dhcpertekeles.dhcpk";
$result =mysqli_query($conn, $sql);
if ($result=mysqli_query($conn,$sql))
{
while ($row=mysqli_fetch_row($result))
{
$addstring .= "\n".$row[0].";".$row[1].";".$row[2].";".$row[3].";".$row[4].";".$row[5].";".$row[6].";".$row[7].";".$row[8].";".$row[9].";".$row[10].";".$row[11].";".$row[12].";";
};
};
/*file_put_contents($path.$filename, $addstring);*/
fwrite($fn, $addstring);
fclose($fn);
The data is in the following format:
The first addstring contains the column names, and has no issues
the second (addstring .=) contains the data:
ID($row[0]), Date($row[1]), Time($row[2]), Description($row[3]), IP($row[4]), Computer name($row[5]), MAC($row[6]), User($row[7])(empty), Transactionid($row[8]), query result($row[9]), query time($row[10]), correlation id($row[11])(empty), DHCID($row[12])(empty)
It is basically daily DHCP server data, uploaded to a database. Now, the code works, it does write everything i want to the csv, but there are 2 problems.
1, the code for some inexplicable reason, inserts an empty row into the csv table between the rows that contain the data. Removing $row[12] fixes this. I tried removing special characters, converting spaces into something that can be seen, and even converting empty string into something that can be seen. Yet nothing actually worked, i even tried file_puts_content(same for the second problem) instead of fwrite, but nothing. The same thing keeps happening. If i remove \n it will work, but the 2nd row onwards will be misplaced to the right by 1 column.
2, For some reason, the last 2 character is removed from the csv. The string that is to be inserted into the csv still contains said 2 characters before writing it to the file. Tried both fwrite and file_puts_content.
As for the .csv format, the data clumns are divided by ; and rows by \n.
Also tried reading the file with both libre office and excel thinking it might be excel that was splurging but no.
Try using fputcsv() function. I didn't test following code but I think it should work.
$file = fopen($path . $filename, 'w');
$header = array(
'Azonosito',
'Datum',
'Ido',
'Leiras',
'IP-cim',
'allomasnév',
'MAC-cim',
'Felhasznalonev',
'Tranzakcioazonosito',
'Lekerdezes eredmenye',
'Vizsgalat ideje',
'Korrelacios azonosito',
'DHCID'
);
fputcsv($file, $header, ';');
$sql = "select * from dhcpertekeles.dhcpk";
$result = mysqli_query($conn, $sql);
if ($result = mysqli_query($conn, $sql)) {
while ($row = mysqli_fetch_row($result)) {
fputcsv($file, $row, ';');
}
}
fclose($file);
The $addstring = file_get_contents($path.$filename) doesn't does nothing because you're overwriting that variable in the next line.
To remove the extra row on 12 did you tried removing the \n AND the \r with something like:
$row[12] = strtr($row[12], array("\n"=>'', "\r"=>''));
You can also check which ascii characters are you receiving in the $row[12] with this function taken form the php site:
function AsciiToInt($char){
$success = "";
if(strlen($char) == 1)
return "char(".ord($char).")";
else{
for($i = 0; $i < strlen($char); $i++){
if($i == strlen($char) - 1)
$success = $success.ord($char[$i]);
else
$success = $success.ord($char[$i]).",";
}
return "char(".$success.")";
}
}
Another tip can be the database it's returning UTF-8 or UTF-16 and you're losing some characters in the text file.
Try looking at that with the mb_detect_encoding function.

PHP Printing a string with multiple single quotes

So I'm having an issue that seems like it should be a pretty simple fix but I can't seem to figure it out.
I'm using prepared statements to query data from my SQL and the return is correct. I have var_dumped the result and confirmed the the information is there.
The table shows this: 2 'all of the way'
The array variable shows this: 2 \'all of the way\'
But when I echo it to the page, I see this: 2
I have tried htmlspecialchars, htmlentities, addslashes, stripslashes and a few combinations of those. Is there a function I'm missing here? Google isn't really helpful because the words to describe the problem are pretty generic.
Thanks in advance!
EDIT
Sorry - didn't add my code because I assumed it was a function I wasn't familiar with. Here it is.
$Res = $db -> query("SELECT * FROM 01_02_item WHERE ParID = $ParID AND active = 1 ORDER BY OrderID") -> fetchAll(PDO::FETCH_ASSOC);
if(empty($Res[0])) $return = "<span class = 'nodata'>No data</span>";
foreach($Res as $r){
$id = $r['id'];
$name = htmlspecialchars($r['Name']);
$title = stripslashes(htmlspecialchars($r['Description']));
$return .= "<li href = '$id' title = '$title' name = '$name'>$name</li>";
}
return $return;
By default htmlspecialchars() doesn't escape single quotes.
You should use htmlspecialchars('foobar', ENT_QUOTES).

php - get character count between two points encased in quotes

Ok this is going to be weird but I need it
I am trying to get the character count for a huge line of code between some particular quotes ". Basically I need to be able to get everything between the 3rd quote in the beginning and the 5th quote at the end.
So here is an example
a:2:{s:10:"categories";s:5758:"...........";s:5:"posts";s:6:"a:0:{}";}
I need to know what the character count is of all the periods. There is actually code in place of those periods.
Since there are 11 periods then my character count will be 11. The only consistent thing is the quotes in this so I need to base off that.
Any help would be awesome.
Here is my code. I am basically creating the code and adding some custom labels. I tried serializing the code first before I unserialize it but that didn't seem to work.
<?
$thisisit .= 'a:2:{s:10:"categories";s:5481:"a:40:{';
include('connect.php');
$sql = "SELECT * FROM wp_terms ORDER BY term_id ASC LIMIT 40";
$result = mysql_query($sql);
$count = 0;
while($row = mysql_fetch_array($result)) {
$name = $row['name'];
$charactercount = strlen($name);
$term_id = $row['term_id'];
$thisisit .= 'i:'.$count.';a:2:{s:11:"filter_name";s:20:"add_keyword_category";s:11:"filter_args";a:7:{s:12:"filter_value";s:'.$charactercount.':"'.strtolower($name).'";s:19:"filter_search_title";s:1:"1";s:21:"filter_search_excerpt";i:0;s:21:"filter_search_content";s:1:"1";s:21:"faf_filter_categories";a:1:{i:4;s:3:"'.$term_id.'";}s:17:"filter_match_word";i:0;s:17:"filter_match_case";i:0;}}';
//echo "<br><br>";
$count++;
}
$thisisit .= '}";s:5:"posts";s:6:"a:0:{}";}';
$array = unserialize($thisisit);
echo strlen($array['categories']);
?>
Actually this data looks serialized. The correct solution would be to use php function unserialize.
Then, given your structure, to know the length of that element:
strlen(unserialize($data)['categories']);
If you run old php, you need to store the result in a temporary variable:
$array = unserialize($data);
echo strlen($array['categories']);
If your serialized data is corrupted (as in "not received from proper execution of serialize"), as it seems from your example, we can return to your original task:
get everything between the 3rd quote in the beginning and the 5th quote at the end
The simplest way to achieve that is:
implode("'", array_slice(explode("'", $data), 3, -5));

Replace characters in MySQL query result PHP

Couldn't find an exact answer to this question on here, though it may be simple (if there is an answer please point me in the right direction).
I am pulling some data from MySQL and some of the characters are causing the data not to be displayed at the end point. I therefore need to single out these specific characters and replace them with a permitted character. Specifically I need to change & , ' and + . I have to do this working from this query:
$query = "select * from data where a_data_id=".$ID." AND a_discard_data_from!=1";
I was wondering if I can add to this string, or after this string, some rule to replace instances & , ' or + with another character/s.
Thanks for looking!
NOTE: There is no problem with the string above, it is functioning fine, I just want to add to it or after it some type of code that will replace certain characters in the data pulled from the query
Surrounding Code:
$arr="";
$main_arr="";
$query = "select * from data where a_data_id=".$ID." AND a_discard_data_from!=1";
$query .=" and last_update >= " . '"' . $dataDate . '"';
$table = mysql_query($query);
if (mysql_num_rows($table) > 0) {
while ($row = mysql_fetch_assoc($table)) {
foreach ($row as $key => $value) {
$arr[$key] = $value;
if ($key == "to_data_id") {
$array=mysql_fetch_array(mysql_query("select name,additional from details where data_id=".$value));
$arr["data_id"] = $array['additional'].".".$array['name'];
}
}
$main_arr[] = $arr;
}
}
$data = json_encode($main_arr);
Just how to slow it into this code would be great, thank you! (This code works fine, just want to know what I could change / add to replace those characters).
UPDATE: Is anyone able to give me an answer with how I might be able to use strtr()function to replace the results please? Thanks again for the responses!
In mysql if you manually select a field after selecting * it overwrites that field, so provided there's only one field you want to run replaces on and you know the field you know which field it is in advance you can change your select query to (the somewhat ungraceful):
"select
*,
REPLACE(
REPLACE(
REPLACE(`data`.`YOURFIELDNAME`, '&', 'A'),
',', 'A'),
'\'', 'A')
from
data
where a_data_id=".$ID." AND a_discard_data_from!=1";
Which will remove those characters. This is not very graceful, and as eggyal pointed out, you're better off doing this on the front end.

while loop not working for acessing sql records

I am passing a string to this file -txtname- (string separated by spaces) and saparate each word and then pass it to the function subtoken() that should fetch the corresponding words from the database, having two attributes-rootwords and example,but subtoken() function executes only once and exits.
$counter=0;
$string = $_REQUEST['txtname'];
$token = strtok($string, ' ');
while ($token != false)
{echo $counter;
subtoken($token,$counter);
$counter++;
$token = strtok(' ');
}
function subtoken($fname,$counter)
{
$row ="";
$result="";
$result = mysql_query('SELECT * FROM hindi WHERE rootwords LIKE \'%:'.$fname.':%\'' );
while($row = mysql_fetch_array($result))
{
$temp=$row['rootwords'];
$token2 = strtok($temp, ':');
echo $token2 ;
while($token2!=false)
{
echo $token2."<br/>" ;
$token2=strtok(':');
}
}
}
mysql_close($con);
The double usage of strtok will prevent the "main" loop to properly process all tokens from the original $string. You simply can't have more than one "open" strtok use at the same time.
Original suspect was your query, that it just doesn't select anything. Try printing the SQL statement, then executing that statement directly (e.g. via phpmyadmin)
// insert this line:
echo(
'SELECT * FROM hindi '.
'WHERE rootwords LIKE \'%:'.$fname.':%\'');
// just before the actual query execution
$result = mysql_query(
'SELECT * FROM hindi '.
'WHERE rootwords LIKE \'%:'.$fname.':%\'' );
From my experience, echo'ing as much data as possible early on while debugging is one of the best tools to easily spot errors.
See also: http://nl2.php.net/mysql_fetch_array
mysql_fetch_array needs a second parameter to work correctly.
Replace mysql_fetch_array with mysql_fetch_row. Or mysql_fetch_assoc if you want to reference to the columns by name.
May be you have some error/warning? Is error_reporting set to E_ALL and display_errors to "On"?
It seems that strtok() has only one pointer. So, when you ended with it in function, you need to reinitialise $token = strtok($string, ' ');? dut I am not sure. I think it would be better if you used explode() function.

Categories