I am using WAMP v.2.5 on a Windows10 machine. My project is a PHP project running off a MySQL DB. It includes numerous AJAX calls, which work fine. I have one specific call however which is giving me a 'Unexpected end of input' error.
The call is made from a View, is directed to a global ajax handler PHP script which forwards the request to the Controller, which then asks the Model for the response. The appropriate Model method is being fired. The method contains error checking and will throw exceptions for an empty result. The DB Query within is valid, and returns results when used in the console. 9 times out of 10 however, the ajax fn will complete without receiving / reading the result of the query and thus generates the above error. Sometimes it will work fine.
When placed on a live server, everything works as it should. It's almost as if the script was running too quickly on the local machine to wait for the DB response or for any exception to be thrown.
Can anyone tell me how to properly test what's happening, or have a solution to the above problem?
EDIT:
Trail of affected code:
$(document).ready(function()
{
//some code
updateFilteredScheduleList();
//some code
});
function updateFilteredScheduleList()
{
var opts = $.extend(true, {}, dialogOptions);
getFilteredScheduleResults()
.done(function(returnedData)
{
var returnedDataObj = parseAjaxJSONResponse(returnedData);
if(returnedDataObj.hasOwnProperty('success'))
buildScheduleList(returnedDataObj.response);
})
.error(function(xhr, options, error)
{
opts.message = error;
displayDialog(opts);
return false;
});
}
function getFilteredScheduleResults()
{
var values = getFilterValues();
values.controller = 'WSVisits';
values.method = 'getFilteredScheduleResults';
console.log(values);
return $.ajax({
type: 'post',
cache: false,
data: values,
url: controllersAjaxPath
});
}
function getFilterValues()
{
var values = {};
//get values of view filters
return values;
}
function parseAjaxJSONResponse(data)
{
var opts = $.extend(true, {}, dialogOptions);
try
{
var tmp = JSON.parse(data);
if(tmp.hasOwnProperty('error'))
{
opts.message = tmp.error;
displayDialog(opts);
return false;
}
return tmp;
}
catch(e)
{
opts.message = e.message;
displayDialog(opts);
return false;
}
}
PHP method (slightly edited):
function getFilteredScheduleResults($args = null)
{
$id = intval($args['MyID']);
$region_id = (!$id) ? ( intval($args['RegionID']) > 0) ? intval($args['RegionID']) : 0 : 0;
$county_id = (!$id) ? ( intval($args['CountyID']) > 0) ? intval($args['CountyID']) : 0 : 0;
$language_id = (!$id) ? ( intval($args['LanguageID']) > 0) ? intval($args['LanguageID']) : 0 : 0;
$center_id = (!$id) ? ( intval($args['CenterID']) > 0) ? intval($args['CenterID']) : 0 : 0;
$type_id = (!$id) ? ( intval($args['TypeID']) > 0) ? intval($args['TypeID']) : 0 : 0;
$support_type_id = (!$id) ? ( intval($args['SupportTypeID']) > 0) ? intval($args['SupportTypeID']) : 0 : 0;
$address_token = (!$id) ? ( trim($args['AddressContains']) !== '') ? trim($args['AddressContains']) : null : null;
$purpose_id = (intval($args['PurposeID']) > 0) ? intval($args['PurposeID']) : 0;
$associate_id = (intval($args['AssociateID']) > 0) ? intval($args['AssociateID']) : 0;
if(!empty($args['From']))
{
$from_obj = DateTime::createFromFormat('d/m/Y', $args['From']);
$args['From'] = (!$from_obj) ? null : $from_obj->format('Y-m-d');
}
if(!empty($args['To']))
{
$to_obj = DateTime::createFromFormat('d/m/Y', $args['To']);
$args['To'] = (!$to_obj) ? null : $to_obj->format('Y-m-d');
}
$sql = " /*query*/ WHERE 1 ";
if($id)
$sql.= " AND ( s.MyID = :MyID ) ";
else
{
if($region_id)
$sql.= " AND ( RegionID = :RegionID ) ";
if($county_id)
$sql.= " AND ( CountyID = :CountyID ) ";
if($language_id)
$sql.= " AND ( LanguageID = :LanguageID ) ";
if($center_id)
$sql.= " AND ( CenterID = :CenterID ) ";
if($type_id)
$sql.= " AND ( s.TypeID = :TypeID ) ";
if($support_type_id)
$sql.= " AND ( SupportTypeID = :SupportTypeID ) ";";
if(!is_null($address_token))
$sql.= " AND ( UPPER(CONCAT_WS(' ', Add1, Add2, Add3, CityTown)) LIKE UPPER(:AddressToken) ) ";
}
$sql.= " GROUP BY s.MyID ORDER BY MyName ASC ";
$db = new Database();
try
{
$db->query($sql);
if($id)
$db->bind(':MyID', $id);
else
{
if($region_id)
$db->bind(':RegionID', $region_id);
if($county_id)
$db->bind(':CountyID', $county_id);
if($language_id)
$db->bind(':LanguageID', $language_id);
if($center_id)
$db->bind(':CenterID', $center_id);
if($type_id)
$db->bind(':TypeID', $type_id);
if($support_type_id)
$db->bind(':SupportTypeID', $support_type_id);
if(!is_null($address_token))
$db->bind(':AddressToken', '%' . $address_token . '%');
}
$db->execute();
$tmp = $db->fetchAllAssoc();
$get_assignments_only = (!empty($args['AssignmentsOnly']));
$returned = [];
$sql = " SELECT VisitID FROM visits_ws WHERE MyID = :MyID ";
if($purpose_id)
$sql.= " AND ( VisitPurposeID = :Purpose ) ";
if($associate_id)
$sql.= " AND ( ( Associate1ID = :AssociateID ) OR ( Associate2ID = :AssociateID ) OR ( Associate3ID = :AssociateID ) OR ( Associate4ID = :AssociateID ) ) ";
if(!empty($args['From']))
$sql.= " AND ( VisitDate >= :From ) ";
if(!empty($args['To']))
$sql.= " AND ( VisitDate <= :To ) ";
$db->query($sql);
foreach($tmp as $i => $t)
{
$db->bind(':MyID', $t['MyID']);
if($purpose_id)
$db->bind(':Purpose', $purpose_id);
if($associate_id)
$db->bind(':AssociateID', $associate_id);
if(!empty($args['From']))
$db->bind(':From', $args['From']);
if(!empty($args['To']))
$db->bind(':To', $args['To']);
$db->execute();
$visits = $db->fetchAllAssoc();
if( ($get_assignments_only) && (empty($visits)) )
continue;
if( ( ($purpose_id) || ($associate_id) || (!empty($args['From'])) || (!empty($args['To'])) ) && (empty($visits)) )
continue;
$tmp[$i]['HasVisits'] = (empty($visits)) ? 0 : 1;
$tmp = $schools[$i];
unset($tmp['Name']);
$schools[$i]['Address'] = build_address($tmp);
unset($schools[$i]['Add1']);
unset($schools[$i]['Add2']);
unset($schools[$i]['Add3']);
unset($schools[$i]['CityTown']);
unset($schools[$i]['CityPostCode']);
unset($schools[$i]['Name']);
unset($schools[$i]['LanguageID']);
unset($schools[$i]['PrincipalID']);
unset($schools[$i]['ContactID']);
unset($schools[$i]['TypeID']);
unset($schools[$i]['CenterID']);
unset($schools[$i]['SupportTypeID']);
unset($schools[$i]['CountyID']);
unset($schools[$i]['AreaCodeID']);
unset($schools[$i]['NetworkCodeID']);
unset($schools[$i]['RegionID']);
$returned[] = $tmp[$i];
}
return ['jct_success'=>'ok', 'response'=>$returned];
}
catch(PDOException $e)
{
return ['jct_error'=>$e->getMessage()];
}
}
Found the culprit:
I had to update my Apache max_input_vars to a higher limit to allow the number of individual parameters being returned to actually be returned. Post size was not the issue.
Related
I've got a stored procedure which looks like this:
-- GET INVITES
DROP PROCEDURE IF EXISTS pda.get_invite;
DELIMITER //
CREATE PROCEDURE pda.get_invite ( code varchar(100), invitator_id bigint )
BEGIN
SELECT * FROM pda_invites
WHERE (pda_invites.invitator_id = invitator_id || invitator_id IS NULL)
AND (pda_invites.code = code || code IS NULL);
END //
CALL get_invite ( 'cec95191-23db-11e9-86d7-26374278e97f', NULL );
That works in phpmyadmin and deliver the desired result.
Now on php side, I've got some kind of query builder in a procedure class with registered arguments, which looks like this:
public function toSQL ( ) {
// Make sure params are set
if ( $this->ready == false ) {
throw new Exception ( 'Called unready procedure ' . $this->PROCEDURE_NAME . '.' );
return false;
}
// Build query
$sql= 'CALL ' . $this->PROCEDURE_NAME . '( ';
$i = 0;
foreach ( $this->args as $arg ) {
$param = $this->params[ $i ][ $arg['NAME'] ];
// Apply valid null values
if ( $param == null || $param == 'null' ) {
$sql = $sql . 'NULL';
// Apply varchar strings
} else if ( $arg['TYPE'] == 'varchar' ) {
$sql = $sql . '\'' . $param . '\'';
// Apply numeric values
} else {
$sql = $sql . $param;
}
if ( ($i+1) < $this->args_count ) {
$sql = $sql . ', ';
}
$i++;
}
$sql = $sql . ' );';
return $sql;
}
In my DB Service I trigger that by calling:
$sql = $procedure->toSQL();
$result = $con->query($sql);
echo($sql);
echo json_encode($result);
That results in following equivalent query string which is also reflected by the mysql log:
CALL get_invite( 'cec95191-23db-11e9-86d7-26374278e97f', NULL );
But the problem and question is that it produces an empty result:
{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
Have anyone a clue why it coulds behave this way?
I want to update array data which comes in foreach loop. I am trying with script given bellow, it is only updating the very last row of data.
And it is giving the error in this line if ($updateInvoiceAddedItems AND $updateInvoiceSubtractedItems) .
PHP script
if (isset($_POST['submit'])) {
foreach($_POST['data'] as $key => $value) {
$invoiceItemId = intval($value['invoiceItemId']);
$itemId = intval($value['ItemId']);
$QTY = intval($value['QTY']);
$addedQTY = intval($value['addedQTY']);
$subtractedQty = intval($value['subtractedQty']);
$Total = is_numeric($value['total']) ? $value['total'] : false;
try {
if($addedQTY > 0) {
$updateInvoiceAddedItems = $db - > prepare("UPDATE `invoiceItems` SET
qty = qty + : addedQTY,
addedQty = addedQty + : addingQTY where id = : Iid ");
$updateInvoiceAddedItems - > execute(array(':Iid' => $itemId, ':addedQTY' => $addedQTY, ':addingQTY' => $addedQty));
}
elseif($subtractedQty > 0) {
$updateInvoiceSubtractedItems = $db - > prepare("UPDATE `invoiceItems` SET
qty = qty - : subtractedQty,
subtractedQty = subtractedQty + : subtractingQty where id = : iiId ");
$updateInvoiceSubtractedItems - > execute(array(':iiId' => $itemId, ':subtractedQty' => $subtractedQty, ':subtractingQty' => $subtractedQty));
}
if ($updateInvoiceAddedItems AND $updateInvoiceSubtractedItems) {
echo ' <script> alert("success") </script>';
exit;
} else {
echo ' <script> alert("Error") </script>';
}
} catch (PDOException $e) {
echo 'Connection failed: '.$e - > getMessage();
}
}
}
For the first question follow #Darius Answer And for the 2nd question change input name from name="data['+i+'][name]" to name="data[<?php echo $i; ?>][name]"
Consider this, you have
if($addedQTY > 0) {
}elseif($subtractedQty > 0) {
}
What happens if you submit a form with
$addedQty = 0, and $subtractedQty = 0 ?
There's nothing to set $updateInvoiceAddedItems && $updateInvoiceSubtractedItems
You get an error because those variables don't exist after the if() else() statement.
So it should look like :
if($addedQTY > 0) {
//code
}elseif($subtractedQty > 0) {
//code
}else{
// throw error or something because it's not what you expected.
}
// Then do the
if ($updateInvoiceAddedItems AND $updateInvoiceSubtractedItems) {
//code
}
OR you could do
if (isset($updateInvoiceAddedItems) && isset($updateInvoiceSubtractedItems)) {
//code
}
Also.. I think your && should be an "OR" statement so "||" ?
First of thank you for your help.
The code piece "while (sqlite_has_more($dres))" is using sqlite2 and I need sqlite3. If there isn't a replacement for has_more is there another code I can use to still Find whether or not more rows are available?
F.Y.I. The server updated their stuff which included their sqlite and now I have to fix this last peice of code to get the schedule to populate and not give me this error.
Fatal error: Non-static method SQLite3::open() cannot be called statically in /home/server/public_html/current-list.php on line 57
$row_num = 0;
if ($dbh = SQLite3::open($sked_path))
{
$qsql = "SELECT rowid,* FROM sked ORDER BY sk_dow_num, sk_time_start, sk_time_end";
$dres = SQLite3::query($dbh, $qsql);
if (SQLite3::num_Rows($dres) > 0)
{
$last_dow = "";
$last_start = "0000";
$last_end = "0000";
while (sqlite_has_more($dres))
{
$ska = Sqlite3Result::fetchArray($dres, SQLITE3_ASSOC);
$rid = $ska['rowid'];
$dow = $ska['sk_dow_name'];
$start = $ska['sk_time_start'];
$end = $ska['sk_time_end'];
$title = preg_replace("/<br\s*\/*>/", " ", $ska['sk_show_title']);
$show_dow = strtoupper($dow);
$show_start = strtoupper(formatTimeAmPm($start));
$show_end = strtoupper(formatTimeAmPm($end));
$show_style = "";
if (stristr($title, "Encore Show"))
$show_style = " class=\"$text_style\"";
Something like ...
<?php
$dbh = new SQLite3;
if ( !$dbh->open($sked_path) ) {
trigger_error('...error handling...', E_USER_ERROR);
}
else {
$dres = $dbh->query('
SELECT
rowid,*
FROM
sked
ORDER BY
sk_dow_num, sk_time_start, sk_time_end
');
if ( !$dres ) {
trigger_error('...error handling...', E_USER_ERROR);
}
else {
$ska = $dres->fetchArray(SQLITE3_ASSOC);
if ( !$ska ) {
onNoRecords();
}
else {
do {
doSomethingWithRowData($ska);
}
while( false!=($ska=$dres->fetchArray(SQLITE3_ASSOC)) );
}
}
}
(completely untested)
I am trying to update a table based on the input provided by a user. There are ten fields which a user can choose to input information into. The table I am trying to input too has a following structure.
leagueTrackID | leagueID | trackID
1 1 1
2 1 2
3 1 12
...
15 1 4
I need the code to update the fields where a new track has been added via looping though each inputted track and place it in a new field which has the matching criteria. The criteria which it needs to be match too is the leagueID. How can this be achieved without overwriting the same column row?
The code below is what I have so far but I have an error with trying to assign the php track variables to either a php array or php list.
$data = mysql_query("SELECT COUNT(leagueID) AS totalTracks , min(leagueTrackID) AS minLeagueID , max(leagueTrackID) AS maxLeagueID , leagueID , trackID
FROM leagueTracks
WHERE leagueID = '$vaildLeagueID'");
$info = mysql_fetch_array( $data );
// get posted track id and assign them to the php track varaibles
if ( $_POST['track1'] == '' ) { $track1 = $info['track1']; } else { $track1 = $_POST['track1']; }
if ( $_POST['track2'] == '' ) { $track2 = $info['track2']; } else { $track2 = $_POST['track2']; }
if ( $_POST['track3'] == '' ) { $track3 = $info['track3']; } else { $track3 = $_POST['track3']; }
if ( $_POST['track4'] == '' ) { $track4 = $info['track4']; } else { $track4 = $_POST['track4']; }
if ( $_POST['track5'] == '' ) { $track5 = $info['track5']; } else { $track5 = $_POST['track5']; }
if ( $_POST['track6'] == '' ) { $track6 = $info['track6']; } else { $track6 = $_POST['track6']; }
if ( $_POST['track7'] == '' ) { $track7 = $info['track7']; } else { $track7 = $_POST['track7']; }
if ( $_POST['track8'] == '' ) { $track8 = $info['track8']; } else { $track8 = $_POST['track8']; }
if ( $_POST['track9'] == '' ) { $track9 = $info['track9']; } else { $track9 = $_POST['track9']; }
if ( $_POST['track10'] == '' ) { $track10 = $info['track10']; } else { $track10 = $_POST['track10']; }
// Assign tracks selected to an array
$tracksArray = array($track1 , '$track2' , '$track3', '$track4', '$track5' , '$track6' ,'$track7', '$track8' , '$track9' , '$tack10');
// Counter
$trackNumber = '1';
// Get the lowest leagueTrackID based on the leagueID being updated
$min = $info['minleagueID'];
// Get the highest leagueTrackID based on the leagueID being updated
$max = $info['maxLeagueID'];
while($min != $max) {
$updateLeagueTracks = mysql_query ("UPDATE userLeague SET trackID = $trackArray['$tracknumber'] WHERE leagueID = '$vaildLeagueID'");
$addTracks = mysql_query($updateLeagueTracks);
$trackNumber++;
$min++;
} // closes the for loop
I recently migrated a PHP site to my server and after migration I receive this error message. As I'm not really familiar with PHP, I'd really appreciate any help. Thanks.
Warning: strpos() expects parameter 1 to be string, resource given in
.../public_html/store /product_list.php on line 121
Line 121 is as follows...
$exists = (strpos($handle, "Resource id") !== false) ? true : false;
Here is the rest of the code on the top of the page for relevance.
<?php session_start();
include_once("../includes/define.inc.php");
include("../includes/common.php");
include("../includes/mysql_functions.php");
if( isset( $_GET['category'] ) )
{
$exists = checkIfExists("aw_category", "aw_category_urlalias='". $_GET['category']."'", "aw_category_id");
if( !$exists )
{
header("Location: " . PRODUCT_LIST );
}
}
$get_category = ( isset( $_GET['category'] ) ) ? $_GET['category'] : "";
$category_id = ( $get_category == "" ) ? "" : getCategoryIDByAlias( $get_category );
$get_page = (isset($_GET['page']) ) ? $_GET['page'] : 0;
/*category menu*/
$qry_cat = "SELECT aw_category_urlalias, aw_category_id,aw_category_name,aw_category_order,aw_category_status FROM aw_category WHERE aw_category_status = 1 ORDER BY aw_category_order asc";
$result_cat = Query($qry_cat);
/*product*/
$qry_pro = "SELECT *
FROM aw_product
INNER JOIN aw_category
ON aw_product.aw_product_category = aw_category.aw_category_id
INNER JOIN aw_image
ON aw_product.aw_product_id = aw_image.aw_img_prodid
WHERE aw_product.aw_product_status = 1";
if( $category_id == "" )
{ //Feature Product
$qry_pro .= " AND aw_product.aw_product_category = 1";
} else {
$qry_pro .= " AND aw_product.aw_product_category = ".$category_id."";
}
$qry_pro .= " GROUP BY aw_product.aw_product_id
ORDER BY aw_product.aw_product_priority desc,aw_product.aw_product_date desc";
if( $get_category=="" )
{ //Feature Product
$qry_pro .= " LIMIT 6";
}
$result_pro = Query( $qry_pro );
//$row_pro = mysql_fetch_array($result_pro);
$result_pro2 = Query( $qry_pro );
if( !$get_category == "" )
{
/*Pagination*/
$num_per_page= 12;
$num_rows = mysql_num_rows($result_pro);
$num_pages = ceil($num_rows/$num_per_page);
$nav = "";
$begin = $get_page * $num_per_page;
$qry_pro .= " LIMIT " . $begin . ",12";
$result_pro = Query( $qry_pro );
$row_pro = mysql_fetch_array($result_pro);
if( $get_page > 0 )
{
$nav ="<a class=\"page_a\" href=\"".PRODUCT_LIST."?category=".$get_category."&page=".( $get_page-1 )."\">« Previous</a> | ";
}
for($p=0;$p<$num_pages;$p++)
{
if($get_page == $p)
$nav .="<a class=\"page_a\" style='text-decoration:underline' href=\"".PRODUCT_LIST."?category=".$get_category."&page=".$p."\">".($p+1)."</a> | ";
else
$nav .="<a class=\"page_a\" href=\"".PRODUCT_LIST."?category=".$get_category."&page=".$p."\">".($p+1)."</a> | ";
}
if($get_page<$num_pages-1)
{
$nav .="<a class=\"page_a\" href=\"".PRODUCT_LIST."?category=".$get_category."&page=".($get_page+1)."\"> Next »</a>";
}
}//-------
/*news*/
$qry_news = "SELECT aw_news_title FROM aw_news ORDER BY aw_news_date desc LIMIT 8";
$result_news = Query($qry_news);
function getCategoryIDByAlias( $alias )
{
$query = "SELECT aw_category_id FROM aw_category WHERE aw_category_urlalias='".$alias."'";
$rs = Query( $query );
$row = mysql_fetch_array( $rs );
return $row['aw_category_id'];
}
function checkIfThumbExists( $thumb )
{
//$exists = ( file_exists( $img_src_thumb ) ) ? true : false;
//echo $exists;
//$exists = ( is_file( $img_src_thumb ) ) ? true : false;
//echo $exists;
//$AgetHeaders = #get_headers( $img_src_thumb );
//$exists = ( preg_match( "|200|", $AgetHeaders[0] ) ) ? true : false;
//echo $exists;
//$header_response = get_headers($img_src_thumb, 1);
//$exists = ( strpos( $header_response[0], "404" ) !== false ) ? false : true;;
//echo $exists;
$handle = #fopen($thumb, 'r');
$exists = (strpos($handle, "Resource id") !== false) ? true : false;
if( $exists )
{
$size = getimagesize( $thumb );
if( $size[3] == 'width="214" height="214"')
{
$exists = true;
} else {
$exists = false;
}
}
return $exists;
}
?>
Try replacing line 121 with the following:
$handle = #file_get_contents($thumb);
$handle = #fopen($thumb, 'r');
$handle not is string
The error is clear. Read manual of stropos()
It need to take a string in parameter, but in you case you set there one source($handle = #fopen($thumb, 'r');) and one string("Resource id")
Use file_get_contents, as example.
fopen returns a resource and strpos expects the first parameter to be a string.
You may use file_get_contents instead, but are you sure you want to check the binary data of a image?
$data = file_get_contents($thumb);
I don't know what are you trying to do with this line, but if you want to weather the file exists or not, i recommend you to use the native PHP functión file_exists, that gives you the chance to check if the file exists or not:
$exists = file_exists($thumb)
Here is PHP reference.
http://es1.php.net/manual/es/function.file-exists.php
As mentioned in other answers you are giving strpos a file handle or 'resource', which is wrong.
However, it looks like you want to test is if the file exists so I would simply do:
$handle = #fopen($thumb, 'r');
if($handle)
{
// File exists
}
else
{
// File doesn't exist
}
As fopen() will return a pointer (resource) if the file can be opened, else false if not.
file_get_contents() looks like the wrong option as it appears you are trying to open and image, so why would you want to search the binary for a string.