I'm writing some html+php code but this part seems to be causing error. Do you see something wrong?
$sql = "SELECT p.seccio_id, count(*), sum(r.preu)
FROM report r, persona p
WHERE r.usuari_upc = p.persona_id
and r.any = " . $_POST["any"] . "
and r.mes = " . $_POST["mes"] . "
and p.any_id = '"
if ($_POST["mes"] < 9) echo ($_POST["any"] - 1) . "-" . $_POST["any"] . "'";
else echo $_POST["any"] "-" . ($_POST["any"] + 1) . "'";
"GROUP BY p.seccio_id
ORDER BY p.seccio_id";
You have to split it up:
$sql = "SELECT p.seccio_id, count(*), sum(r.preu) FROM report r, persona p WHERE .usuari_upc = p.persona_id and r.any = " . $_POST["any"] . " and r.mes = " . _POST["mes"] . " and p.any_id = '";
if ($_POST["mes"] < 9)
$sql .= ($_POST["any"] - 1) . "-" . $_POST["any"] . "'";
else
$sql .= $_POST["any"] "-" . ($_POST["any"] + 1) . "'";
$sql .= " GROUP BY p.seccio_id ORDER BY p.seccio_id";
P.S. Your sql is vulenarable to SQL injection.
Related
I'm having this error when click on a tag on product page on my Opencart 2.3.0.2 store
PHP Fatal error: Uncaught exception 'Exception' with message 'Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'OR man.name LIKE '%%' pd.tag LIKE '%conjunto%' AND pd.tag LIKE '%infantil%' AND ' at line 1<br />Error No: 1064<br />SELECT p.product_id, (SELECT AVG(rating) AS total FROM oc_review r1 WHERE r1.product_id = p.product_id AND r1.status = '1' GROUP BY r1.product_id) AS rating, (SELECT price FROM oc_product_discount pd2 WHERE pd2.product_id = p.product_id AND pd2.customer_group_id = '1' AND pd2.quantity = '1' AND ((pd2.date_start = '0000-00-00' OR pd2.date_start < NOW()) AND (pd2.date_end = '0000-00-00' OR pd2.date_end > NOW())) ORDER BY pd2.priority ASC, pd2.price ASC LIMIT 1) AS discount, (SELECT price FROM oc_product_special ps WHERE ps.product_id = p.product_id AND ps.customer_group_id = '1' AND ((ps.date_start = '0000-00-00' OR ps.date_start < NOW()) AND (ps.date_end = '0000-00-00' OR ps.date_end > NOW())) ORDER BY ps.priori in C:\inetpub\wwwroot\cabanins\system\library\db\mysqli.php on line 40
I dont know what the reason for this error is because my localhost version is working normally.
Your issue is right here:
man.name LIKE '%%' pd.tag
You need to include a AND tag like so
man.name LIKE '%%' AND pd.tag
Although there's no reason to have
man.name LIKE '%%'
as %% will match EVERYTHING.
So you could just make it:
OR pd.tag LIKE '%conjunto%'
Thanks for helping me. I dont understand why the code is wrong only on online version and works fine on localhost. Im using the same code. Thats the code
if (!empty($data['filter_category_id'])) {
if (!empty($data['filter_sub_category'])) {
$sql .= " FROM " . DB_PREFIX . "category_path cp LEFT JOIN " . DB_PREFIX . "product_to_category p2c ON (cp.category_id = p2c.category_id)";
} else {
$sql .= " FROM " . DB_PREFIX . "product_to_category p2c";
}
if (!empty($data['filter_filter'])) {
$sql .= " LEFT JOIN " . DB_PREFIX . "product_filter pf ON (p2c.product_id = pf.product_id) LEFT JOIN ".$from." p ON (pf.product_id = p.product_id)";
} else {
$sql .= " LEFT JOIN ".$from." p ON (p2c.product_id = p.product_id)";
}
} else {
$sql .= " FROM ".$from." p";
}
$sql .= " LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) WHERE pd.language_id = '" . (int) $this->config->get('config_language_id') . "' AND p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int) $this->config->get('config_store_id') . "'";
if (!empty($data['filter_category_id'])) {
if (!empty($data['filter_sub_category'])) {
$sql .= " AND cp.path_id = '" . (int) $data['filter_category_id'] . "'";
} else {
$sql .= " AND p2c.category_id = '" . (int) $data['filter_category_id'] . "'";
}
if (!empty($data['filter_filter'])) {
$implode = array();
$filters = explode(',', $data['filter_filter']);
foreach ($filters as $filter_id) {
$implode[] = (int) $filter_id;
}
$sql .= " AND pf.filter_id IN (" . implode(',', $implode) . ")";
}
}
if (!empty($data['filter_name']) || !empty($data['filter_tag'])) {
$sql .= " AND (";
if (!empty($data['filter_name'])) {
$implode = array();
$words = explode(' ', trim(preg_replace('/\s+/', ' ', $data['filter_name'])));
foreach ($words as $word) {
$implode[] = "pd.name LIKE '%" . $this->db->escape($word) . "%'";
}
if ($implode) {
$sql .= " " . implode(" AND ", $implode) . "";
}
if (!empty($data['filter_description'])) {
$sql .= " OR pd.description LIKE '%" . $this->db->escape($data['filter_name']) . "%'";
}
}
if (!empty($data['filter_name']) && !empty($data['filter_tag'])) {
$sql .= " OR ";
}
if (!empty($data['filter_tag'])) {
$implode = array();
$words = explode(' ', trim(preg_replace('/\s+/', ' ', $data['filter_tag'])));
foreach ($words as $word) {
$implode[] = "pd.tag LIKE '%" . $this->db->escape($word) . "%'";
}
if ($implode) {
$sql .= " " . implode(" AND ", $implode) . "";
}
}
if (!empty($data['filter_name'])) {
if($multiplicar_produtos) {
$sql .= " OR LCASE(p.model) LIKE '%" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "%'";
} else {
$sql .= " OR LCASE(p.model) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'";
}
$sql .= " OR LCASE(p.sku) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'";
$sql .= " OR LCASE(p.upc) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'";
$sql .= " OR LCASE(p.ean) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'";
$sql .= " OR LCASE(p.jan) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'";
$sql .= " OR LCASE(p.isbn) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'";
$sql .= " OR LCASE(p.mpn) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'";
}
$sql .= ")";
}
What am I missing?
I have a drop down with values. I think everything is working fine, except when I post the results to another table I can't seem to get the gameID from the first table to post, it just goes through as blank. Am I missing an association with the team and the gameID?
Query to get data for drop down:
$sql = "select s.*, (DATE_ADD(NOW(), INTERVAL " . SERVER_TIMEZONE_OFFSET . " HOUR) > gameTimeEastern or DATE_ADD(NOW(), INTERVAL " . SERVER_TIMEZONE_OFFSET . " HOUR) > '" . $cutoffDateTime . "') as expired ";
$sql .= "from " . DB_PREFIX . "schedule s ";
$sql .= "inner join " . DB_PREFIX . "teams ht on s.homeID = ht.teamID ";
$sql .= "inner join " . DB_PREFIX . "teams vt on s.visitorID = vt.teamID ";
$sql .= "where s.weekNum = " . $week . " ";
$sql .= "order by s.gameTimeEastern, s.gameID";
//echo $sql;
$query = $mysqli->query($sql) or die($mysqli->error);
if ($query->num_rows > 0) {
$i = 0;
while ($row = $query->fetch_assoc()) {
$sGameID = (int)$row['gameID'];
$homeTeam = new team($row['homeID']);
$visitorTeam = new team($row['visitorID']);
$surv_pick_options_h[$i]=$row['homeID'];
$surv_pick_options_v[$i]=$row['visitorID'];
if ($row['expired']){
$surv_pick_expired_h[$i]=$row['homeID'];
$surv_pick_expired_v[$i]=$row['visitorID'];
}
$surv_gameID[$i] = (int)$row['gameID'];
$i++;
$rowclass = (($i % 2 == 0) ? ' class="altrow"' : '');
}
};
Drop down select option:
$sWeek = (int)getCurrentWeek()+1;
if ($week < $sWeek){
$survpicks_to_disable = array_slice($survpicks,0,$week-1);
$disabled = array_merge($survpicks_to_disable,$surv_pick_expired_h,$surv_pick_expired_v);
echo '<select name="survpick" id="survpick">
<option default>Select</option>';
foreach($surv_pick_options_h as $home){
echo '<option value="'.$home.'"'.(in_array($home,$disabled)?' style="background-color:pink" disabled':'').($home == $currentID?' selected':'').'>'.$home.'</option>';
}
foreach($surv_pick_options_v as $visitor){
echo '<option value="'.$visitor.'"'.(in_array($visitor,$disabled)?' style="background-color:pink" disabled':'').($visitor == $currentID?' selected':'').'>'.$visitor.'</option>';
}
}
echo '</select>';
}
And finally update a table with results:
$sql = "insert into " . DB_PREFIX . "picksurvivor (weekNum, userID, user, gameID, picksurv, showPicks) values (" . $_POST['week'] . ", " . $user->userID . ",'" . $user->userName . "', '" . $surv_gameID . "', '" . $_POST['survpick'] . "', ". (int)$_POST['showPicks'] . ");";
$mysqli->query($sql) or die('Error deleting survivor pick: ' . $mysqli->error);
I found a different approach, doing an update after the insert to basically brute force the gameID in there.
I have made a database connection in php and FETCH parts like story and id.
the URL forms ok without '&' but fails when '&' is added in the URL.
Here is my php code with '&id=' added in the URL
$fullurl = /cms/page.php . '?chapter=' . $row['story'] . '&id=' . $row['id'];
Can someone put me right about the correct syntax...
The error is pretty obvious
$fullurl = /cms/page.php . '?chapter=' . $row['story'] . '&id=' . $row['id'];
should be changed so that all text is within the citation marks..
$fullurl = '/cms/page.php?chapter=' . $row['story'] . '&id=' . $row['id'];
Otherwise you will end up in an error.
Also please, consider using error_reporting(E_ALL); when debugging.
The part: /cms/page.php is not a string.... and thus is wrong. You could just change it to something like this:
<?php
// NOTICE THAT THE PART "/cms/page.php" IS NOW EMBEDDED IN QUOTES (STRING)
$fullurl = "/cms/page.php" . '?chapter=' . $row['story'] . '&id=' . $row['id'];
// OR EVEN COMPACT IT LIKES SO:
$fullurl = "/cms/page.php?chapter=" . $row['story'] . '&id=' . $row['id'];
poiz
it still didnt work but i found i dont need to fetch from NEWS_ARTICLES. In fact my variables are already fetched as you see below...
Here is my actual code.
$sql = "SELECT old,title,story,shortstory,author,origauthor,ip,timestamp,allowcomments,short,approved,viewcount,rating,archive date,neverarchive,archived,id,
" . NEWS_USERS . ".user AS authorname,
" . NEWS_USERS . ".avatar AS authoravatar,
commentcount AS comments
FROM " . NEWS_ARTICLES . " INNER JOIN " . NEWS_USERS . " ON " . NEWS_ARTICLES . ".author = " . NEWS_USERS . ".uid WHERE id IN (";
if($nocats == "1"){
$sql .= "SELECT id AS storyid FROM " . NEWS_ARTICLES . " WHERE id NOT IN (SELECT storyid FROM " . NEWS_GROUPCATS . " WHERE type = 'news') UNION ";
}
$sql .= "SELECT storyid FROM " . NEWS_GROUPCATS . " WHERE type = 'news' AND catid IN (SELECT catid FROM " . NEWS_GROUPCATS . " WHERE type = 'rss' AND storyid = ?) ) AND archived = '0' ORDER BY timestamp DESC LIMIT 0, $rssamount";
$newsstories = DataAccess::fetch($sql, $feedid);
foreach($newsstories AS $row){
if(FRIENDLY){
$fullurl = $newslocation . $prefix . $row['id'] . "-0-" . makefriendly($row[title]);
}else{
$fullurl = $newslocation . '?epic-code=' . $row['shortstory'] . '&id=' . $row['id'];
}
'&id' gives...
error on line 12 at column 85: EntityRef: expecting ';'
'id' gives...
[a link] http://www.example.com//stock-charts/share-charts.php?epic-code=ALTPid=3360
the & is missing ....
How do i bind values to a variable which is partially processed with diffrent statements and then concatenated using php .= method
Please note that I am not using array to bind parameters.
below is piece of code
$wher = '';
now I have added few varibles to $wher like
if (!empty($_SESSION['advs']['title']))
{
$wher .= '(';
if (isset($_SESSION['advs']['desc']))
{
$wher .= "(au.description like '%" . $system->cleanvars($_SESSION['advs']['title']) . "%') OR ";
}
$wher .= "(au.title like '%" . $system->cleanvars($_SESSION['advs']['title']) . "%' OR au.id = " . intval($_SESSION['advs']['title']) . ")) AND ";
}
more addition to $wher
if (isset($_SESSION['advs']['buyitnow']))
{
$wher .= "(au.buy_now > 0 AND (au.bn_only = 'y' OR au.bn_only = 'n' && (au.num_bids = 0 OR (au.reserve_price > 0 AND au.current_bid < au.reserve_price)))) AND ";
}
if (isset($_SESSION['advs']['buyitnowonly']))
{
$wher .= "(au.bn_only = 'y') AND ";
}
if (!empty($_SESSION['advs']['zipcode']))
{
$userjoin = "LEFT JOIN " . $DBPrefix . "users u ON (u.id = au.user)";
$wher .= "(u.zip LIKE '%" . $system->cleanvars($_SESSION['advs']['zipcode']) . "%') AND ";
}
now I am using $wher in database query like
// get total number of records
$query = "SELECT count(*) AS total FROM " . $DBPrefix . "auctions au
" . $userjoin . "
WHERE au.suspended = 0
AND ".$wher . $ora . "
au.starts <= " . $NOW . "
ORDER BY " . $by;
$wher is being used in SQL select query.
How do I put placeholders to $wher and bind the values??
my problem is something like PHP PDO binding variables to a string while concatenating it
But slight different way
We have a script that generate invoice once a month (cron). But we would like to add feature, that we would be able to select date range "from - to" and then generate invoice only for the date selected.
I guess making input fields with calendar pop-up isn't hard, but filtering with PHP is a bit bigger challenge, so if anyone want to take a look at my code and give me some tips, I would be grateful.
function genInvoice($clientID, $orderID=0, $paid=false)
{
if($orderID == 0)
$sql = "select tblorders.* from tblorders,tblusers where invoiceid=0 and tblorders.userid=tblusers.id " .
"and status='closed' and tblusers.clientid=" . $clientID;
else
$sql = "select tblorders.* from tblorders,tblusers where invoiceid=0 and tblorders.userid=tblusers.id " .
"and tblusers.clientid=" . $clientID . " and tblorders.id=" . $orderID;
$res = full_query($sql) or die(mysql_error());
// If no closed orders uninvoiced, just return
if(!mysql_num_rows($res))
return 0;
$amount = 0;
$orders = array();
while($row = mysql_fetch_array($res, MYSQL_ASSOC))
{
// print_r($row);
// print "<br><hr>";
$amount += $row['amount'];
$orders[] = $row['id'];
}
$date = date("Y-m-d");
$status = $paid ?'Paid' : 'Unpaid';
$sql = "insert into tblinvoices (clientid, date, duedate, subtotal, total, status) values (" . $clientID . ",'" . $date .
"','" . $date . "'," . $amount . "," . $amount . ",'" . $status . "')";
$res = full_query($sql) or die(mysql_error());
$invoiceid = mysql_insert_id();
$sql = "update tblorders set invoiceid=" . $invoiceid . " where id in (" . implode(",", $orders) . ")";
$res = full_query($sql) or die(mysql_error());
$sql = "select tblorders.id as ReportID, FirstName, LastName, SearchName, CountyID, StateID, bl_orderitems.userid, bl_orderitems.amount, " .
"bl_orderitems.notes from tblorders, bl_orderitems left join bl_search on bl_search.id=packageid where tblorders.id in (" .
implode(",", $orders) . ") and bl_orderitems.orderid=tblorders.id order by tblorders.id,bl_orderitems.id";
$res = full_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($res, MYSQL_ASSOC))
{
if($row['CountyID'] != 0)
$locale = getCounty($row['CountyID']);
else if($row['StateID'] != 0)
$locale = getState($row['StateID']);
if($row['SearchName'] != "")
$description = mysql_real_escape_string($row['FirstName'] . " " . $row['LastName'] . " " .
$row['SearchName'] . " " . $locale . " (Order #" . $row['ReportID'] . ")");
else
$description = "Search Package: " . mysql_real_escape_string($row['notes'] . " (Order #" . $row['ReportID'] . ")");
$sql = "insert into tblinvoiceitems (invoiceid, userid, type, description, amount, duedate) values " .
"(" . $invoiceid . "," . $row['userid'] . ",'search','" . $description . "','" .
$row['amount'] . "','" . $date . "')";
// print $sql . "<br>";
full_query($sql) or die(mysql_error());
}
sendmessage ('Invoice Created', $invoiceid);
return $invoiceid;
}
not going to look through all that code, but filtering results by a date range is easy.
SELECT id FROM some_table WHERE some_date_field BETWEEN $first_date AND $second_date