unable to execute query - php

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);

Related

PHP Check mysqli_num_rows not working

I've searched thoroughly and nothing seems to be working; I have this code here which posts into my database but the problem is I am trying to run a conditional which checks if a row exists using the mysqli_num_rows function, but it is not actually working. I have tried many different versions and other functions as well such as mysqli_fetch_row, but nothing seems to work. Here is my code:
if (!empty($_POST)) {
$db_conx="";
$name = $_POST['name'];
$module = $_POST['module'];
$secret = $_POST['secret'];
$uid1 = $dmt->user['uid'];
$queryA = "INSERT INTO table_a (uid1,name,module,secret) VALUES ('$uid1','$name','$module','$secret')";
$resultA = mysqli_query($db_conx,$queryA);
$queryB = "SELECT 1 FROM table_a WHERE name='$name' LIMIT 1";
$resultB = mysqli_query($db_conx,$queryB);
$resultC = mysqli_query($db_conx,$queryB);
$query = mysqli_query($db_conx,"SELECT * FROM table_a WHERE name='$name'");
if (empty($name)||empty($module)||empty($secret)) {
echo "Oops! Can't leave any field blank <br />";
exit();
} elseif(mysqli_num_rows($query) > 0){
echo "name already exists.";
exit();
} elseif ($db_conx->query($queryA) === TRUE) {
echo "New record created successfully.";
exit();
} else {
echo "Error: " . $queryA . "<br>" . $db_conx->error;
exit();
}
}
As you can see the query appears to run but indeed does not do what it's told.
The first line of code inside your IF is destroying the variable you are using to hold the database connection
if (!empty($_POST)) {
$db_conx=""; // get rid of this line
So basically nothing using the mysqli API will work.
ALSO:
Add these as the first 2 lines of a script you are trying to debug
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
as you are obviously not readng your php error log

Updating a record using passed variables

This Update Query seems to work inside MySQL WorkBench but when applying it to my php application doesn't want to work... Both the $TotalSeats & $PerfID parameters have been tested and they output the desired number.
Is this a minor syntax error or am I missing a trick here?
$deductSeats = "UPDATE perf SET Seats=(SELECT SUM(Seats -'$TotalSeats')) WHERE PerfID = '$PerfID'";
if (mysqli_query($conn,$deductSeats))
{
echo 'Query Worked!<br>';
}
else
{
echo 'Query Didnt Work<br>';
}
$deductSeats = "deductSeats(`$TotalSeats`,`$PerfID`)";
You can try :
$deductSeats = "UPDATE perf SET `Seats` = `Seats` - ".$TotalSeats." WHERE PerfID = ".$PerfID;
if (mysqli_query($conn,$deductSeats)) {
echo 'Query Worked!<br>';
} else {
echo 'Query Didnt Work<br>';
}

Mysql_num_rows not returning any value

What is the problem in my code ? every time it echo This image used as cover image , but delete query work properly.how can i fix it?
<?php
session_start();
if(!empty($_SESSION['userId']) && !empty($_SESSION['name'])){
include ('connect.php');
dbConnect();
if (isset($_GET['ximgid'])) {
$del=mysql_query("Delete FROM project_image WHERE ximgid='".$_GET['ximgid']."' And coverflag !='1'");
$delete=mysql_num_rows($del);
if($delete==1){
echo "<script type='text/javascript'>alert('Sucessfully Delete !!!')</script>";
echo "<script>javascript:window.location = 'projectImage.php'</script>";
}else{
echo "<script type='text/javascript'>alert('This Image Used As Cover Image')</script>";
echo "<script >window.location.href = 'projectImage.php'</script>";
}
}else{
echo "<script>javascript:window.location = 'index.php'</script>";
}
}
?>
mysql_num_rowsonly works with selectstatement.
For delete statements you have to use mysql_affected_rows
Here the part of the documentation of mysql_affected_rows:
Retrieves the number of rows from a result set. This command is only
valid for statements like SELECT or SHOW that return an actual result
set. To retrieve the number of rows affected by a INSERT, UPDATE,
REPLACE or DELETE query, use mysql_affected_rows().
mysql_affected_rows() is the way to go
$delete=mysql_affected_rows($del);
if($delete>0){
echo "<script type='text/javascript'>alert('Sucessfully Delete !!!') </script>";
echo "<script>javascript:window.location = 'projectImage.php'</script>";
}else if($delete==0){
echo "<script type='text/javascript'>alert('This Image Used As Cover Image')</script>";
echo "<script >window.location.href = 'projectImage.php'</script>";
}else{
echo "<script type='text/javascript'>alert('mysql error')</script>";
}
I had to solve my problem in an alternative way which is given below:
<?php
session_start();
if(!empty($_SESSION['userId']) && !empty($_SESSION['name'])){
include ('connect.php');
dbConnect();
if(isset($_GET['ximgid'])){
$selQuery = "SELECT coverflag FROM project_image WHERE ximgid ='".trim($_GET['ximgid'])."' AND zid = '1000' AND xpid = '".trim($_GET['pid'])."'";
$flagtResult=mysql_query($selQuery);
$flagRow=mysql_fetch_array($flagtResult);
mysql_free_result($flagRow);
$cover=$flagRow[0];
if($cover == 1){
echo "<script type='text/javascript'>alert('Used as cover picture')</script>";
echo "<script>javascript:window.location = 'projectImage.php'</script>";
}else{
$sql = "DELETE FROM project_image WHERE ximgid = '".trim($_GET['ximgid'])."' AND coverflag != '1' AND zid = '1000' AND xpid = '".trim($_GET['pid'])."'";
$result = mysql_query($sql) or die(mysql_error());
if($result > 0){
echo "<script type='text/javascript'>alert('Sucessfully Detele !!!')</script>";
echo "<script>javascript:window.location = 'projectImage.php'</script>";
}
}
}
}else{
echo "<script>javascript:window.location = 'index.php'</script>";
}
?>
Now I can get my proper output.. Thanks Everyone.
first of all it appears that you are escaping ximgid and coverflag with ' which would throw a syntax error in your sql if those were not varchar fields.
$del=mysql_query("Delete FROM project_image WHERE ximgid=".$_GET['ximgid']." And coverflag !=1;");
Second issue to address would be that you are taking a $_GET parameter and putting it directly into your SQL query which is just trouble looking to happen so I would suggest next changing it to:
$del=mysql_query("Delete FROM project_image WHERE ximgid=".mysql_real_escape_string($_GET['ximgid'])." And coverflag !=1;");
if you need extra help debugging your SQL you can always temporarily put a call to
echo mysql_error();
after your call to mysql_query in order to show the error message from the server.

mysqli deletion

<?php
if (intval($_GET['page']) == 0) {
redirect_to("staff.php");
}
$id = mysqli_prep($_GET['page']);
$query3 = "DELETE FROM page WHERE id = {$id}, LIMIT 1";
$result = mysqli_query($connection, $query3);
if (mysqli_affected_rows($connection) == 1) {
redirect_to("staff.php");
} else {
// Deletion Failed
echo $id ."<br />" . $query3 . "<br />" . $result . "<p>Subject
deletion failed.</p>";
echo "<p>" . mysqli_error() . "</p>";
echo "Return to Main Page";
}
// Keep on working Edit:2#
mysqli_query($connection, "DELETE FROM pages WHERE id = 11 ");
//- Works
Edit 3#
$id = $_GET['page'];
echo "<p>" . $id ."</p>";
$query3 ="DELETE FROM pages WHERE id = {$id} ";
mysqli_query($connection,$query3 );
// Still Works -- YaY for working backwards
// Edit #4 By "now it might be obvious what my error was "pages" not "page"
// Thanks everyone - And thank you for telling me about the error page
// My defense - newbie- Anyway Lesson from this - working backwards
// Takes a while, Error checking Fast!!!!!!
?>
$connection is started and selected. The $id is selected successfully, and the $page = $id, but it still will not work. $query 3 seems fine, but Deletion failed. I don't have any idea what the error is. Thanks for any help in advance.
-Josh Edit Check Error Check
You have a comma after the ID:
$query3 = "DELETE FROM page WHERE id = {$id}, LIMIT 1";
^ remove this
I don't have any idea what the error is.
That's because you didn't check. Every time you prepare or execute a query, you need to check for errors. Most of the functions in mysqli return FALSE if they encounter an error.
$result = mysqli_query($connection, $query3);
if ($result === false) {
trigger_error(mysqli_error($connection), E_USER_ERROR);
header("Location: /error.php");
exit;
}
The failure to check for error cases is one of the most common blunders committed by database programmers.
if ($page == get_page_by_id($id)) {
== for comparison
=== to compare the value and the cast
$val = true;
if ($val === true) {
echo "\$val is bool(true)";
}
if ($val == "true") {
echo "\$val matches value";
}
if ($val === "true") {
// this will never happen
} else {
echo "\$val doesnt === \"true\"";
}
try to use php_flag display_errors on in your .htaccess
this will allow you to see and identify php errors.

mysql_fetch_assoc "or die" statement triggered but still working

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.

Categories