I'm really struggling to get my code to work, and I can't figure out why.
I have a database in my PHPMyAdmin and it contains 2 tables:
tennisCourts
courtID
courtName
bookingFee
tenniscourts_Availability
courtID
court_dateBooked
I am writing a PHP program using PEAR repository, and I am struggling to create code that allows me to:
Display All courtNames and their corresponding bookingFee BASED ON users search date ONLY IF the courtName is not already booked by another user.
Here is my current code:-
$CHOSEN_BOOKING_DATE = $_GET['user_dateField']; //GET's input data from user form in my other html document.
$database->setFetchMode(MDB2_FETCHMODE_ASSOC);
$myQuery = "SELECT * FROM tennisCourts, tenniscourts_Availability WHERE court_dateBooked != $CHOSEN_BOOKING_DATE";
$queryResult =& $db->query($myQuery);
if (PEAR::isError($queryResult)) {
die($queryResult->getMessage());
}
echo '<table>';
while ($Col =& $queryResult->fetchRow()) {
echo '<td>'.$queryResult['courtName'].'</td>';
echo '<td>'.$queryResult['bookingFee'].'</td>';
echo '<td>'.$queryResult['court_dateBooked'].'</td>';
}
?>
The code above displays all the courtNames and BookingFee's for All court_dateBooked fields in my database. I cant get it to display the courtNames and bookingFee only if it isn't booked. If it is booked it should return "sorry no courts found on this date".
I am still new to PHP and SQL so forgive me if I have not made myself clear. I have been researching online and various sources say to use SQL UNION OR JOIN? Could someone please enlighten me on how they could be used in context to my scenario? I really appreciate any help. Thank you for checking out my question.
Try this:
$myQuery = "
SELECT c.courtName
, c.bookingFee
, a.court_dateBooked
FROM tennisCourts AS c
LEFT JOIN tenniscourts_Availability AS a ON c.id = a.courtID
WHERE a.court_dateBooked != '" . $CHOSEN_BOOKING_DATE ."'";
Make sure you sanitize and escape $CHOSEN_BOOKING_DATE properly before executing your query. Since it looks like you're using PDO you should be using prepared statements for this.
Related
I'm confused right now.
I've been coding for some while now, to fix a problem, but I'm going blind on how to do, can anyone help me?
First, I have an datatable with all my customers in, then I click "USE" I should go to another page where I can make an case. This is all good, if I only should use one table, but in my project I need more then 1 table, so my question is:
$sql = "SELECT customers.cust_id,
customers.customer_name, numberplate.car
FROM customers , numberplate WHERE SESSION = numberplate.cust_id";
But I can't see how to do it, I know how to make a profilepage and so on, but this ting really tricks my brian right now. Anyone to help?
My session look like this:
if (isset($_GET['cust_id']) && $_GET['cust_id'] != "") {
$id = $_GET['cust_id'];
} else {
$cust_id = $_SESSION['cust_id'];
}
You're confusing your SQL with PHP.
$_SESSION is the variable which contains PHP's session data.
but your MYSQL statement: "WHERE SESSION = numberplate..." is referencing a column in the mysql table.
You want to use sql like:
SELECT customers.cust_id,
customers.customer_name, numberplate.car
FROM customers , numberplate WHERE numberplate.cust_id = ?";
and then bind the value of $_SESSION['cust_id'] to the database call.
But additionally, you're trying to JOIN two tables together without any details on how to do that...
so your SQL then becomes:
SELECT customers.cust_id, customers.customer_name,
numberplate.car
FROM customers,
JOIN numberplate ON customers.cust_id = numberplate.cust_id
WHERE numberplate.cust_id = ?
So basically, I have an HTML form that asks a user to select an option from a dropdown list. The list is populated with a mysql query, but also includes an additional option labeled as 'All.' If the users selects all I want it my PHP script to run a timecard for so and so and then underneath that do the same thing for the next employee, so on and so forth. So far, it works fine if you select just one person, but if you select all it says there are no results to display :/. Any help is appreciated.
if ($empfullname == 'All') {
$query = "select fullname from ".$db_prefix."info order by fullname asc";
$result = mysql_query($query);
} else {
print timecard_html($empfullname, $local_timestamp_in_week);
}
while ($row=mysql_fetch_array($result)) {
print timecard_html(stripslashes("".$row['empfullname'].""), $local_timestamp_in_week);
}
Also, I know mysql is depreciated, but that is what I know and I am just trying to make it work with this. Thanks.
Now, something looks off in your code. When doing your select statement, you are selecting 'fullname'. But when printing, you are using 'empfullname'. Kindly correct this first.
need some enlightment here, and this is my first post here.
I would like to call and use my previously created mysql view using php... is it possible?
or in another words,
i'm wondering....can we OR how do we call mysql view, that we already created using php? to reduce long query coding
standard generic codes as follow :
$sql= " SELECT shipping.tarrif1, city.city_name
FROM shipping JOIN city
ON shipping.id_city = city.id_city";
$db->QueryArray($sql);
while ($row = $db->Row()) {
echo $row->city_name. " - " . $row->tarrif1 . "<br />\n";
}
now for the MYSQL VIEWS :
$sql= " CREATE VIEW shipsumarry AS SELECT shipping.tarrif1, city.city_name
FROM shipping JOIN city
ON shipping.id_city = city.id_city";
Pure MYSQL command :
query: SELECT * FROM shipsummary
IN PHP :
$sql = i'm badly stuck here...please help
How do we access it using php.
thanks before
Addition 1:
ok... let me rewrite the example :
$sql1= " CREATE VIEW shipsumarry AS SELECT shipping.tarrif1, city.city_name
FROM shipping JOIN city
ON shipping.id_city = city.id_city";
$sql2= "SELECT * FROM shipsummary";
$db->QueryArray($sql2);
$sql2 can not see shipsummary VIEW, coz it's already in a different var
how to utilise and then execute $sql1 ? & $sql2?
The process is the same in PHP - a MySQL view is seen by the client (PHP) as a regular table, so querying it as
mysql_query("SELECT * FROM shipsummary");
// Or for whatever framework you're using:
$db->QueryArray("SELECT * FROM shipsummary");
should work correctly. If it does not work correctly, the MySQL user with which you are accessing the view may have broken permissions. (Seems unlikely though).
UPDATE
After you edited your question, I can see the problem quite clearly.
$sql1= " CREATE VIEW shipsumarry AS SELECT shipping.tarrif1, city.city_name
FROM shipping JOIN city
ON shipping.id_city = city.id_city";
$sql2= "SELECT * FROM shipsummary";
// Here, you need to execute $sql1 before $sql2 is useful.
$db->QueryArray($sql1);
// Now execute $sql2
$db->QueryArray($sql2);
We don't know what database class or framework you are using, but if there is a comparable method to QueryArray() that doesn't return a result set, but just executes a statement, use it to create the view instead.
Now, all that being said...
Unless the definition of the view must change every time this code executes, and unless you have a reason to then DROP VIEW shipsummary at the end of this script's execution each time, it makes far, far, far, far .... more sense to simply create the view in the database, where it will stay forever, rather than to keep re-creating it with PHP. Views, once created, stay created.
Don't think of them as a temporary query time/code saver. Create the views you will need ONCE in your database (using PHPMyAdmin or mysql CLI, or however you created your tables), and access them with PHP.
Why not just send that
SELECT * FROM shipsummary
To mysql query, it should work, unless i'm not understanding your question...
Pls help.
I am working on a php project and this requires adding and altering data from the SQL database. There are two tables involved with this: emp which contains employee details and pay containing payroll records for each employee.
I would like to have a dropdown list containing all employee names (empname) from the database. Below the list is a form where the user shall input the payroll details. These details will then be saved into the SQL pay table corresponding to the employee name selected.
I've tried searching over the web but it doesn't seem to similar to my problem. How should I do this? Thanks!
Wihtout knowing any more details about your datbase, table structure and other stuff, this is closes that I could get.
<?php
/* Connect to SQL and retreive data */
$sqlConf = array('u'=>'username','p'=>'password','h'=>'localhost','d'=>'myDatabase');
$sqlCon = mysql_connect($sqlConf['h'], $sqlConf['u'], $sqlConf['p']);
if ($sqlCon) {
$emp = array();
mysql_select_db($sqlConf['d'], $con);
$result = mysql_query("SELECT * FROM emp");
while($row = mysql_fetch_array($result)) { $emp[] = $row; }
mysql_close($sqlCon);
}
/* Generate select box contents */
$html = '<select name="emp">';
$html .= '<option>Employee list</option>';
if (!empty($emp)) {
foreach ($emp as $k => $v) {
$html .= '<option value="'.$v['empid'].'">'.$v['empname'].'</option>';
}
}
$html .= '</select>';
/* Output */
echo $html;
?>
Sounds like you need to learn some basic php/SQL. The basic outlines of the problem are:
Query the dropdown list from SQL, and display in an option-select.
When they the form submit, send a corresponding query to update the database.
Is there some particular aspect of this problem that you can't get past?
This can be solved in any number of ways and the overall structure, design and layout of your application would dictate which route to go.
You could have classes that represent your database objects, classes that represent your forms, you could print your forms by mixing php and html like a crazy person and so on and so on.
Then it all depends on if you will be using ajax or not.
So give us a bit more information about how your application is designed and that will probably help.
If you have not started at all I would suggest you to look into some of the many frameworks. Zend Framework or Symphony for example. They have a good way of handling db abstractions and forms creation etc.
I'm writing a small application that will write the contents of a csv file to a database in CodeIgniter, but I'm having difficulty checking for dupes before write. Since this is a fairly common task, I was wondering how some of the professionals (you) do it. For context and comparison, here is my (currently non-working) code:
$sql = "SELECT * FROM salesperson WHERE salesperson_name='" . $csvarray['salesperson_name'][$i] . "'";
$already_exists = $this->db->query($sql);
if (sizeof($already_exists) > 0) {
//add to database
}
Any input at all short of "You suck!" (I already hear that from my own brain twice an hour at this point) will be greatly appreciated. Thanks.
What you're doing will work, but as above the comparison should be "== 0" not "> 0".
You can also use CodeIgniters built in num_rows method instead of using sizeof, like so:
$sql = "your query";
$query = $this->db->query($sql);
if ($query->num_rows() == 0) {
// no duplicates found, add new record
}
As a side note, if you're using CodeIgniter then it's worthwhile to use Active Record to build your queries instead of writing SQL. You can learn more about it here: CodeIgniter - Active Record
Firstly you probably want (rather than >0)
if (sizeof($already_exists) == 0) {
//add to database
}
Also could just push all your data to a temporary staging table, which you could then clean out with some spiffy sql- and then push back to your staging table.
Taking a punt on you using mysql (either that or postgres if you are phping) You could try this (taken from http://www.cyberciti.biz/faq/howto-removing-eliminating-duplicates-from-a-mysql-table/)
You will have to change your .ID to your primary key
delete from salesperson_temptable
USING salesperson_temptable, salesperson_temptable as vtable
WHERE (NOT salesperson_temptable.ID=vtable.ID)
AND (salesperson_temptable.salesperson_name=vtable.salesperson_name)
then when you review the contents of salesperson_temptable you can then insert it back to the salesperson table