SQL Query invalid/not displaying results - php

I am working on a property management software projects and I have been stuck at this point for a while now and I'm getting no where.
I can have one section working then another breaks so I'm chasing my tail here.
I'm trying to accomplish a form to search a database for specific entries such as bedrooms/baths, maxrent/minrent, and sorting functions included in the form.
SQL,
$beds = $_POST['beds'];
$baths = $_POST['baths'];
$minrent = $_POST['minrent'];
$maxrent = $_POST['maxrent'];
$result = mysqli_query($con,"SELECT * FROM units WHERE bed LIKE '%$beds%' OR bath LIKE '%$baths%' AND rent>='$minrent' AND rent<='$maxrent'");
while($row = mysqli_fetch_array($result)){}
Any help to the correct formatting of the sql would be fantastic. Thanks
EDIT: This is just a local project, not trying to make it web-safe.
Also, the columns I am using are rent, bed, bath with ~150 records.
EDIT: Solved, changed the column type from TEXT to INT.

You can try this, Added ( for OR )
"SELECT * FROM units WHERE (bed LIKE '%$beds%' OR bath LIKE '%$baths%')
AND (rent between '$minrent' AND '$maxrent' )"

Related

Correct syntax for SQL Submittion

I'm working with Prestashop and I've got a module that generates shipping labels for my orders. When a label is made it generates a tracking code that can be used on the carriers website. The problem though is that our shippers have to copy and paste this code into prestashop for customers to receive a tracking email. It's my goal to automate this process to minimize human error within our system.
I've found the table and column within prestashop's database that houses the tracking code (ps_order_carrier, tracking_number) and I have confirmed that changing this value in the database effects the order in the way I have intended. Within the prestashop module there is a section of code that submits the tracking number and various order information like the order id which I will likely need to it's own table so I'm assuming I can just duplicate this portion of code and modify it to meet my needs. The following is the code within the module:
$sql = 'INSERT INTO '._DB_PREFIX_.$this->name.'_labels
(
id_order,
id_shipment,
postage_label_ref_id,
postage_label_object,
postage_label_updated_at,
postage_label_label_url,
tracking_code,
selected_rate_ref_id,
selected_rate_object,
selected_rate_updated_at,
selected_rate_service,
selected_rate_carrier,
selected_rate_shipment_ref_id,
tracker_ref_id,
tracker_object
)
VALUES
(
"'.(int)$data['id_order'].'",
"'.pSQL($data['id_shipment']).'",
"'.pSQL($data['postage_label']['ref_id']).'",
"'.pSQL($data['postage_label']['object']).'",
"'.pSQL($data['postage_label']['updated_at']).'",
"'.pSQL($data['postage_label']['label_url']).'",
"'.pSQL($data['tracking_code']).'",
"'.pSQL($data['selected_rate']['ref_id']).'",
"'.pSQL($data['selected_rate']['object']).'",
"'.pSQL($data['selected_rate']['updated_at']).'",
"'.pSQL($data['selected_rate']['service']).'",
"'.pSQL($data['selected_rate']['carrier']).'",
"'.pSQL($data['selected_rate']['shipment_ref_id']).'",
"'.pSQL($data['tracker']['ref_id']).'",
"'.pSQL($data['tracker']['object']).'"
)';
Db::getInstance()->Execute($sql);
I made a copy of this directly underneath and amended it to meet my needs but it doesn't seem to do what I want it to. I have a feeling I'm messing up the syntax. I've tried a few different variations of it so it's a bit chaotic but here is what I have as of writing this:
$sql2 = 'INSERT INTO `ps_order_carrier` WHERE `id_order` = '.(int)$data['id_order'].'
(
tracking_number
)
VALUES
(
"'.pSQL($data['tracking_code']).'"
)';
Db::getInstance()->Execute($sql2);
Any help would be greatly appreciated as this would save us so much time.
Thanks!
You're trying to update a row using an "INSERT" query.
$sql2 = 'UPDATE `ps_order_carrier` SET tracking_number = "'.pSQL($data['tracking_code']).'" WHERE `id_order` = '.(int)$data['id_order'].'
Db::getInstance()->Execute($sql2);
But the best way would be to first load the orderCarrier Object and change its tracking value without doing a direct query to DB.
$order = new Order($data['id_order']);
$orderCarrier = new OrderCarrier($order->getIdOrderCarrier());
$orderCarrier->tracking_number = $data['tracking_code'];
$orderCarrier->save();
To avoid all kind of mistakes in MySQL query syntax Prestashop have some classes and functions you can use:
Db::getInstance()->insert($this->name.'_labels',
array(
'id_order' => (int)$data['id_order'],
'id_shipment' => pSQL($data['id_shipment']),
/*and so on*/
)
);
Remember to cast all ID values to int and use pSQL in all string values.
There is an update function if you need it too.
Good luck.
there is no where clause in the insert statement.
specify all the values - and you get a new record.
$sql2 = 'INSERT INTO ps_order_carrier
(
tracking_number
, id_order
)
VALUES
(
"'.pSQL($data['tracking_code']).'"
, "'.(int)$data['id_order'].'"
)';
not tested - you may still need to fiddle with the quotes...

Random jump within while() loop in PHP for MySQL query

I am doing an example project for University and got a problem that I can't solve.
In general, the project is to create an automated pizza order system in PHP and MySQL on Apache. The system works through the following steps:
- Customer places order -> Baker receives order, proceeds -> Driver receives order at certain state, proceeds
- Customer can view order at all time through session
Now I hung up at the last step: The driver can see a page that has a table with the information that the baker worked with and passed on (all changes are on database side). The driver can only see a whole package (whenever all pizzas are marked as a certain status, also saved in DB).
For this, I have the following SQL statement
SELECT PizzaID, BestellungID, Adresse, PizzaName, Preis, Status FROM angebot, bestelltepizza, bestellung where bestellung.bestellungid = bestelltepizza.fbestellungid and angebot.PizzaName = bestelltepizza.fPizzaName and (select min(status) from bestelltepizza where bestellung.bestellungid = fbestellungid) >2 ORDER BY Status, BestellungID
Now, when I use var_dump() to get the mysqli_num_rows() output, I get no errors and the following output int 26. Compared to the database rows, it's the correct number. I fetch the sql:
while($row = mysqli_fetch_array($this->result)) {
var_dump(mysqli_num_rows($this->result));
var_dump($row);
...
}
Within the while() loop contains another query
$this->query = "SELECT fPizzaName FROM bestelltepizza WHERE fBestellungID = '$BestellID'";
var_dump($this->query);
$tmpResult = $this->_database->query($this->query);
$count = mysqli_num_rows($tmpResult);
Now here is the problem, the while() loop leaves out a random $BestellID which can contain x rows of data. But when I count the output of var_dump() everything is correct. However, var_dump($this->query); is not showing the query statement for the specific jump, too.
Any ideas what this could be? Full link to pastebin below.
To not extend this question to the fullest, I uploaded the whole code to pastebin here: http://pastebin.com/u888CPLw
Offtopic: Appreciate any help, thanks. If I failed clearing out my exact problem or if any questions pop up to my question, please comment and I will clarify. Thanks.
while($row = mysqli_fetch_array($this->result)) {
$count = mysqli_num_rows($tmpResult);
for($i = 0; $i < $count; $i++) {
$tmpVar = mysqli_fetch_array($this->result);
Ive snipped the code to show the problem
$count is based on $tmpResult you are then doing a fetch array on $this->result you should be doing it on $tmpResult
As Marc B says, Its a simple query to either inner join / left join on to the query. It would be better to use the join.

Names for PHP query results and PHP loops.

This might be a simple question, but I can't find a definitive answer I can understand. I use PHP loops alot, I'm fairly new to PHP so they are usually simple like so:
<?php
$result = mssql_query("SELECT Price FROM Window_Extras WHERE ExtraID = '4' ");
while ($row = mssql_fetch_array($result)) {
?>
<a title="<?php echo $row['Colour']; ?>"></a>
<?php }?>
Is a really simple example, that doesn't make much sense, but I hope it shows how I use them. The question I wanted to ask was if $row and $result have to be named that for it to work, could they for example be named $priceresult and $pricerow?
This is because sometimes I would like to use multiple queries for a single loop, for example:
<?php
$result = mssql_query("SELECT Price FROM Extras WHERE ExtraID = '4' ");
$colourresult = mssql_query("SELECT ColourID FROM Colours WHERE Type = '8' ");
while ($row = mssql_fetch_array($result, $colourresult)) {
?>
This however didn't work, when I tried to echo out:
<?php echo $row['ColourID']; ?>
Can anyone tell me how I should be approaching this, and if I am at all on the correct track. Sorry if I havn't explained it very well.
To answer your first question:
Yes, you can use any variable name you like for the result and row variables. PHP doesn't care what you call them, and in fact it's perfectly possible to have several of them in use at any given time, in which case they obviously need to have different names.
You then followed up that question by asking why the following code doesn't work:
$result = mssql_query("SELECT Price FROM Extras WHERE ExtraID = '4' ");
$colourresult = mssql_query("SELECT ColourID FROM Colours WHERE Type = '8' ");
while ($row = mssql_fetch_array($result, $colourresult)) {
....
}
The reason for this is that the _fetch_array() function can only work with one set of results at a time. You would need to fetch a separate row array for each of them.
It's not clear what you're trying to do with these two queries, and why you would want to put them into the same loop together in the way you've shown.
I'm going to assume that the two queries are linked in some way that makes it logical for you to use them together like this? Perhaps the Extra item you're loading has a known Colour; ie you know that the Extra item numbered 4 is coloured with the Colour numbered 8?
Typically a program wouldn't be written with this knowledge; it would be part of the data. So in the Extras table, you would have a ColourID field, which would contain the value 8. The program would load the Extras record, see that the ColourID was set, and then load the matching Colours record according to what it saw.
Thus, your code could look something like this:
$result = mssql_query("SELECT Price FROM Extras WHERE ExtraID = '4' ");
while ($row = mssql_fetch_array($result)) {
$colourresult = mssql_query("SELECT ColourID FROM Colours WHERE Type = '".$row['colourID']."' ");
while ($row2 = mssql_fetch_array($result)) {
....
}
}
Inside the inner while loop, you could then access fields from either query, using $row or $row2 respectively (again, you can name these as you see fit).
However, that's not the end of the story, because SQL actually has the ability to merge these two queries into one without needing all that PHP code, using a thing call a SQL JOIN.
Now we can write a more complex query, but go back to having simpler PHP code:
$result = mssql_query("SELECT Extras.Price, Colours.ColourName FROM Extras WHERE ExtraID = '4' INNER JOIN Colours ON Colours.ColourID = Extras.ColourID");
while ($row = mssql_fetch_array($result)) {
....
}
If you're a beginner in PHP and SQL, these concepts are all probably new to you, so I advise trying them out, experimenting with them, and most importantly, reading a few (good quality) tutorials about them before proceeding much further.
Hope that helps. :)
(PS: as I said above, make sure you're reading good tutorials; beware of bad PHP examples and teaching sites -- there's a lot of them out there, teaching poor code and obsolete techniques; make sure you're reading something worthwhile. A good place to start might be http://phpmaster.com/)
This is because mssql_fetch_array can only take one result set. So removing $result and leaving $colourresult should work for you.
See: http://php.net/manual/en/function.mssql-fetch-array.php
Your variables ($...) can be called whatever you want, it's generally better to name them in a way that you can understand, hence most of the examples in the PHP Manual contain variables like $row, $result, $query, etc.
In terms of your database query, you can only pass one query to the mssql_query method. If you have data from different tables that you need to display, you should try and join the tables if possible using SQL rather than looping through multiple result sets.

Codeigniter 2.1 - active record

I have reached dead end with the brain o.O. In DB I have two tables:
store_module->caffe_id, module_id, position, order
module->id_module, name, description, image
I have query where I take all modules for set ID (store_module table), and I need to get all modules which appear in this query (module_id). What I need to do?
This is the code (I am awake for 30+ hours and my brain is refusing to communicate with me, deadline is almost here, and this on of the last things I need to do. So, please help :D):
function mar_get_modules($id){
$q = $this->db->get_where('store_module', array('caffe_id' => $id));
$modules = $q->result_array();
}
Start simple, by using a regular query (if I guess right, you need a JOIN there).
This query should work:
$sql = "SELECT m.*,sm.* FROM module m
LEFT JOIN store_module sm ON sm.id_module = m.module_id
WHERE sm.caffe_id = ?";
return $this->db->query($sql, array($id))->result_array();
Now, you can transform it into an AR query:
$query = $this->db->select('module.*,store_module.*')
->from('module')
->join('store_module', 'store_module.id_module = module.module_id','left')
->where('store_module.caffe_id',$id)
->get();
return $query->result_array();
While AR is quicker sometimes, I usually prefer writing my queries "by hand", taking advantage of the binding to prevent SQL injections; it's a lot easier to see how things are working if you have a query fully laid under your eyes
Sasha,
In the function above, you are not returning anything. You'll need to update the 3rd line something to the effect of return $q->result_array();

PHP SQL Multiple autocomplete search

currently I've written a code and it works fine with only keyword. Also, it doesn't take care of multiple entries. for example, if I have the keyword "blue" twice in DB; it shows "blue" twice in the search input box when I start typing "blue". Rest of the code works fine. How should I tweak my code? Also, if a column has "blue" & "green" as the row; it shows the complete thing: "blue & green". My php code:
<?php
$keyword = mysql_real_escape_string($_POST['keywords']);
$sql = "SELECT * FROM job WHERE work='$keyword' or work LIKE 'ANOTHER_PARAMETER' LIMIT 5";
$result = mysql_query($sql);
$numrows = mysql_num_rows($result);
echo //details and run the loop
?>
You can try modifying your SQL DB. You can have a column of "work_ids" and another for "work corresponding to those ids".
Sorry, I left a part of your question unanswered but thanks to #T-shirt Dude; I remebered it instantly. If I am reading your question right, you want to search for multiple keywords in a single column? If so you can do:
$sql = mysql_query("SELECT work_id, work FROM job
WHERE work like '%$q%' OR work like 'ANOTHER_PARAMETER'
ORDER BY work_id LIMIT 10");
You can put as many "OR"s that you want.
Considering the work to be the column with the values 'blue' and 'green' in it, the code should be:
"SELECT * FROM job WHERE work='$keyword' or work LIKE 'ANOTHER_PARAMETER' GROUP BY work LIMIT 5";
If that's not the case, I was unable to understand your question.
I'm not sure I completely follow--seeing the code that creates response might help us a little more.
At any rate, from the way I'm understanding your problem, it sounds like you might need a group by.

Categories