I have php code with two queries. One is in an Oracle database, with the result being about 100 rows of data (within the data there are SKU numbers). The other is in a mysql database with about 30 rows of data (with the data there are also SKU numbers).
I need to compare each SKU in the first query to the second query, line by line. If the SKU in the first query also appears in the second query, then I need it to echo the SKU.
All SKUs in the second query are in the first query, so I would expect the result to echo all 30 SKUs, but it does not. Depending on how I change the syntax, it echos 17 rows, 100 rows, or no rows at all.
It's worth noting that both queries work fine. The Oracle query is insanely long and has a lot of sub-queries in it, so I will not include that full query below. The Oracle query returns the results perfectly in SQL Developer, and the MySQL query returns the results perfectly in HeidiSQL. Both queries have been tested and echoed as tables in other php files to make sure that they were working fine.
Below is what the php file that I am trying to fix looks like so far;
<?php
$conn = oci_connect($user, $pswd, $hst);
$sql = oci_parse($conn,"[Really long Oracle Query]");
while ($row = oci_fetch_assoc($sql))
{
$sku = $row['SKU'];
$con = mysql_connect("[database host]", "[database user]", "[database password]");
mysql_select_db("[database_name]");
$sqls = "SELECT * FROM [table_name] WHERE [this_date_column] BETWEEN
DATE_SUB(NOW(), INTERVAL 14 DAY) AND NOW()";
$result = mysql_query($sqls);
$mailer = NULL;
while($rows = mysql_fetch_assoc($result))
{
$m_sku = $rows['sku'];
if ($m_sku == $sku)
{
$mailer == 'false';
}
}
if ($mailer == 'false')
{
echo $m_sku;
echo "<br>";
}
}
?>
Again; there are only 30 SKUs in the MySQL query, but over 100 SKUs in the Oracle query. All SKUs in the MySQL query are definitely in the Oracle query.
Anyone see what I am doing wrong?
Thanks in advance,
-Anthony
You have basic sintacsis errors:
= is used to assign values
== compares 2 variables (not counsidering there type *)
=== compares 2 variables including there types.
your code should look something like this:
while($rows = mysql_fetch_assoc($result))
{
$m_sku = $rows['sku'];
if ($m_sku == $sku)
{
$mailer = false; // == is for comparison, = is for assign
}
}
if ($mailer === false)
{
echo $m_sku;
echo "<br>";
}
if($member == 'false'){...}
when 'false' is compared with == to a falsefull value (0, null, false, array(), '') .. it will NOT be mach it as it is parsed as a "not empty string" so it is not falsefull .
Here is your code with the MySQL connect moved outside the loop and the == assignment fixed.
<?php
//Connect to databases
$oracle = oci_connect($user, $pswd, $hst);
$mysql = mysql_connect("[database host]", "[database user]", "[database password]");
mysql_select_db("[database_name]");
//Get rows from Oracle
$oracle_result = oci_parse($oracle, "[Really long Oracle Query]");
$oracle_rows = array();
while ($row = oci_fetch_assoc($oracle_result)) $oracle_rows[] = $row;
//Get rows from MySQL
$mysql_sql = "SELECT * FROM [database_name] WHERE this_date_column BETWEEN
DATE_SUB(NOW(), INTERVAL 14 DAY) AND NOW()";
$mysql_result = mysql_query($mysql_sql);
$mysql_rows = array();
while ($row = mysql_fetch_assoc($mysql_result)) $mysql_rows[] = $row;
foreach ($oracle_rows as $oracle_row) {
$oracle_sku = $oracle_row['SKU'];
foreach ($mysql_rows as $mysql_row) {
$mysql_sku = $mysql_row['sku'];
$mailer = null;
if ($mysql_sku == $oracle_sku) {
$mailer = false;
echo $mysql_sku . "<br>";
}
}
}
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'm creating a search box that queries two MySQL tables and lists the results in real time. For now though, I have a working prototype that will query only one table. I've written the following PHP code in conjunction with JQuery and it works wonderfully:
HTML
<input onkeyup="search(this);" type="text">
<ol id="search-results-container"></ol>
Javascript
function search(input) {
var inputQuery = input.value;
/* $() creates a JQuery selector object, so we can use its html() method */
var resultsList = $(document.getElementById("search-results-container"));
//Check if string is empty
if (inputQuery.length > 0) {
$.get("search-query.php", {query: inputQuery}).done(function(data) {
//Show results in HTML document
resultsList.html(data);
});
}
else { //String query is empty
resultList.empty();
}
}
and PHP
<?php
include("config.php"); //database link
if(isset($_REQUEST["query"])) {
$sql = "SELECT * FROM students WHERE lastname LIKE ? LIMIT 5";
/* Creates $stmt and checks if mysqli_prepare is true */
if ($stmt = mysqli_prepare($link, $sql)) {
//Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_query);
//set parameters
$param_query = $_REQUEST["query"] . '%';
//Try and execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
$result = mysqli_stmt_get_result($stmt);
//get number of rows
$count = mysqli_num_rows($result);
if ($count > 0) {
//Fetch result rows as assoc array
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo "<h1>Students:</h1>"; //Header indicates student list
for ($i = 0; $i < $count; $i++) {
$name = $row["lastname"];
echo "<p>$name</p>";
}
}
else { //Count == 0
echo "No matches found.<br>";
}
}
else { //Execution of preped statement failed.
echo "Could not execute MySQL query.<br>";
}
} // end mysqli_prepare
} // end $_RESQUEST isset
?>
The details of the students table are arbitrary, except for the fact that it has a String column that lists the student's last name.
My problem is that there is also a staff table which is effectively the same as students but for a different purpose. I'd like to query the staff table at the same time as students, but have the results separated like so:
<h1>Students:</h1>
<p>Student1</p>
<p>Student2</p>
<h1>Staff</h1>
<p>Staff1</p>
<p>Staff2</p>
The obvious answer would be to add another $sql statement similar to the one on Line 5 and just do both queries serially - effectively doubling the search time - but I'm concerned this will take too long. Is this a false assumption (that there will be a noticeable time difference), or is there actually a way to do both queries alongside each other? Thanks in advance!
If the two tables have identical structures, or if there is a subset of columns which could be made to be the same, then a UNION query might work here:
SELECT *, 0 AS type FROM students WHERE lastname LIKE ?
UNION ALL
SELECT *, 1 FROM staff WHERE lastname LIKE ?
ORDER BY type;
I removed the LIMIT clause because you don't have an ORDER BY clause, which makes using LIMIT fairly meaningless.
Note that I introduced a computed column type which the result set, when ordered by it, would place students before staff. Then, in your PHP code, you would just need a bit of logic to display the header for students and staff:
$count = mysqli_num_rows($result);
$type = -1;
while ($count > 0) {
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$curr_type = $row["type"];
if ($type == -1) {
echo "<h1>Students:</h1>";
$type = 0;
}
else if ($type == 0 && $curr_type == 1) {
echo "<h1>Staff:</h1>";
$type = 1;
}
$name = $row["lastname"];
echo "<p>$name</p>";
--$count;
}
I have two MySQL tables - "mfb_servicelog" and "mfb_agent_status_summary".
I want to select data from "total_ce" column in "mfb_agent_status_summary" where sl_id = $sl_id and then export it as an excel sheet using PHPExcel.
I can get the $sl_id value from mfb_servicelog table where h_id = $value[$i].
And the values of $value is coming from another php file using _POST as an array.
Please point me to the right direection.
Here is my code: (Its returning long list of error)
$value = $_POST['hospitalname'];
$from = $_POST['from'];
$to = $_POST['to'];
if($_POST["Submit"]=="Submit") {
for ($i=0; $i<sizeof($value); $i++) {
$queryslid="SELECT sl_id FROM mfb_servicelog WHERE h_id LIKE ('".$value[$i]."')";
if ($resultslid = (mysql_query($queryslid) or die(mysql_error())) {
while($rowslid = mysql_fetch_row($resultid)) {
$slidset[$i] = $rowslid;
}
$querycasesentered = "SELECT total_ce FROM agent_summary WHERE sl_id LIKE ('".$slidset[$i]."')";
if ($resultcaseentered = (mysql_query($querycasesentered) or die(mysql_error())) {
while($rowce = mysql_fetch_row($resultcasesentered)) {
$casee[$i] = $rowce;
if($i == 0) {
$col = 'H';
}
else {
$col = $k;
}
foreach ($rowce as $cell) {
$obejctPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
}
}
Just a heads up, you are accepting POST data without cleaning it before running your SQL statement, this is very very dangerous and opens your database to injection attacts. But to the problem at hand. Use a join SQL statement something like:
$sql = "SELECT total_ce FROM agent_summary AS agent LEFT JOIN mfb_servicelog AS service ON agent.sl_id = service.sl_id WHERE service.h_id LIKE ('".$value[$i]."')"
You are using mysql_query in a wrong way.
mysql_query has 2 parameters which is the connection and the query
You can look at this definition:
http://www.w3schools.com/php/func_mysqli_query.asp
In short, I suggest that you should use PDO when you are not sure what you are doing with mysql. In order to understand what is PDO, you should read this tutorial http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers carefully which help you to prevent your code from the SQL Injection.
I tried to search for something similar in the web but no results.
What I am trying to do is simply taking the results from the DATABASE and then run some functions for EACH result.
We have two kinds of functions.
The first function is when the row "Type" is = F , the second one when the row "Type" is = T.
The problem that I am having with this code is that it runs the functions ONLY for the first mySQL result.
But I have more results in the same time, and the functions should run for EACH mySQL result and not only for the first one.
I do not know if I need a foreach or whatever. I do not know anything about arrays and php loops.
Thank you.
include_once("../dbconnection.php");
date_default_timezone_set('UTC');
$TimeZone ="UTC";
$todaydate = date('Y-m-d') ."\n";
$time_utc=mktime(date('G'),date('i'),date('s'));
$NowisTime=date('G:i:s',$time_utc);
$MembID =(int)$_COOKIE['Loggedin'];
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$queryMAIN="SELECT * FROM TableTuit WHERE TimeZone ='".$TimeZone."' AND Date ='".$todaydate."' ORDER BY ID ASC";
$result=mysql_query($queryMAIN) or die("Errore select TableT: ".mysql_error());
$tot=mysql_num_rows($result);
while($ris=mysql_fetch_array($result)){
$text=$ris['Tuitting'];
$account=$ris['IDAccount'];
$memberID=$ris['memberID'];
$type=$ris['Type'];
$id=$ris['ID'];
$time=$ris['Time'];
if($time <= $NowisTime){
if($type=="F") //if the row type is = F, then do the things below
{
$queryF ="SELECT * FROM `TableF` WHERE `memberID`='$MembID' AND `ID`='$account'";
$result=mysql_query($queryF) or die("Errore select f: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0) {
$row = mysql_fetch_assoc($result);
DO FUNCTION // Should call the function that requires the above selected values from $queryF. Should Run this function for every mysql result given by $queryMAIN where row "type" is = F
}
}
}
if($type=="T") //if the row type is = T, then do the things below
{
$queryT = $queryF ="SELECT * FROM `TableT` WHERE `memberID`='$MembID' AND `ID`='$account'";
$result=mysql_query($queryT) or die("Errore select $queryT: ".mysql_error());
$count = mysql_num_rows($result);
if ($count == 0)
$Isvalid = false;
else
{
$Isvalid = true;
$row = mysql_fetch_assoc($result);
}
if($Isvalid){
DO THIS FUNCTION // Should call the function that requires the above selected values from $queryT. Should Run this function for every mysql result given by $queryMAIN where row "type" is = T
}
}
}
}//END OF MYSQL WHILE OF $queryMAIN
You are using $result for the outer Query ($result=mysql_query($queryMAIN); and the Query inside the while loop $result=mysql_query($queryF); - I believe you do not want to mix these?
Right now you process the first row from TableTuit, then overwrite the $result with a row from TableF or TableT. In the next loop, the following columns will not be found in the array (unless they are also in these two tables, of course):
$text=$ris['Tuitting'];
$account=$ris['IDAccount'];
$memberID=$ris['memberID'];
$type=$ris['Type'];
$id=$ris['ID'];
$time=$ris['Time'];
You are loading the results into an array, try using this in your while loop instead:
while($ris=mysql_fetch_assoc($result)){
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?