mysql_fetch_assoc "or die" statement triggered but still working - php

Please forgive me if this is a dumb question. I'm only a week into programming...
I'm getting my fetch error "or die" statement triggered on line 87 (at least in my editor it is 87, not sure how it will show up here). The strange thing is that it still works. The variables on the next two lines are being set and echoed correctly. Any ideas on why this is occurring would be appreciated. Thanks.
<?php
include 'header.php';
//$results_per_page=10;
//$count_results=mysql_query("SELECT COUNT('zipcodes') FROM jobposts");
//$page_results=$count_results;
//echo $count_results;
//if ($count_results%$results_per_page!=0)
//{
//$page_results+=1;
//}
/////// zip code search setup ///////////
$homezip=22102;
$radius=10;
$id=1;
$query="select longitude,latitude from zipcodes where zipcode='$homezip'";
$run_query=mysql_query($query) or die ("run query error");
$findzip2=mysql_fetch_array($run_query) or die ("test");
$homelong=$findzip2['longitude'] or die ("array error");
$homelat=$findzip2['latitude'] or die ("array error");
function calcDist($lat_A, $long_A, $lat_B, $long_B) {
$distance = sin(deg2rad($lat_A))
* sin(deg2rad($lat_B))
+ cos(deg2rad($lat_A))
* cos(deg2rad($lat_B))
* cos(deg2rad($long_A - $long_B));
$distance = (rad2deg(acos($distance))) * 69.09;
return $distance;
}
//////// end zip code search setup ////////////////
echo "<table border='1'>";
if (isset($_POST['search']))
{
$keywords=$_POST['keywords'];
$zipcode=$_POST['zipcode'];
if ($zipcode=="")
{
($zipcode_search="");
}
else
{
($zipcode_search=" and zipcode='$zipcode'");
}
if (!(isset($_POST['hidden'])))
{
$search = "select * from jobposts where description LIKE '%$keywords%' $zipcode_search";
$run_search=mysql_query($search) or die ("cannot run search");
//$zip_array=$main_array[''];
//echo count($zip_array)."<br>";
//echo $zip_array['zipcode'];
////store results in array
////pull zip codes out of array one at a time
////put the zip codes in the radius function - if statement
////if less than allowable radius - publish results
$count=0;
if (mysql_num_rows($run_search)>=1)
{
while ($query_rows=mysql_fetch_assoc($run_search))
{
$zip_array[$count]=($query_rows['zipcode']);
$zip_to_test=$zip_array[$count];
$testquery="select longitude,latitude from zipcodes where zipcode='$zip_to_test'";
$testrun_query=mysql_query($testquery) or die ("run query error");
$testfindzip2=mysql_fetch_assoc ($testrun_query) or die ("fetch error - testfindzip2");
$testlong=$testfindzip2['longitude'] or die ("array error");
$testlat=$testfindzip2['latitude'] or die ("array error");
$count++;
echo $testlong."<br>";
if (calcDist($homelat,$homelong,$testlat,$testlong)<$radius)
{
echo "<tr><td>".$query_rows['company']."</td><td>".$query_rows['zipcode']."</td></tr>";
}
}
}
else
{
echo "No results found.";
}
}
else
{
echo "Please submit search data before submitting.";
}
}
else
{
echo "Failed to submit search request.";
}
?>

mysql functions only return false, which would trigger your die(), if something went wrong with the query: syntax error, not connection, permission denied, etc...
A query which returns no results is NOT an error condition, and will not trigger the or die(). An empty result set is a perfectly valid result set.
As well,
$var = $othervar or die();
makes no sense whatsoever, as an assignment will always succeed (unless you run out of memory or something).

Script can not continue execution if die statement is called. I don't beleive in magic. So, output of your program is
...
fetch error - testfindzip2
...<br>
...
If "yes" - you've found some major bug in php. If "no", please, show it here.

Related

$connection->query($mysearch) not working

The error occurs like that, when i try to connect to DB to search something, it doesn't connects... here is the code below
$connection = new mysqli($db_server,$db_user,$db_pass,$db_name);
if($connection->connect_errno)
{
die ("Connection Failed");
}
$selcap = "SELECT * FROM captcha_codes ORDER BY RAND() LIMIT 1";
$seldcap = $connection->query($selcap);
if($seldcap === true)
{
while ($capdata = $seldcap->fetch_array(MYSQLI_BOTH))
{
$imglink = $capdata['image'];
$idcap = $capdata['id'];
$codecap = $capdata['code'];
}
} else {
$msgreg = "Couldn't connect to Captcha, please contact admin!";
}
The result is Couldn't connect to Captcha, please contact admin!
Use the less strict == comparison here: if($seldcap === true), that should solve the issue.
So the condition would look like: if($seldcap == true)
As mentioned by others, you could also check the number of results as well.
See the docs for mysqli::query() for more information on the results of that function.
If you want to check either query returns result or not use num_rows :
$seldcap = $connection->query($selcap);
if($seldcap->num_rows > 0)
{
//your while stuff
}
else{
//your error stuff
}

How to work with data from mysql in php-multidimensional array

I get null values when I run this code
$dataArray = mysql_query ("SELECT * from _$symbol order by date DESC limit 10;");
while ($ArrayData = mysql_fetch_assoc($dataArray)) {
$dayData [] = $ArrayData;
}
$todaysdate = $dayData[0]['date'];
$volPercentAVG = $dayData[0]['volume'] / $dayData[0]['_50dayVol'];
mysql_query ("update _$symbol set volPercentAvg=$volPercentAVG WHERE date=$todaysdate;");
It does not return anything, I am not sure I am approaching the MDarray correctly? I have triple checked the column names.
Anywhere to do with this would be helpfull
Thanks.
#Fred-ii- YOU DID IT! Can I or you make this an answer so I can vote for it? If I can I dont see how. – illcrx
Posting my comment as the answer in order to close the question.
If your date column contains any spaces or dots etc. then change WHERE date=$todaysdate
to/and quoting it WHERE date='$todaysdate'
For example: 2014-10-06 22:59:52
Would explain why you were not getting results.
However, I'm quite surprised/baffled that MySQL did not throw you a syntax error, bizarro.
Don't have time to read your entire bit right now, but I can give you my test method from our standard mysqli execution set:
print_r($Record);
This will allow you to see the structure and possibly where your error lies.
I'll also give you our framework which can be very useful (which is why we have it! LOL). Example framework (two functions) to make it easier to use mysqli in php with two lines for each query. It also allows for CLI or web output and debugging which will dump the query (so you can run it) and shows a print_r function to show results.:
This goes at the top:
define('DEBUG', false);
define('CLIDISPLAY', false);
if (CLIDISPLAY) {
define('PRE', '');
define('PRE_END', '');
} else {
define('PRE', '<pre>');
define('PRE_END', '</pre>');
}
require_once("/etc/dbconnect.php");
$DBLink = new mysqli($VARDB_server, $VARDB_user, $VARDB_pass, $VARDB_database, $VARDB_port);
if ($DBLink->connect_errno) {
printf(PRE . "Connect failed: %s\n" . PRE_END, $DBLink->connect_error);
exit();
}
Be sure you have a normal php file at /etc/dbconnect.php with your credentials in it (do not put these in a web folder in case php fails one day and exposes your passwords! LOL). Note that this file can then be shared and loaded only once. It should invoke
# Sample execution
$Query = "select * from vicidial_users where user='6666' and active='Y' limit 1";
$Records = GetData($DBLink, $Query);
print_r($Records[0]); // Single record return access via [0] to access a field named "id": $Records[0]['id']
// Multiple record return access via array walking
foreach ($Records as $Record) {
print_r($Record);
}
$Query = "update vicidial_users set active='Y' where user='6666' limit 1";
UpdateData($DBLink, $Query);
Functions (can be loaded from the credentials file or within your working file or put in a "functions.php" file and "require_once('functions.php');".
function GetData($DBLink, $Query) {
if (DEBUG) {
echo PRE . "Query: $Query\n" . PRE_END;
}
if ($Result = $DBLink->query($Query)) {
if (DEBUG) {
printf(PRE . "Affected rows (Non-Select): %d\n" . PRE_END, $DBLink->affected_rows);
}
while ($Record = $Result->fetch_assoc()) {
$ReturnData[] = $Record;
}
return $ReturnData;
} else {
if (DEBUG) {
printf(PRE . "Errormessage: %s\n", $DBLink->error);
printf("Affected rows (Non-Select): %d\n", $DBLink->affected_rows);
echo "No Records Returned\n" . PRE_END;
}
return false;
}
}
function UpdateData($DBLink, $Query) {
if (DEBUG) {
echo PRE . "Query: $Query\n" . PRE_END;
}
if ($Result = $DBLink->query($Query)) {
if (DEBUG) {
printf(PRE . "%s\n", $DBLink->info);
printf("Affected rows (Non-Select): %d\n" . PRE_END, $DBLink->affected_rows);
}
return;
} else {
if (DEBUG) {
printf(PRE . "Errormessage: %s\n", $DBLink->error);
printf("Affected rows (Non-Select): %d\n", $DBLink->affected_rows);
echo "No Records Returned\n" . PRE_END;
}
return;
}
}

Retrieve SQL statement from MySQL and process in PHP

I have successfully saved a number of SQL UPDATE statements to MySQL and now I want to retrieve them and have PHP process them. The code is below.
When I echo $query I get the correct SQL statements from the DB, but then when I try to process them, I get an error Warning: mysqli_query() [function.mysqli-query]: Empty query
It makes no sense to me and is driving me nuts! Do I have to do something else to $query so PHP can process it?
$num_rows = mysqli_num_rows($resultSQL);
if ($num_rows > 0)
{
while ($row = mysqli_fetch_array($resultSQL))
{
$strSQLupd[] = $row['uSQL'];
}
foreach ($strSQLupd as $query) {
$resultSQLupd = mysqli_query($link,
$query
);
if (!$resultSQLupd)
{
$error = 'Error fetching data: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
}
}
Are you setting the value of $link somewhere and is it required for what you're doing in this application? Also, remember that var_dump($varname); is always a helpful debugging tool.
foreach ($strSQLupd as $query) {
// put a var_dump below
var_dump($query);
$resultSQLupd = mysqli_query($query
);
if (!$resultSQLupd)
{
$error = 'Error fetching data: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
}
Give this a shot and look at the query string dumped to the screen. It may be null which is what's producing your error.

unable to execute query

Can somebody help me with this query.The page doesn't load up whenever i run this query.I'm pretty much sure its something really simple mistake which I'm unable to figure out.Your help is much appreciated.
$aggr_nr = $_REQUEST['stck_list_nr_01'].$_REQUEST['stck_list_nr_02'].$_REQUEST['stck_list_nr_03'];
echo $aggr_nr;
$sql="SELECT v.id FROM vers_einl_aggregatnummer AS v WHERE v.aggr_nr = $aggr_nr";
$aggr_id = mysql_query($sql);
if ($aggr_id == true)
{
echo "query 1 executed".$aggr_id;
else
{
echo("<br />Could not execute statement ".$sql);
}
}
//sanitize the inputs
$aggr_nr = mysql_real_escape_string($_REQUEST['stck_list_nr_01'].$_REQUEST['stck_list_nr_02'].$_REQUEST['stck_list_nr_03']);
echo $aggr_nr;
$sql="SELECT v.id FROM vers_einl_aggregatnummer AS v WHERE v.aggr_nr = '".$aggr_nr."'";//missing Quotes
$aggr_id = mysql_query($sql);
if ($aggr_id) {
while($result = mysql_fetch_array($aggr_id))
echo "ID NUMBER:".$result['id'];
} else {
echo "<br />Could not execute statement ".$sql;
}
there was a syntax error look at this
if ($aggr_id != false)//since on success resource type is returned.
{
echo "query 1 executed".$aggr_id;
}else
{
echo("<br />Could not execute statement ".$sql);
}
also
$aggr_nr = $_REQUEST['stck_list_nr_01'].$_REQUEST['stck_list_nr_02'].$_REQUEST['stck_list_nr_03'];
echo $aggr_nr;
if(isset($aggr_nr)&&is_numeric($aggr_nr))
{
$aggr_nr=mysql_real_escape_string($aggr_nr);
$sql="SELECT v.id FROM vers_einl_aggregatnummer AS v WHERE v.aggr_nr = $aggr_nr";
$aggr_id = mysql_query($sql);
}
Just a word about PHP errors not showing (page doesn't load up).
You can configure PHP to stop on errors and not show it. This should be the default setting on a production server to not show too much internal information in case of an error.
You can use these lines to display all the errors, but don't forget to turn it off again ;)
ini_set('display_errors', 1);
error_reporting(E_ALL);

PHP newbie with a perplexing piece of code

this ought to be simple, but it doesn't seem to be working for me. i have tested it with good and bad passwords. no matter what, it will not go into the else statement. i am not sure what i am missing
my code:
$mysqli = mysqli_connect("localhost", "joeuser", "somepass", "testDB");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$sql = "SELECT * FROM login_info";
$res = mysqli_query($mysqli, $sql);
if ($res) {
while ($newArray = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
$id = $newArray['first_name'];
$testField = $newArray['last_name'];
echo "The ID is ".$id." and the text is ".$testField."<br/>";
}
} else {
printf("Could not retrieve records: %s\n", mysqli_error($mysqli));
}
mysqli_free_result($res);
mysqli_close($mysqli);
}
If i send it a user and password that do exist it does the if statement fine, but if i send it a test for one that is not in the db it still won't do the else? why?
For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a MySQLi_Result object.
A query is only not successful if some serious error occurred. Simply because a SELECT query didn't match any rows doesn't make the query unsuccessful. You'll still get a MySQLi_Result object back. You'll want to check with mysqli_num_rows whether the result set contains any rows.
BTW, save yourself some nesting:
if (!$something) {
exit;
}
// continue as usual
No need for an else here, since you're exiting anyway. Makes things simpler.
Like this:
if ($res) {
while ($newArray = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
$id = $newArray['first_name'];
$testField = $newArray['last_name'];
echo "The ID is ".$id." and the text is ".$testField."<br/>";
}
}
if (!isset($id)) {
printf("Could not retrieve records: %s\n", mysqli_error($mysqli));
}

Categories