I have some code which uses odbc calls. I've had no problem with the pulling data from a MS SQL database until this bit of code. Instead of saving the string to a variable it outputs the string and saves an int 1 to the variable instead.
below is the relevant code:
$qry = 'SELECT * FROM cst_AdEssayDetails_vw WHERE AdEnrollSchedID = ?';
$essay = odbc_prepare($conn,$qry);
if(odbc_execute($essay,array($AdEnrollSchedID))){
if (odbc_num_rows($essay)>0){
while (odbc_fetch_row($essay)){
$setTopic = odbc_result($essay,'setTopic');
$essay_active = odbc_result($essay,'active');
$essay_date = date("m-d-y", strtotime(odbc_result($essay,'StartDate')));
$essayID = odbc_result($essay,'EssayID');
$EnrollSchedID = odbc_result($essay,'AdEnrollSchedID');
$intro = odbc_result($essay,'intro');
$support = odbc_result($essay,'support');
$conclusion = odbc_result($essay,'conclusion');
$essay_comment = odbc_result($essay,'comment');
$submitted = odbc_result($essay,'submitted');
$dateSubmitted = date("m-d-y", strtotime(odbc_result($essay,'dateSubmitted')));
$essay_grade = odbc_result($essay,'grade');
$AdStudentEssayID = odbc_result($essay,'AdStudentEssayID');
$topic = odbc_result($essay,'topic');
echo '<intro1>'.$intro.'</intro1>';
echo '<intro_len>'.strlen($intro).'</intro_len>';
if (1 > strlen($essay_comment)){
$essay_comment = ' ';
} else {
$essay_comment = urlencode($essay_comment);
}
if (1 > strlen($essay_grade)) {
$essay_grade = ' ';
}
if (2 < strlen($topic)){
$topic = urlencode($topic);
} else {
$topic = ' ';
}
if (2 < strlen($intro)){
$intro = urlencode($intro);
} else {
$intro = ' ';
}
if (2 < strlen($support)){
$support = urlencode($support);
} else {
$support = ' ';
}
if (2 < strlen($conclusion)){
$conclusion = urlencode($conclusion);
} else {
$conclusion = ' ';
}
echo '<setTopic>'.$setTopic.'</setTopic>';
echo '<essay_active>'.$essay_active.'</essay_active>';
echo '<essay_date>'.$essay_date.'</essay_date>';
echo '<essayID>'.$essayID.'</essayID>';
echo '<topic>'.$topic.'</topic>';
echo '<intro>'.$intro.'</intro>';
echo '<support>'.$support.'</support>';
echo '<conclusion>'.$conclusion.'</conclusion>';
echo '<essay_comment>'.$essay_comment.'</essay_comment>';
echo '<submitted>'.$submitted.'</submitted>';
echo '<dateSubmitted>'.$dateSubmitted.'</dateSubmitted>';
echo '<essay_grade>'.$essay_grade.'</essay_grade>';
echo '<AdStudentEssayID>'.$AdStudentEssayID.'</AdStudentEssayID>';
}
} else {
The output I get from this is:
'Test Introduction Paragraph
Test Supporting Paragraph
2nd test supporting paragraph
Test Conclusion Paragraph
Test Essay Topic
<intro1>1</intro1>
<intro_len>1</intro_len>
<setTopic>%3Cp%3ETest%20Topic%3C%2Fp%3E</setTopic>
<essay_active>1</essay_active>
<essay_date>01-01-70</essay_date>
<essayID>29</essayID>
<topic></topic>
<intro></intro>
<support></support>
<conclusion></conclusion>
<essay_comment>1</essay_comment>
<submitted>1</submitted>
<dateSubmitted>07-11-16</dateSubmitted>
<essay_grade></essay_grade>
<AdStudentEssayID>59</AdStudentEssayID>'
The output I expect is:
'<intro1>Test Introduction Paragraph</intro1>
<intro_len>1</intro_len>
<setTopic>%3Cp%3ETest%20Topic%3C%2Fp%3E</setTopic>
<essay_active>1</essay_active>
<essay_date>01-01-70</essay_date>
<essayID>29</essayID>
<topic>Test Essay Topic</topic>
<intro>Test Introduction Paragraph</intro>
<support>Test Supporting Paragraph 2nd test supporting paragraph</support>
<conclusion>Test Conclusion Paragraph</conclusion>
<essay_comment>1</essay_comment>
<submitted>1</submitted>
<dateSubmitted>07-11-16</dateSubmitted>
<essay_grade></essay_grade>
<AdStudentEssayID>59</AdStudentEssayID>'
So the question is, Why is it doing this? Why does it output 'intro','support','conclusion', and 'topic' instead of saving them to the variable?
Related
<?php
$id = array(
"UC4MubF2asPHQbXN44DVNeXg",
"UCXuDgoo_oiZf8UkIXs3Y_kw",
"UCMnDuOzzJrWzr5tfemDcqlQ",
"UC9FH1mkHLFQuPPEPu9CfR1A",
"UCfyEAw41i7PRetP2erYf9dg",
);
// Getting Emails from DB and Looping with Channel Title and Video Title
$conn = mysqli_connect("localhost","username","password","dbname");
$query = "SELECT * FROM prospects ORDER BY email";
$rows = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($rows)) {
$to[] = $row['email'];
}
$size = sizeof($id);
//echo "<br>Number of channel Ids: ".$size."<br><br>";
// Looping each Url for Each Email to get Data
foreach($to as $t){
echo $t."<br>";
for ($i = 0; $i < $size; $i++) {
$url = "https://www.youtube.com/channel/$id[$i]";
// echo $url."<br>";
$channel = trim(explode('https://www.youtube.com/channel/', $url)[1]);
// echo $channel."<br>";
$rss = "https://www.youtube.com/feeds/videos.xml?channel_id=$channel";
// echo $rss."<br>";
$xml = simplexml_load_file($rss);
$title = $xml->title;
// echo $title."<br>";
$videoTitle = $xml->entry[0]->title;
// echo $videoTitle."<br>";
$id[$i] = $xml->id;
// echo $id[$i]."<br>";
// $idOnly = substr($id[$i] , strpos($id[$i] , "yt:channel:") + 11);
// echo $idOnly."<br>";
$pub[$i] = $xml->entry[0]->published;
// echo $pub[$i]."<br>";
$realDate_ = new DateTime($pub[$i]);
// var_dump($realDate_);
$realDate2_ = $realDate_->format("D, d M Y")."<br>";
//echo $realDate2_;
$today_ = new DateTime();
// $today2_ = $today_->format("D, d M Y")."<br>";
// echo $today2_;
// if ($today2_ == $realDate2_) {
// echo "true";
// This is the Result with Every Email
echo $content = "• <a href='https://bladingflix.com/render.php?email=$t&channel=$idOnly'>".$title." - ".$videoTitle."</a><br>";
// }
}
}
?>
For the First Email the Data Shows Properly but in for the others
Purpose = get collected links add the user email to each url repeat for each.
Please make below changes in your existing code
In the second for() loop you are replacing the $id array as below
$id[$i] = $xml->id;
Instead of replacing the $id[$i] value, create new variable as below
$xmlId = $xml->id;
$idOnly = substr($xmlId, strpos($xmlId , "yt:channel:") + 11);
And please uncomment the $idOnly variable.
It will work. And try to refactor this code.
I am a beginner programmer. Only in php.
On php, am at procedural style. Not on oop or pdo yet. Hence, you see mysqli and procedural style.
I am building a SERP with pagination. Like google, when they show you your keywords search result.
Don't mistake my thread. Not trying to prevent Sql injection as I managed to do it using prepared statements.
Learning to use urlencode(), rawurlencode(), htmlentities() as I'm trying to use them to prevent user's injecting unwanted html tags to breakup the html of my SERPs.
On this occasion, I am having problem using urlencode() properly.
I get this error:
Warning: urlencode() expects parameter 1 to be string, array given in ... on line ...
Following are the concerned lines as I urlencode() their values so no user (keywords searcher) can inject html tags to breakup the html of my SERP:
$search = $_GET['search']; //Keyword(s) to search.
$col = $_GET['col']; //MySql Tbl Col to search.
$tbl = $_GET['tbl']; //MySql Tbl to search.
$max = $_GET['max']; //Max Result per page.
$page = $_GET['page']; //Serp Number.
The above vars contain one values each as each $_GET contains one value each, even though $_GET is a a global variable (array). So here, nothing to do with arrays or more than one value per each variable.
Issue is on this following line that comes just after the WHILE loop:
LINE 145
$query_string_1 = '?search=' .urlencode($search) .'&tbl=' .urlencode($tbl) .'&col=' .urlencode($col) .'&max=' .intval($max);
Here is the code context:
//ERROR REPORTING FOR DEVMODE ONLY.
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL);
//MYSQLI CONNECTION.
mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);
$server = 'localhost';
$user = 'root';
$password = '';
$database = 'brute';
if(!$conn = mysqli_connect("$server","$user","$password","$database"))
{
echo 'Mysqli Connection Error' .mysqli_connect_error($conn);
echo 'Mysqli Connection Error Number' .mysqli_connect_errno($conn);
}
if(!mysqli_character_set_name($conn) == 'utf8mb4')
{
echo 'Initial Character Set: ' .mysqli_character_set_name($conn);
mysqli_set_charset("$conn",'utf8mb4');
echo 'Current Character Set: ' .mysqli_character_set_name($conn);
}
//PAGINATION SECTION.
$search = $_GET['search']; //Keyword(s) to search.
$col = $_GET['col']; //MySql Tbl Col to search.
$tbl = $_GET['tbl']; //MySql Tbl to search.
$max = $_GET['max']; //Max Result per page.
$page = $_GET['page']; //Serp Number.
//QUERY DATABASE FOR KEYWORD COUNT.
$query = "SELECT COUNT(id) From links WHERE keyword = ?";
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,'s',$search);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt,$row_count);
if(mysqli_stmt_fetch($stmt))
{
echo 'Row Count: ' .$row_count; echo '<br>';
}
else
{
echo 'Record fetching failed!';
echo 'Error: ' .mysqli_stmt_error($conn);
echo 'Error: ' .mysqli_stmt_errno($conn);
}
mysqli_stmt_close($stmt);
}
else
{
echo 'Search Preparation Failed!';
}
//mysqli_close($conn);
echo '<b>'; echo __LINE__; echo '</b>'; echo '<br>';
//START KEYWORD SEARCH & OUTPUT RESULT
echo $offset = ($page*$max)-$max; echo '<br>';
echo '<b>'; echo __LINE__; echo '</b>'; echo '<br>';
$query = "SELECT id,date_and_time,domain,domain_email,ip,url,anchor,title,description,keyword,keyphrase From links WHERE keyword = ? LIMIT $offset,$max";
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,'s',$search);
mysqli_stmt_execute($stmt);
if($result = mysqli_stmt_get_result($stmt))
{
/*
FOLLOWING BOTH ARE EQUAL:
$col = mysqli_fetch_array($result) //SHORT VERSION.
$col = mysqli_fetch_array($result,MYSQLI_BOTH) //LONG VERSION.
*/
$col = mysqli_fetch_array($result); //SHORT VERSION.
$id = $col['0']; //MYSQLI_NUM
$date_and_time = $col['date_and_time']; //MYSQLI_ASSOC
$domain = $col['2']; //MYSQLI_NUM
$domain_email = $col['domain_email']; //MYSQLI_ASSOC
$ip = $col['4']; //MYSQLI_NUM
$url = $col['url']; //MYSQLI_ASSOC
$anchor = $col['6']; //MYSQLI_NUM
$title = $col['title']; //MYSQLI_ASSOC
$description = $col['8']; //MYSQLI_NUM
$keyword = $col['keyword']; //MYSQLI_ASSOC
$keyphrase = $col['10']; //MYSQLI_NUM
echo 'Id: ' .$id; echo '<br>';
echo 'Date And Time: ' .$date_and_time; echo '<br>';
echo 'Domain: ' .$domain; echo '<br>';
echo 'Domain Email: ' .$domain_email; echo '<br>';
echo 'Ip: ' .$ip; echo '<br>';
echo 'Url: ' .$url; echo '<br>';
echo 'Anchor: ' .$anchor; echo '<br>';
echo 'Title: ' .$title; echo '<br>';
echo 'Description: ' .$description; echo '<br>';
echo 'Keyword: ' .$keyword; echo '<br>';
echo 'Keyphrase: ' .$keyphrase; echo '<br>';
}
else
{
echo 'Record fetching failed!';
echo 'Error: ' .mysqli_stmt_error($stmt);
echo 'Error: ' .mysqli_stmt_errno($stmt);
}
mysqli_stmt_close($stmt);
}
mysqli_close($conn);
echo '<b>'; echo __LINE__; echo '</b>'; echo '<br>';
//PAGINATION SECTION TO NUMBER THE PAGES AND LINK THEM.
$total_pages = ceil($row_count/$max);
$i = '1';
//$selfpage = $_SERVER['PHP_SELF'];
$selfpage = basename(__FILE__,''); //Echoes: url_encode_Template.php. Does not fetch the url $_GET params.
$path = rawurlencode($selfpage);
$query_string_1 = '?search=' .urlencode($search) .'&tbl=' .urlencode($tbl) .'&col=' .urlencode($col) .'&max=' .intval($max);
while($i<=$total_pages)
{
$query_string_2 = '&page=' .intval($i);
$url = $path .htmlentities($query_string_1) .htmlentities($query_string_2); //Full URL With $_GET params: https://localhost/Templates/url_encode_Template.php?search=keyword&tbl=links&col=keyword&max=100&page=1
if($page == $i)
{
echo '<a href=' .'"' .$url .'"' .'>' .'<b>' .intval($i) .'</b>' .'</a>';
}
else
{
echo '<a href=' .'"' .$url .'"' .'>' .intval($i) .'</a>';
}
$i++;
}
?>
Frankly, the pagination page is nearly finished, had it not been for this urlencode() issue!
If you spot any other errors which I have not asked about it's subject due to overlooking them then kindly show me a code sample by editing my code in order to show me how I really should've coded it. (I'm talking about my usage of urlencode(), rawurlencode(), htmlentities() as I'm trying to use them to prevent user's injecting unwanted html tags) to breakup my SERP.
I'd appreciate it if my code is edited by someone and the correction is displayed on this thread, wherever I went wrong.
Your problem is that you are overwriting the value of the $col variable that you initially populate with the 'col' parameter in the GET request with the result of your keyword search.
$col = $_GET['col']; //MySql Tbl Col to search.
...
$col = mysqli_fetch_array($result); //SHORT VERSION.
You do not seem to be using the col parameter for anything, you may be able to just remove it from the query string. If you do intend to use it, simply rename the variable you are using for the query result row.
For future reference, you can encode array values into a query string using the http_build_query function. This would simplify your code, and would have allowed you to see were the problem is in this case.
// Set some test values for the parameters
$search = 'my search term';
$tbl = 'my_table_name';
$col = 'column_1';
$max = 10;
// Simulate variable being overwritten with database result
$col = [
'id' => 123,
'date_and_time' => '2021-06-20 09:44:00',
'domain' => 'stackoverflow.com'
];
// Build an array of the parameters to be included in the query string
$queryParameters = [
'search' => $search,
'tbl' => $tbl,
'col' => $col,
'max' => $max
];
/*
* Build the query string using http_build_query
* Any array values will be represented appropriately
* Prepend the ? to the result
*/
$query_string_1 = '?'.http_build_query($queryParameters);
echo $query_string_1.PHP_EOL;
My problem is in my code I'm having problems with it calculating something with a variable that does not exists some times and some times does.
I want it to give me back number of deaths if empty '0' if not prints me what is in the variable, but for some reason i get this:
E_NOTICE : type 8 -- Undefined property: stdClass::$numDeaths -- at
line 66 E_WARNING : type 2 -- Division by zero -- at line 71
here is my code:
<?php
$apiKey = 'e9044828-20e3-46cc-9eb5-545949299803';
$summonerName = 'tamini';
$new = rawurlencode($summonerName);
$news = str_replace(' ', '', $summonerName);
$str = strtolower($news);
// get the basic summoner info
$result = file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/' . $new . '?api_key=' . $apiKey);
$summoner = json_decode($result)->$str;
$id = $summoner->id;
// var_dump($summoner);
?>
<?php
$clawzz = file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.3/game/by-summoner/' . $id . '/recent?api_key=' . $apiKey);
$gazazz = json_decode($clawzz);
?>
<?php
$entrieszz = $gazazz->games;
usort($entrieszz, function($ac,$bc){
return $bc->createDate-$ac->createDate;
});
foreach($entrieszz as $statSummaryzz){
$gamemodekillz = $statSummaryzz->stats->championsKilled;
$gamemodedeathz = $statSummaryzz->stats->numDeaths;
$gamemodeassistz = $statSummaryzz->stats->assists;
$kdamatchhistoryeach = ($gamemodekillz + $gamemodeassistz) / $gamemodedeathz;
echo ' <br>';
echo $gamemodekillz;
echo ' <br>';
if ($gamemodedeathz == 0){
echo '0';
}
else {
echo $gamemodedeathz ;
}
echo ' <br>';
echo $gamemodeassistz;
echo ' <br>';
if ($gamemodedeathz == 0){
echo 'Perfect Score';
}
else {
echo $kdamatchhistoryeach ;
}
?>
You need to check if the value exist:
if( isset($statSummaryzz->stats) && isset($statSummaryzz->stats->numDeaths) ) {
$gamemodedeathz = $statSummaryzz->stats->numDeaths;
}
I have successfully pulled data from mySql into the message of the html email. But after several attempts, I'm unable to add a two break lines after the 10th record. Any assistance would be wonderful.
$sorc325sql = "Select * ".$sorc325sql2;
echo "<br>325sql=".$sorc325sql."<br><br>";
$sorc325res = mysqli_query($connectXXX, $sorc325sql) or die(mysqli_error($connectXXX));
if (mysqli_num_rows($sorc325res) < 1) {
$display_block = "<p><em>No topics exist.</em></p>";
} else {
while ($sorc325row = mysqli_fetch_array($sorc325res)) {
$sorc325arycustctr++;
$message .= $sorc325row['progName'].', ';
}
}
Using Mark B's idea, you need to add it to the current $sorc325arycustctr++; line
$sorc325sql = "Select * ".$sorc325sql2;
echo "<br>325sql=".$sorc325sql."<br><br>";
$sorc325res = mysqli_query($connectXXX, $sorc325sql)
or die(mysqli_error($connectXXX));
if (mysqli_num_rows($sorc325res) < 1) {
$display_block = "<p><em>No topics exist.</em></p>";
} else {
$sorc325arycustctr = 0;
while ($sorc325row = mysqli_fetch_array($sorc325res)) {
$sorc325arycustctr++;
if (! ($sorc325arycustctr % 10)) {
$message .= '<br>';
}
$message .= $sorc325row['progName'].', ';
}
}
I am working on a php script to pull quest data from wowhead, particularly what starts and ends the quest, whether it is an item or a npc, and what its id or name is, respectively. This is the relevant portion of the whole script, with the rest involving database insertion. This is the completed snippet of code I came up with if anyone is interested. Also, seeing as this will run about 15,000 times, is this the best method of obtaining/storing the data?
<?php
$quests = array();
//$questlimit = 14987;
$questlimit = 5;
$currentquest = 1;
$questsprocessed = 0;
while($questsprocessed != $questlimit)
{
echo "<br>";
echo " Start of iteration: ".$questsprocessed." ";
echo "<br>";
echo " Attempting to process quest: ".$currentquest." ";
echo "<br>";
$quests[$currentquest] = array();
$baseurl = 'http://wowhead.com/quest=';
$fullurl = $baseurl.$currentquest;
$data = drupal_http_request($fullurl);
$queststartloc1 = strpos($data->data, 'quest_start');
$queststartloc2 = strpos($data->data, 'quest_end');
if($queststartloc1==false)
{$currentquest++; echo "No data for this quest"; echo "<br>"; continue;}
$questendloc1 = strpos($data->data, 'quest_end');
$questendloc2 = strpos($data->data, 'x5DDifficulty');
$startcaptureLength = $queststartloc2 - $queststartloc1;
$endcaptureLength = $questendloc2 - $questendloc1;
$quest_start_raw = substr($data->data,$queststartloc1, $startcaptureLength);
$quest_end_raw = substr($data->data, $questendloc1, $endcaptureLength);
$startDecoded = preg_replace('~\\\\x([A-Fa-f0-9]{2})~e', 'chr("0x$1")', $quest_start_raw);
$endDecoded = preg_replace('~\\\\x([A-Fa-f0-9]{2})~e', 'chr("0x$1")', $quest_end_raw);
$quests[$currentquest]['Start'] = array();
$quests[$currentquest]['End'] = array();
if(strstr($startDecoded, 'npc'))
{
$quests[$currentquest]['Start']['Type'] = "npc";
preg_match('~npc=(\d+)~', $startDecoded, $startmatch);
}
else
{
$quests[$currentquest]['Start']['Type'] = "item";
preg_match('~item=(\d+)~', $startDecoded, $startmatch);
}
$quests[$currentquest]['Start']['ID'] = $startmatch[1];
if(strstr($endDecoded, 'npc'))
{
$quests[$currentquest]['End']['Type'] = "npc";
preg_match('~npc=(\d+)~', $endDecoded, $endmatch);
}
else
{
$quests[$currentquest]['End']['Type'] = "item";
preg_match('~item=(\d+)~', $endDecoded, $endmatch);
}
$quests[$currentquest]['End']['ID'] = $endmatch[1];
//var_dump($quests[$currentquest]);
echo " End of iteration: ".$questsprocessed." ";
echo "<br>";
echo " Processed quest: ".$currentquest." ";
echo "<br>";
$currentquest++;
$questsprocessed++;
}
?>
These are called "escape sequences". Normally, they're used to represent characters not printable otherwise, but can encode any character. In php, you can decode them like this:
$text = '
quest_start\\x5DStart\\x3A\\x20\\x5Bitem\\x3D16305\\x5D\\x5B\\x2Ficon\\x5D\\x5B\\x2Fli\\x5D\\x5Bli\\x5D\\x5Bicon\\x20name\\x3Dquest_end\\x5DEnd\\x3A\\x20\\x5Burl\\x3D\\x2Fnpc\\x3D12696\\x5DSenani\\x20Thunderheart\\x5B\\x2Furl\\x5D\\x5B\\x2Ficon\\x5D\\x5B\\x2Fli\\x5D\\x5Bli\\x5DNot\\x20sharable\\x5B\\x2Fli\\x5D\\x5Bli
';
$decoded = preg_replace('~\\\\x([A-Fa-f0-9]{2})~e', 'chr("0x$1")', $text);
Which gives you a string similar to this:
quest_start]Start: [item=16305][/icon][/li][li][icon name=quest_end]End: [url=/npc=12696]Senani Thunderheart[/url][/icon][/li][li]Not sharable[/li][li
(obviously, some kind of BB-code). To remove all bbcodes, yet one replacement is necessary:
$clean = preg_replace('~(\[.+?\])+~', ' ', $decoded);