EDIT1 : used double quotes and single quotes but I am getting same error.
EDIT2 : same query is returning me result in mysql shell
I am selecting a row from a table.
if(!isset($_GET['title']) || !isset($_GET['user'])){
echo "hi"; //something come here
}
else{
$title = $_GET['title'];
$title = mysqli_real_escape_string($conn,$title);
$user = $_GET['user'];
$user = mysqli_real_escape_string($conn,$user);
echo $title ;
echo $user ;
// tried giving value directly to test but no luck
$query = "SELECT * FROM site WHERE client=\"Chaitanya\" && title=\"werdfghb\" ";
$result5 = mysqli_query($conn,$query) or die(mysqli_error());
$count = mysqli_num_rows($result5);
echo $count ;
while($result9 = mysqli_fetch_array($result5)){
$kk=$result9['url'];
echo $kk ;
}
$page = $kk;
include ( 'counter.php');
addinfo($page);
}
In my database there is a row with columns title and client and the values I entered are in that row but when I echo count(no of rows) it is showing zero.
Is there anything wrong with code ?
The error you are getting is due to the line
$page = $kk;
in this code $kk is not declared previously. The defined $kk is in the while loop scope.
declare the variable like this in the outer scope from the while loop
...
$kk = null;
while($result9 = mysqli_fetch_array($result5)) {
$kk = $result9['url'];
echo $kk ;
}
$page = $kk;
...
Error on Fetching Data
You have to crack you SQl into smaller pieces and test the code like this.
run the query SELECT * FROM site without any where and get the count
run the query SELECT * FROM site WHERE client='Chaitanya' and get the count
SELECT * FROM site WHERE title='werdfghb' and check the count
Then run the whole query
And see the results. This way u can find out in where the issue is in your SQL code. I prefer you use the mysql client to execute this queries
As I pointed out in my comment, $kk is undefined in the $page = $kk;, since it is declared in the while loop.
Do something like:
$kk = ''; //can also do $kk=NULL; if you want.
while($result9 = mysqli_fetch_array($result5)) {
$kk=$result9['url'];
echo $kk ;
}
$page = $kk;
try this one
$client = "Chaitanya";
$title = "werdfghb";
$query="SELECT * FROM site WHERE client='".$client."' and title='".$title."' ";
you can also use this
$query="SELECT * FROM site WHERE client={$client} and title={$title} ";
Related
I have this script executing as a cron job everyday to update days remaining to pay invoices. I first query every row of my table and attempt to store the data in a multidimensional array but this seems to be storing everything I query in the first element of my array.
Here's my script:
<?php
include '../inc/dbinfo.inc';
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
error_log( "################################################# UpdateVendorInvoiceDays.php #################################################" );
$three = 3;
$fetchAllInvoices = "SELECT VENDORINVOICEID, VdrInvoiceReceived, PaymentDue, COUNT(*), DATEDIFF(PaymentDue, NOW()) FROM tblVendorInvoices WHERE VdrInvoiceStatusID != ?";
$getInvoices = $conn->prepare($fetchAllInvoices);
$getInvoices->bind_param("i", $three);
$getInvoices->execute();
$result = $getInvoices->get_result();
$rows = array();
$j = 0;
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]); //Only outputs one row
//UPDATE DAYS REMAINING IN EACH ENTRY THAT ISNT PAID
$updateDaysRemaining = "UPDATE tblVendorInvoices SET DaysRemaining = ? WHERE VENDORINVOICEID = ? AND VdrInvoiceStatusID ! = ?";
$setDays = $conn->prepare($updateDaysRemaining);
$k = 0; //incrementor
$numberOfEntries = $rows['COUNT(*)'];
for($k;$k<$numberOfEntries;$k++){
$setDays->bind_param("iii", $rows[$k]["DATEDIFF(PaymentDue, NOW())"],
$rows[$k]['VENDORINVOICEID'], $three);
if($setDays->execute()){
error_log('Cron success');
}else{
error_log('Cron fail');
}
}
?>
Currently the output from my first query is:
[[{"VENDORINVOICEID":88,"VdrInvoiceReceived":"2018-08-21","PaymentDue":"2018-07-27","COUNT(*)":2,"DATEDIFF(PaymentDue, NOW())":-25}]]
and my error log only gives me a notice for $rows['COUNT(*)'] being undefined (which makes sense)
I've looked at other answers here but they don't seem to have the same structure as I do.
EDIT: I also have 2 rows in my database but this only puts out one. I forgot to mention this.
There are a couple of simplifications to get all of the rows. Instead of...
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]);
You can just return all rows using fetch_all()...
$rows = $result->fetch_all (MYSQLI_ASSOC);
echo json_encode($rows);
Then encode the whole array and not just the one element - which is what $rows[0][0] was showing you.
As for you other problem - change in your select statement to
COUNT(*) as rowCount
and then you can use this alias for the field reference...
$rows['COUNT(*)']
becomes
$rows['rowCount']
I was wondering why I got an error saying Notice: Undefined variable: query_add_landdev_temp_payroll in C:\xampp\htdocs\op\ajax\ajaxLanddevNTPPayroll.php on line xx. for the past 2 weeks, it works perfect. When I tried to execute the code today, I got that kind of error. Here is my code:
$query_get_payroll = mysqli_query($new_conn, "SELECT ntp_with_ob_payroll_transaction.ntp_id, ntp_with_ob_payroll_transaction.allotment_code, ntp_with_ob_payroll_transaction.category_name, ntp_with_ob_payroll_transaction.block_number, ntp_with_ob_payroll_transaction.activity, ntp_with_ob_payroll_transaction.lot_number, ntp_with_ob_payroll_transaction.labor_cost, other_budget.quantity FROM ntp_with_ob_payroll_transaction JOIN other_budget ON ntp_with_ob_payroll_transaction.ob_id = other_budget.ob_id WHERE other_budget.transaction_id = $transaction_id AND other_budget.ob_number = '$ntp_number' AND is_payroll = 0");
while($row = mysqli_fetch_assoc($query_get_payroll)) {
$ntp_id = $row['ntp_id'];
$allotment_code = $row['allotment_code'];
$category_name = $row['category_name'];
$block_number = $row['block_number'];
$activity = $row['activity'];
$lot_number = $row['lot_number'];
$labor_cost = $row['labor_cost']; //this is equivalent to unit cost
$quantity = $row['quantity']; //this is equivalent to total percentage
$query_add_landdev_temp_payroll = mysqli_query($new_conn, "INSERT INTO temp_payroll_landdev(ntp_id, userid, transaction_id, ntp_number, contractor_name, allotment_code, category_name, block_number, activity, lot_numbers, regular_labor, quantity) VALUES($ntp_id, $_SESSION[userid], $transaction_id, '$ntp_number', '$fullname', '$allotment_code', '$category_name', $block_number, '$activity', '$lot_number', '$labor_cost', '$quantity')");
}
if($query_add_landdev_temp_payroll) {
echo 1;
//database file name
$database_file = $database.'.sql';
$new_database_file = $new_database.'.sql';
if(file_exists('backup/'.$new_database_file)) {
unlink('backup/'.$new_database_file);
//backup project database
$command = "C:/xampp/mysql/bin/mysqldump --host=$new_host --user=$new_user --password=$new_pass $new_database > backup/$new_database_file";
system($command);
} else {
//backup project database
$command = "C:/xampp/mysql/bin/mysqldump --host=$new_host --user=$new_user --password=$new_pass $new_database > backup/$new_database_file";
system($command);
}
} else {
echo 0;
}
If the query doesn't return any rows, mysqli_fetch_assoc() will return false the first time, so you'll never go into the loop, and never assign to the variable. If you then try to use the variable you get that warning.
You can give it a default initial value before the loop, or you can change your test to:
if (!empty($query_add_landdev_temp_payroll))
BTW, the variable only contains the result of the INSERT in the last iteration of the loop. Maybe you should put the if block inside the loop, right after the INSERT?
Also, there's no need to do INSERT in a loop. You can do the whole thing with a single query:
INSERT INTO temp_payroll_landdev(ntp_id, userid, transaction_id, ntp_number, contractor_name, allotment_code, category_name, block_number, activity, lot_numbers, regular_labor, quantity)
SELECT ntp_with_ob_payroll_transaction.ntp_id, ntp_with_ob_payroll_transaction.allotment_code, ntp_with_ob_payroll_transaction.category_name, ntp_with_ob_payroll_transaction.block_number, ntp_with_ob_payroll_transaction.activity, ntp_with_ob_payroll_transaction.lot_number, ntp_with_ob_payroll_transaction.labor_cost, other_budget.quantity
FROM ntp_with_ob_payroll_transaction
JOIN other_budget ON ntp_with_ob_payroll_transaction.ob_id = other_budget.ob_id
WHERE other_budget.transaction_id = $transaction_id AND other_budget.ob_number = '$ntp_number' AND is_payroll = 0
just update the if condition like this,
if(isset($query_add_landdev_temp_payroll) && $query_add_landdev_temp_payroll)
Looks like you are using a variable inside a while command. So outside that command this variable will not define. Try use $query_add_landdev_temp_payroll = null; before while command. Hope it help you!
CODE :
$nerd_result = mysql_query("select * from nerd_profile where nerd_reg_no = '$reg_no'");
$nerd_data = mysql_fetch_array($nerd_result);
$tags = array();
$tags = explode(",",$nerd_data['nerd_interests']);
for($i = 0; $i < sizeof($tags)-1; $i++)
{
if($i != sizeof($tags)-2)
{
$sub_query = $sub_query."`tags` like %".$tags[$i]."% or ";
}
else
{
$sub_query = $sub_query."`tags` like %".$tags[$i]."% ";
}
}
$proper_query = "select * from `qas_posts` where ".$sub_query." and `post_date` like '%$today%'";
$result = mysql_query($proper_query);
while($each_qas = mysql_fetch_array($result))
Description :
I am adding the like clause along with php variable in a string and concatenating it with the further variables with like clause to come. In the end when I echo I get the perfect query that I want but
mysql_fetch_array()
does not accept that generated query rather if I hard code it , it works perfect what am I doing wrong ?? can I do that ??
When doing string comparisons in mysql you need to make sure you have quotes around your comparison value.
$sub_query = $sub_query."`tags` like '%".$tags[$i]."%' or ";
and
$sub_query = $sub_query."`tags` like '%".$tags[$i]."%' ";
for ($i=0; $i<$count; $i++) {
$appid = $chk[$i];
include "dbconnect.php";
$selectquery = mysql_query("SELECT * FROM regform_admin WHERE tid = '$appid'");
$fetch = mysql_fetch_array($selectquery);
$tid = $fetch['tid']; $username = $fetch['username']; $c_month = $fetch['month']; $c_day =$fetch['day']; $c_year = $fetch['year'];
$c_month2 = $fetch['month2']; $c_day2 =$fetch['day2']; $c_year2 = $fetch['year2'];
$pickup = "".$c_month."/".$c_day."/".$c_year."";
$return = "".$c_month2."/".$c_day2."/".$c_year2."";
$pickuploc = "".$fetch['pickupret']." "." ".$fetch['speclocation']."";
$desti = "".$fetch['destination']." "." ".$fetch['location']."";
$vehicle1 = $fetch['vehicle1'];
$datesent = date("n j, Y; G:i"); ;
$rand = rand(98765432,23456789);
include "vehicledbconnect.php";
$vquery = mysql_query("SELECT * FROM vehicletbl WHERE vehicle = '$vehicle1'");
$getvquery = mysql_fetch_array($vquery);
$maxcars = $getvquery['maxcars'];
$carsleft = $getvquery['carsleft'];
if ($carsleft == 0) {
echo '
<script language="JavaScript">
alert("Cannot move reservation to Pending for payment status. No available vehicles left for this reservation.");
</script>';
echo "$vehicle1";
}
Hi guys my problem here is that the $vehicle is not returning its values if it is inserted in a database query ($vquery = mysql_query("SELECT * FROM vehicletbl WHERE vehicle = '$vehicle1'");) but if it is echoed, it return its value. The logic here is that it will select all the values from vehicletbl wherein the value of any values in 'vehicle' column will be equal to the $vehicle1. Thanks for the help!
You've got ZERO error handling on your queries. Try adding some debugging to the query calls:
$result = mysql_query(...) or die(mysql_error());
The rest of the code is ugly, but looks "ok", so start looking at WHY you're not getting anything back from the queries.
Never ever assume a query succeeds.
try this to debug :
$sql = "SELECT * FROM vehicletbl WHERE vehicle = '" . $vehicle1 . "'";
$vquery = mysql_query($sql) or die(mysql_error() . "\n<br>$sql");
thats what i do to find errors in my sql.
Noob programmer ? Here are some things to know :
for ($i=0; $i<$count; $i++) {
$appid = $chk[$i];
// Replaced By ...
foreach($chk as $appid){
http://php.net/manual/en/control-structures.foreach.php
// Include the file before the loop ! You're including 20 times your file, but you just need to do it once ! Another thing to know:
include_once("dbconnect.php");
http://php.net/manual/en/function.include-once.php
$desti = "".$fetch['destination']." "." ".$fetch['location']."";
// WHY ?? Isn't that easier to do this ?
$desti = $fetch['destination']." ".$fetch['location'];
And security :
// Don't forget to escape your variables before putting it in mysql queries
$appid = mysql_real_escape_string($appid);
$selectquery = mysql_query("SELECT * FROM regform_admin WHERE tid = '$appid'");
Best way to defend against mysql injection and cross site scripting
There are other remarks, but try to improve those points first !
i am trying to display data based on wether data in a field is new. instead of showing only the data that is new it is showing all data. can someone point out my error. many thanks
<?php
include("../../js/JSON.php");
$json = new Services_JSON();
// Connect to MySQL database
mysql_connect('localhost', 'root', '');
mysql_select_db(sample);
$page = 1; // The current page
$sortname = 'id'; // Sort column
$sortorder = 'asc'; // Sort order
$qtype = ''; // Search column
$query = ''; // Search string
$new = 1;
// Get posted data
if (isset($_POST['page'])) {
$page = mysql_real_escape_string($_POST['page']);
}
if (isset($_POST['sortname'])) {
$sortname = mysql_real_escape_string($_POST['sortname']);
}
if (isset($_POST['sortorder'])) {
$sortorder = mysql_real_escape_string($_POST['sortorder']);
}
if (isset($_POST['qtype'])) {
$qtype = mysql_real_escape_string($_POST['qtype']);
}
if (isset($_POST['query'])) {
$query = mysql_real_escape_string($_POST['query']);
}
if (isset($_POST['rp'])) {
$rp = mysql_real_escape_string($_POST['rp']);
}
// Setup sort and search SQL using posted data
$sortSql = "order by $sortname $sortorder";
$searchSql = ($qtype != '' && $query != '') ? "where ".$qtype." LIKE '%".$query."%' AND new = 1" : '';
// Get total count of records
$sql = "select count(*)
from act
$searchSql";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$total = $row[0];
// Setup paging SQL
$pageStart = ($page -1)*$rp;
$limitSql = "limit $pageStart, $rp";
// Return JSON data
$data = array();
$data['page'] = $page;
$data['total'] = $total;
$data['rows'] = array();
$sql = "select *
from act
$searchSql
$sortSql
$limitSql";
$results = mysql_query($sql);
while ($row = mysql_fetch_assoc($results)) {
$data['rows'][] = array(
'id' => $row['id'],
'cell' => array($row['id'], $row['slot'], $row['service'], $row['activity'], $row['department'], $row['company'], $row['address'], $row['user'], $row['item'], $row['filebox'], date('d/m/Y',strtotime($row['date'])), $row['quantity'], $row['type'], $row['new'])
);
}
echo $json->encode($data);
?>
You should debug SQL by looking at the SQL query, not at the PHP code that produces the SQL query. If you echo $sql and look at it, you'll probably see any syntax errors much more easily.
You can also copy & paste that SQL and try to execute it in the MySQL command tool, and see what happens, whether it gives the result you want, you can profile it or use EXPLAIN, etc.
You're using mysql_real_escape_string() for integers, column names, and SQL keywords (ASC, DESC). That escape function is for escaping only string literals or date literals. It's useless for escaping unquoted integers, column names, SQL keywords, or any other SQL syntax.
For integers, use (int) to typecast inputs to an integer.
For column names or SQL keywords, use a whitelist map -- see example in my presentation http://www.slideshare.net/billkarwin/sql-injection-myths-and-fallacies
You're not testing for error statuses returned by any of your functions. Most functions in ext/mysql return false if some error occurs. You should check for that after every call to a mysql function, and report errors if they occur.
You're selecting a database using a constant name sample instead of a quoted string "sample". This might be intentional on your part, I'm just noting it.
Also, this is not related to your errors, but you should really upgrade to PHP 5. PHP 4 has been end-of-lifed for over two years now.
after looking at the code again and all the suggestions i think i should be using an AND clause and not WHERE. for example the code
$searchSql = ($qtype != '' && $query != '') ? "where ".$qtype." LIKE '%".$query."%' AND new = 1" : '';
this is the WHERE clause? which basically translates to:
$sql = "select *
from act
$searchSql
$sortSql
$limitSql"; <- original code
$sql = "select *
from act
WHERE company LIKE '%demo%' AND new = 1
$sortSql
$limitSql";<-updated code
am i on the right track?