I'm working on INSERTing VALUES using MySQL queries that involve escaping values via a PHP script. I was able write code that works (see below), but the only ways I can figure out are so cumbersome that they remind me of plebs eating peas off a fork at West Point. I have to believe I'm missing something. MySQL and PHP are supposed to work together, right? Can anyone point me in a better direction? Thanks!
<?php
// CONNECTION = "$connection".
require("Connection.php");
// CREATE TABLE
$create_table_query="
CREATE TABLE IF NOT EXISTS `titles_table`
(lastpost_id INT(10) NULL,
title VARCHAR(200))
";
$create_query_results=mysqli_query($connection,$create_table_query);
// Set up CUMBERSOME query:
$title1="IL - Yingying Zhang, 26, Urbana, 9 June 2017";
Echo "\$title1 looks like: $title1 <br>"; // 'IL - Yingying Zhang, 26, Urbana, 9 June 2017'
$title2="NJ - Brendan Creato, 3, found dead in Cooper River Park, 13 Oct 2015";
Echo "\$title2 looks like: $title2 <br>"; // 'NJ - Brendan Creato, 3, found dead in Cooper River Park, 13 Oct 2015'
$title1_escaped="'".mysqli_real_escape_string($connection,$title1)."'";
Echo "\$title1_escaped looks like: $title1_escaped <br>";
$title2_escaped="'".mysqli_real_escape_string($connection,$title2)."'";
Echo "\$title2_escaped looks like: $title2_escaped <br>";
$sql_query_CUMBERSOME="
INSERT INTO `titles_table`(
lastpost_id,
title
)
VALUES
(1013,
$title1_escaped),
(1014,
$title2_escaped);
";
echo "<br>";
echo "Here's what \$sql_query_CUMBERSOME looks like :<br>";
echo "$sql_query_CUMBERSOME </br>";
// INSERT INTO `titles_table`( lastpost_id, title ) VALUES (1013, 'IL - Yingying Zhang, 26, Urbana, 9 June 2017'), (1014, 'NJ - Brendan Creato, 3, found dead in Cooper River Park, 13 Oct 2015');
// RUN and TEST $sql_query_CUMBERSOME
$sql_query_CUMBERSOME_results=mysqli_query($connection,$sql_query_CUMBERSOME);
// TEST the results (the tests report success)
IF(!$sql_query_CUMBERSOME_results):
$results_error_message=mysqli_error($connection);
ECHO "ERROR: \$sql_query_CUMBERSOME_results doesn't exist. The mysqli error message is: $results_error_message </br>";
ELSE:
$affected_rows=mysqli_affected_rows($connection);
ECHO "SUCCESS: \$sql_query_CUMBERSOME_results exists. Here is the affected rows count: $affected_rows </br></br>";
ENDIF;
// -----------------------------------
// SET UP alternative UNWIELDLY query:
$sql_query_UNWIELDLY = "INSERT INTO `titles_table`(lastpost_id,title) ";
$sql_query_UNWIELDLY .= "VALUES (1015,'";
$sql_query_UNWIELDLY .= mysqli_real_escape_string($connection,'IL - Yingying Zhang, 26, Urbana, 9 June 2017');
$sql_query_UNWIELDLY .= "'),";
$sql_query_UNWIELDLY .= "(1016,'";
$sql_query_UNWIELDLY .= mysqli_real_escape_string($connection,'NJ - Brendan Creato, 3, found dead in Cooper River Park, 13 Oct 2015');
$sql_query_UNWIELDLY .= "');";
echo "Here's what \$sql_query_UNWIELDLY looks like:<br>";
echo "$sql_query_UNWIELDLY </br>";
// INSERT INTO `titles_table`(lastpost_id,title) VALUES (1015,'IL - Yingying Zhang, 26, Urbana, 9 June 2017'),(1016,'NJ - Brendan Creato, 3, found dead in Cooper River Park, 13 Oct 2015');
// RUN and TEST $sql_query_UNWIELDLY
$sql_query_UNWIELDLY_results=mysqli_query($connection,$sql_query_UNWIELDLY);
// TEST the results (the tests report success)
IF(!$sql_query_UNWIELDLY_results):
$results_error_message=mysqli_error($connection);
ECHO "3a) ERROR: \$sql_query_UNWIELDLY_results doesn't exist. The mysqli error message is: $results_error_message </br>";
ELSE:
$affected_rows=mysqli_affected_rows($connection);
echo "SUCCESS: \$sql_query_UNWIELDLY_results exists. Here is the affected rows count: $affected_rows </br>";
ENDIF;
?>
I think the line of code looks good but, Only things we can use to close the connection after use.
End of your code add
mysqli_close($connection);
hope it will work, if not let me know.
Related
I've got a project that involves getting flight information from a database.
I want the results to look like:
01 Nov 2017 - Eastern Airways 7601
Departing from Southampton, Eastleigh (SOU) at 0840
However my code seems to bring up the below with a mysterious live of nonsense as per below
01 Nov 2017 - Eastern Airways 7601
Departing from , () at 084001 Nov 2017 - 7601 //this line I don't want
Departing from Southampton, Eastleigh (SOU) at 0840
$link = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx' );
foreach ($flights as $b) {
$query = "SELECT * FROM `airlines` WHERE `iatacode` = '$airline' LIMIT 0 , 30;";
$query .= "SELECT * FROM `airports` WHERE `Airport Code` = '$depdest' LIMIT 0 , 30;";
/* Execute queries */
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_array($result))
/* print results */
{
$date=date_create($depdate);
echo "<b>" . date_format($date,"d M Y"). " - ". $row['airlinename']." ".$flightno. "</b><br/>";
echo "Departing from " .$row['City Name'].", ".$row['Airport Name']." (".$row['Airport Code'].") at " . $deptime;
}
mysqli_free_result($result);
}
} while (mysqli_next_result($link));
}
Can anyone see what I'm doing wrong?
Data base tables are as below
table 1 - Name "airports"
Airport ID City name Airport Code Airport Name Country name Country Abbrev. World Area Code
1, 108 Mile Ranch, ZMH , 108 Mile Ranch , Canada, CA, 906,
2, Aachen, AAH Aachen/Merzbruck, Germany, DE, 429,
3, Aachen, ZIU, Railway, Germany, DE, 429,
4, Aalborg, AAL, Aalborg, Denmark, DK, 419,
etc
table 2 - Name "airlines"
airline id, Iata, Airline Name
1, 0A, Amber Air,
2, 0B, Blue Air,
3, 0C, IBL Aviation,
etc
Thanks!
If I was to guess, I would say that there is a problem with the $b variable.
It seems your output is being written twice: the value "084001" in the middle of the second line looks to be the 0840 flight time from one entry, and then immediately starting the next entry as the date.
I would guess that the foreach is looping twice, instead of once, causing two outputs.
Could you do an output of the $b variable?
echo "<pre>";
print_r($b);
echo "</pre>";
I'd like to parse txt files to HTML using preg_replace to add formatting.
The format of the file is like this :
09:19:49 13-12-15 Sunday Hello World
1234567 Today is a beautiful day
1234568 Tomorrow will be even better
1234569 December is the best month of the year!
This should be treated as a group and parsed into a table, like :
<table>
<tr><td>09:19:49 13-12-15</td><td>Sunday</td><td>Hello World</td></tr>
<tr><td>1234567</td><td>(optional)</td><td>Today is a beautiful day</td></tr>
<tr><td>1234568</td><td>(optional)</td><td>Tomorrow will be even better</td></tr>
<tr><td>1234569</td><td>(optional)</td><td>December is the best month of the year!</td></tr>
</table>
For now, I'm using two separate preg_replacements, one for the first line (date) and a second one for the following ones, which can be just one or up to 100 or so. But, this file can contain other text as well, which needs to be ignored (as for the replacement), but if this line has more or less the same format (7 digits and some text) it gets formatted as well :
$file = preg_replace('~^\s*((\[.*\]){0,2}\d{1,2}:\d{2}:\d{2}(\[/.*\]){0,2})\s(\d{2}-\d{2}-\d{2}(\[/.*\]){0,2})\s+(?:\d{2}/\d{3}\s+|)(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\s+(.+)$~m', '<table class="file"><tr class="entry"><td class="time">$1 $4</td><td class="day">$6</td><td class="message">$7</td></tr>', $file);
$file = preg_replace('~^\s*(.{0,11}?)\s*((\[.+?\])?\d{7}(\[/.+?\])?)\s+(.+?)$~m', '<tr class="id"><td class="optional">$1</td><td class="id">$2</td><td class="message">$5</td></tr>', $file);
How to improve this? Like, if I have this content :
09:19:49 13-12-15 Sunday Hello World
1234567 Today is a beautiful day
1234568 Tomorrow will be even better
1234569 December is the best month of the year!
Liverpool - WBA 2-2
1234570 This line should be ignored
19:29:59 13-12-15 Sunday Hello World
1234571 Today is a beautiful day
1234572 Tomorrow will be even better
So, I'd like to catch and preg_replace only the first block and the last one, starting with time/date and some following lines, starting with a 7-digit ID.
So far, thanks for reading ;)
I think this accomplishes what you are trying to do.
There was one line that were unclear to me why it should be ignored:
1234570 This line should be ignored
This line meets the 7 digits and some text requirement.
The regex I came up with was:
/^(\d{2}:\d{2}:\d{2}\h*\d{1,2}-\d{1,2}-\d{1,2}|\d{7})\h*([a-zA-Z]{3}day)?\h*(.+)/m
Here is a regex101 demo: https://regex101.com/r/qB0gH6/1
and in PHP usage:
$string = '09:19:49 13-12-15 Sunday Hello World
1234567 Today is a beautiful day
1234568 Tomorrow will be even better
1234569 December is the best month of the year!
Liverpool - WBA 2-2
1234570 This line should be ignored
19:29:59 13-12-15 Sunday Hello World
1234571 Today is a beautiful day
1234572 Tomorrow will be even better';
echo preg_replace('/^(\d{2}:\d{2}:\d{2}\h*\d{1,2}-\d{1,2}-\d{1,2}|\d{7})\h*([a-zA-Z]{3}day)?\h*(.+)/m', '<td>$1</td><td>$2</td><td>$3</td>', $string);
Output:
<td>09:19:49 13-12-15</td><td>Sunday</td><td>Hello World</td>
<td>1234567</td><td></td><td>Today is a beautiful day</td>
<td>1234568</td><td></td><td>Tomorrow will be even better</td>
<td>1234569</td><td></td><td>December is the best month of the year!</td>
Liverpool - WBA 2-2
<td>1234570</td><td></td><td>This line should be ignored</td>
<td>19:29:59 13-12-15</td><td>Sunday</td><td>Hello World</td>
<td>1234571</td><td></td><td>Today is a beautiful day</td>
<td>1234572</td><td></td><td>Tomorrow will be even better</td>
Okay, per your update it is a bit more complicated but I think this does it:
$string = '09:19:49 13-12-15 Sunday Hello World
1234567 Today is a beautiful day
1234568 Tomorrow will be even better
1234569 December is the best month of the year!
Liverpool - WBA 2-2
1234570 This line should be ignored
19:29:59 13-12-15 Sunday Hello World
1234571 Today is a beautiful day
1234572 Tomorrow will be even better';
echo preg_replace_callback('/(?:^|\n)(\d{2}:\d{2}:\d{2}\h*\d{1,2}-\d{1,2}-\d{1,2})\h+([a-zA-Z]{3}day)?\h*(.+?)\n((\d{7})\h+(.+?)(\n|$))+/',
function ($matches) {
$lines = explode("\n", $matches[0]);
$theoutput = '<table><tr>';
foreach($lines as $line) {
if(preg_match('/(?:^|\n)(\d{2}:\d{2}:\d{2}\h*\d{1,2}-\d{1,2}-\d{1,2})\h+([a-zA-Z]{3}day)?\h*(.*)/', $line, $output)) {
//it is the first date string line;
foreach($output as $key => $values) {
if(!empty($key)) {
$theoutput .= '<td>' . $values . '</td>';
}
}
} else {
if(preg_match('/(\d{7})\h*(.*)/', $line, $output)) {
$theoutput .= '</tr><tr>';
foreach($output as $key => $values) {
if(!empty($key)) {
$theoutput .= '<td>' . $values . '</td>';
}
}
}
}
}
$theoutput .= '</tr></table>';
return $theoutput;
}, $string);
Output:
<table><tr><td>09:19:49 13-12-15</td><td>Sunday</td><td>Hello World</td></tr><tr><td>1234567</td><td>Today is a beautiful day</td></tr><tr><td>1234568</td><td>Tomorrow will be even better</td></tr><tr><td>1234569</td><td>December is the best month of the year!</td></tr></table>
Liverpool - WBA 2-2
1234570 This line should be ignored
<table><tr><td>19:29:59 13-12-15</td><td>Sunday</td><td>Hello World</td></tr><tr><td>1234571</td><td>Today is a beautiful day</td></tr><tr><td>1234572</td><td>Tomorrow will be even better</td></tr></table>
I am newbie in php. Can this be possible to be done?? the script role is to find the match in another row but not on the same column...
the .csv file
**first row** **second row** **third row**
This is for NNMM NN/MM#000-45NNMM;1 2001
AA/BB#000-45AABB;2 ----- 2002
NN/MM#000-45NNMM;2 ----- 2003
This is for XXYY XX/YY#000-45XXYY;1 2004
LL/QQ#000-45LLQQ;2 ----- 2005
WW/KK#000-45WWKK;2 ----- 2006
CC/DD#000-45CCDD;2 ----- 2005
PP/SS#000-45PPSS;2 ----- 2006
This is for AABB AA/BB#000-45AABB;1 2007
XX/YY#000-45XXYY;2 ----- 2008
This is for PPSS PP/SS#000-45PPSS;1 2009
This is for CCDD CC/DD#000-45CCDD;1 2010
in first row: there are 5 fields the last char in string is "2".(i.e.AA/BB#000-45AABB;2)
in second row: there are 5 fields the last char in string is "1".(i.e.AA/BB#000-45AABB;1)
now i want to do a matching script where the first row find the match in 2ndrow.. and display the data from first row which the match is found... hope it makes sense...
desired output
This is for NNMM NN/MM#000-45NNMM;1 2001
This is for XXYY XX/YY#000-45XXYY;1 2004
This is for AABB AA/BB#000-45AABB;1 2007
This is for PPSS PP/SS#000-45PPSS;1 2009
This is for CCDD CC/DD#000-45CCDD;1 2010
i have started a script but stuck working out with the logic...
$file = fopen('sample.csv', 'r');
echo "<table style='border: 2px solid black; text-align:left'>";
while (($line = fgetcsv($file)) !== FALSE) {
list( $row1, $row2, $row3) = $line;
echo "<tr>";
echo "<td>$row1</td>";
echo"<td>$row2</td>";
echo "<td>$row3</td>";
echo "</tr>";
}
echo "</table>";
It is propably not best tool for that, but I tried to do it with regex, and I know it is ugly, but try it out:
(?|(?:([A-Z]{2}\/[A-Z]{2}#\d{3}-\d{2}([A-Z]{4});)(1))(?=(?:.|\n)+?(\d{4})(?:.|\n)+\1(?:2))|(?:([A-Z]{2}\/[A-Z]{2}#\d{3}-\d{2}([A-Z]{4});)2)(?=(?:.|\n)+(?:\1(1))(?:.|n)+?(\d{4})))
DEMO
Relevant data is in groups, so you can use something like: "This is for $2\t$1$3\t$4" to get data you want. In substitution part of my demo, you can see the output (but it only replace matched parts and the the rest of umatched text is still there, but it is just to see how such output could look).
use a do while() instead of while sorry can't write the code for you
and you have to use if statements also if ($row1 == $row1) {then do this}
i am displaying the top 5 results from a sql query using the following code;
<?php
$query = "SELECT location, COUNT(location) AS qty FROM ecmt_memberlist GROUP BY location ORDER BY qty DESC LIMIT 0,5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "<span class='graphValue'>x".$row['qty']."</span> " . $row['location'] . "<br />";
} ?>
this is displaying my result strings as follows:
x46 Moon 20 - Sisters of EVE Academy
x34 Moon 7 - Ammatar Fleet Assembly Plant
x28 Jita x11 Jita IV - Moon 4 - Caldari Navy Assembly Plant
x11 Jita IV - Moon 4
x9 Lonetrek III - FUUUFAGOLAS
how can i trim down the $row['location'] to show the words before the first "-" for example;
x46 Moon 20
x34 Moon 7
x28 Jita x11 Jita IV
x11 Jita IV
x9 Lonetrek III
Just use strstr() and print before needle, e.g.
strstr($row['location'], "-", TRUE);
while you could do it with php as every on else suggest, i think its better to do it with mysql:
$query = "SELECT SUBSTRING_INDEX(location,'-',1) as location, COUNT(location) AS qty FROM ecmt_memberlist GROUP BY location ORDER BY qty DESC LIMIT 0,5";
echo explode('-', $row['location'])[0];
OR
echo preg_replace('/\-\s.+/i', '', $row['location']);
$str='x46 Moon 20 - Sisters of EVE Academy';
$str2=substr($str,0,strpos($str,' -'));
echo $str2;
There's a couple different ways you could do this, one using explode()
$location = explode("-", $row['location']);
Then call everything before the "-" with echo $location[0]; See PHP Explode
Or you can use strstr()
$location = strstr($row['location'], '-', true);
and call it with just $location as setting the 3rd parameter to true returns everything before the first occurrence of the 2nd parameter. See PHP strstr
Or you can use split()
$location = split("-", $row['location']);
and call it using $location[0]
i have the following URI:
http://mysite/myapp/index.php/test/testURL/CAN-q1/300-48/fa1/59//can-a2
You'll notice that the 7th URI segment is not set.
I need to test for these types of scenarios.
I've tried a few different things but i can't seem to get it to work. What's happening is segment 8 is being assigned as segment 7.
Here's some test code I've been playing with this morning:
echo '3 - '. $this->uri->segment(3);
echo '<BR>';
echo '4 - '. $this->uri->segment(4);
echo '5 - '. $this->uri->segment(5);
echo '<BR>';
echo '6 - '.$this->uri->segment(6);
echo '<BR>';
$test = $this->uri->segment(7,0);
echo '7 is: '.$test;
echo '<BR>';
echo '8 - '. $this->uri->segment(8);
echo '<BR>';
And the results come back as:
3 - CAN-q1
4 - 300-48
5 - fa1
6 - 59
7 is: can-a2
8 -
Based on reading the codeigniter manual, i would have expected that segment 7 would contain a 0 or whatever i passed as the second parameter in the uri->segment() method.
Can you tell me where I'm going wrong?
Thanks.
I just decided to pass a space instead of an empty URI, based on comments that others have made that you can't have a empty segment.
This seems to have resolved the problem.
Thanks to everyone who commented.