I have a query that returns all the data while running at MSSQL, but when I try to get the result with php code it returns null
SELECT:
$query = "SELECT DISTINCT (E080SER.desser) as desser,
E080SER.CODFAM codfam, e085cli.apecli apecli,
E085CLI.CODCLI codcli, E085CLI.NOMCLI nomeCli
FROM
E160CTR,
E160CVS, e080ser,
E085CLI,
E070EMP,
E070FIL
WHERE
e070emp.nomemp like '%Gestão tech%' and
e080ser.codser = e160cvs.codser and
e080ser.codser like ('%manw%') and (E160CTR.CODEMP = 1) and
((E160CTR.CODEMP = E070FIL.CODEMP) AND (E160CTR.CODFIL =
E070FIL.CODFIL) AND
(E160CTR.CODCLI = E085CLI.CODCLI) AND (E160CVS.CODEMP =
E160CTR.CODEMP) AND
(E160CVS.CODFIL = E160CTR.CODFIL) AND (E160CVS.NUMCTR =
E160CTR.NUMCTR)) AND
(E160CTR.SITCTR = 'A') and e080ser.sitser = 'a' and
E080SER.CODEMP IN (1, 9)
order by e080ser.desser";
PHP CODE:
$sql = sqlsrv_query($conn, $query);
while($item = sqlsrv_fetch_array($sql)){
var_dump($item);
}
Sometimes it's necessary to fetch all result sets with sqlsrv_next_result() to get your data. You may try with this:
<?php
...
$sql = sqlsrv_query($conn, $query);
do {
while($item = sqlsrv_fetch_array($sql)){
var_dump($item);
}
} while (sqlsrv_next_result($sql));
...
?>
There is an extra semicolon after the while loop, i.e. the body of the loop is empty. Then the result you try to read is after the last row, that's why you don't get what you expected.
I've found the problem
The problem was the encoding, I put the $query inside of utf8_encode(), and now it is returning the results.
Thank you all for your time.
Related
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!
I run the query directly through PHP MyAdmin and it returns 1 result. Am I missing something? Well clearly I must be and I can't wrap my head round it!?!
I think I'm just tired or something!
Any help would be much appreciated:-
$query_road_tax = mysqli_query($conn011, "SELECT * FROM road_tax_pricing WHERE (tax_from_co2 <='$vehicle_co2' AND tax_upto_co2 >='$vehicle_co2'");
$row_road_tax = mysqli_fetch_assoc($query_road_tax);
$Six_Month=$row_road_tax['tax_6month'];
$Twelve_Month=$row_road_tax['tax_12month'];
Closing ) and " issue it would be
$query_road_tax = mysqli_query($conn011, "SELECT * FROM
road_tax_pricing WHERE (tax_from_co2 <='$vehicle_co2' AND tax_upto_co2 >='$vehicle_co2')");
Try that - you might have to print the results in loop.
$query = "SELECT * FROM road_tax_pricing WHERE (tax_from_co2 <='$vehicle_co2' AND tax_upto_co2 >='$vehicle_co2')";
if($query_road_tax = mysqli_query($conn011, $query)) {
while ($row = mysqli_fetch_assoc($query_road_tax)) {
/* print_r($row); */
printf($row["tax_6month"]);
printf($row["tax_12month"]);
}
}
I have a PHP code which has the following output:
[{"stockdata":29655.88482666}]
And I need to change the code on my php to get the result in this format:
[{"data": [29655.88482666]}]
This is the code of my php:
<?php
function getArraySQL(){
$startd = "29964";
$endd = "29968";
$dsn = "prueba";
$connect = odbc_connect( $dsn, '', '' );
$query = "
Select SUM(TON_DESCARGADO) as stockdata
from
(Select unit,[load],enum_LOAD.[name],SUM(dumptons) as TON_DESCARGADO
from hist_dumps inner join hist_loclist on hist_dumps.shiftindex = hist_loclist.shiftindex
and hist_dumps.loc = hist_loclist.locid
inner join enum_LOAD on hist_dumps.[load] = enum_LOAD.[num]
where hist_dumps.shiftindex between '$startd' and '$endd'
GROUP BY loc,UNIT,unit#,[load],enum_LOAD.[name])TEMP1
where unit = 'Stockpile'
GROUP BY unit
order BY UNIT";
if(!$rs = odbc_exec($connect, $query)) die();
$rawdata = array();
$i=0;
while($row = odbc_fetch_array($rs))
{
$rawdata[$i] = $row;
$i++;
}
odbc_close( $connect );
return $rawdata;
};
$stockdata = getArraySQL();
echo json_encode(($stockdata), JSON_NUMERIC_CHECK);
What need to be changed to get the correct format? Should I do something to improve the code of my php?
How should I write it if I connect php to SQL server via PDO and get the same result? (just an optional doubt)
I don't find custom output in json_encode, so if you want to customize the output of array , you would need to prepare it.
I assumed the data exists at zero index (0).
So, I use $stockdata[0]
for JSON_NUMERIC_CHECK replace, used (float)
here is the preparation of output to send exactly you want.
$stockdata = getArraySQL();
$Numeric_data = (float) $stockdata[0];
$data = '[{"data": ['.$Numeric_data.']}]';
echo $data;
Demo
I have a MySQL table that looks like this:
index | tag | posts
-------------------------
1 | cats | 9,10
2 | a cat | 9,10
3 | kitty | 9,10
4 | meow | 9,10
I am trying to just return the row that matches a search query.
I passed the search parameter using a simple ?search=cats.
This is the PHP that I'm using:
$search = $_GET['search'];
$query = mysql_query("SELECT * FROM tags WHERE tag = '$search'");
echo(mysql_num_rows($query));
$result = mysql_fetch_array($query);
$print = $result['posts'];
echo($print);
However the mysql_num_rows($query) prints 0 and the $print returns NULL. I can check it with ($print == ""), it evaluates to TRUE and mysql_num_rows($query) returns 4.
I tried setting the search query to something that wasn't in the table and it retuned FALSE as expected. I also tried removing the WHERE tag = '$search' and it returns the table like it should.
Is there something I'm overlooking?
Edit
Took everyone's advice and the code I'm using now is:
$search = mysql_real_escape_string($_GET['search']);
var_dump($search); //prints string(4) "cats" just like it should
$queryText = "SELECT * FROM tags WHERE tag = '%".$search."%'";
echo($queryText); //SELECT * FROM tags WHERE tag = '%cats%'
$query = mysql_query($queryText) or die(mysql_error()); //no error
$rows = mysql_num_rows($query); //this returns 0 and I know it should match 1 row
echo('rows: '.$rows);
$result = mysql_fetch_array($query);
$print = $result['posts'];
echo($print); //empty
Still have the same problem. The mysql_query is retuning NULL instead of the row or FALSE if it doesn't match.
(in the future I will use the mysqli API, but I would like to finnish this project in mysql. thanks for your suggestions and advice)
Try this code now.
Remeber when you want to debug something in PHP the faster way is var_dump not echo. Also you should avoid mysql_api because they are deprecated, use PDO instead PDO on PHP.net
var_dump($_GET); // Just for debuggin if as something
$search = $_GET['search'];
$query = mysql_query("SELECT * FROM tags WHERE tag = '".mysql_real_escape_string($search)."'");
// echo(mysql_num_rows($query));
$result = mysql_fetch_array($query);
var_dump($result);
//$print = $result['posts'];
//echo($print);
Ok so after referring to the above edit you made, here is the solution
Use "LIKE" instead of "=" when using wildcard "%"
So your query now should be
$queryText = "SELECT * FROM tags WHERE tag LIKE '%" . $search . "%'";
[I created the exact same db on my local system and ran the same code you gave, After making the above changes, It runs as expected]
$search = $_GET['search'];
echo $select_query="SELECT * FROM tags WHERE tag = '".mysql_real_escape_string($search)."'";
$query = mysql_query($select_query);
echo(mysql_num_rows($query));
while($result = mysql_fetch_array($query))
{
print_r($result);
}
Note:
$search = $_GET['search'];
$query = mysql_query("SELECT * FROM tags WHERE tag = '$search'");
That is very dangerouse: It allow sql incersion code to your database. You must always escape all what you get from the client.
$search = mysql_real_escape_string($_GET['search']); //It require open database connection.
Note2:
mysql_query is obsolete, use mysqli instead ;-)
Answer:
If you have not answer, you probable has an error in an other part.
Try
//1) Look if your search has a correct value
var_dump($search);
//2) Replace the query with (just for debugging):
$query = mysql_query("SELECT * FROM tags WHERE tag = 'cats';");
You may also use "tag like '%cats%'" if you want a more flexible search.
If you remove the WHERE tage = '$search', it cannot return the table like it should because your mysql_fetch_array is not in a while loop... but that aside...
// make sure before you execute the code to check that $_GET['search'] is not empty
// start with escaping the search-value (for mysql-injection)
$search = msyql_real_escape_string($_GET['search']);
// changed the query so it searches for tags containing the search value.
// if you would have records with tags "blue cat" and "red cat" it shows them both
// when searching for "cat"
$query = mysql_query("SELECT * FROM tags WHERE tag LIKE '%".$search."%'");
// put the number of rows in a var
$num = mysql_num_rows($query);
// check this var if it's not 0
if ($num != '0'){
while ($row = mysql_fetch_array($query){
echo $row['posts'];
// etc...
}
} else {
// 0 rows found
echo "nothing found";
}
I'm trying to write a script that gets data from a sql server based on the id of the entry in my data base. when I try to access the page using the link with the id of the entry it returns as if it does not recognize the id. Below is the php code :
<?php
require('includes/config.inc.php');
require_once(MYSQL);
$aid = FALSE;
if (isset($_GET['aid']) && filter_var($_GET['aid'], FILTER_VALIDATE_INT, array('min_range' => 1)) ) {
$aid = $_GET['aid'];
$q = "SELECT aircraft_id, aircraft_name AS name, aircraft_type AS type, tail_number AS tn FROM aircraft USING(aircraft_id) WHERE aircraft_id = $aid";
$r = mysqli_query($dbc, $q);
if (!(mysqli_num_rows($r) > 0)) {
$aid = FALSE;
}
}// end isset tid
if ($aid) {
while ($acdata = mysqli_fetch_array($r, MYSQLI_ASSOC)){
echo'<h2>'. $acdata['tail_number'] .'</h2>';
}
} else {
echo '<p>This pages was accessed in error.</p>';
}
?>
Any hints?
Try to var_dump($q); before $r = mysqli_query($dbc, $q); to inspect your query and then just execute it through phphmyadmin or in MySQL server terminal directly and see what does it return.
Update:
Use var_dump($q);die(); to stop script from executing after dumping.
You are using a field alias in your query, so you must use that in your echo to:
echo'<h2>'. $acdata['tn'] .'</h2>';
Get rid of the USING(aircraft_id), it causes an error and your query doesn't execute.
"SELECT aircraft_id, aircraft_name AS name, aircraft_type AS type, tail_number AS tn FROM aircraft WHERE aircraft_id = $aid"
I guess it's a leftover from a previous version of the query? Using (id) is a shortcut for
FROM
foo
INNER JOIN bar ON foo.id = bar.id
It can be used when the tables to be joined are joined on columns which have the same name. Just shorter to write.
Since you are not joining you have to remove it.