I want to select a value from a database in sql with php. So, the value that I want to select is a part of the value which I compare it with.
There are two tables: one is called event and the other weekly. In the table event, there is a column called name, that is the name of each event. Weekly has also a column called name, and it´s the name of the weekly. So, I want to get the id from a weekly comparing the two names. But the name of the event can have something before and/or after the name. For example:
Weekly name: Monday
Weekly id: 1
Event: NJK Monday 3
Another example:
Weekly name: Tuesday
Weekly id: 2
Event: Tuesday ks
I´ve tried to do it with a LIKE condition, but I didn´t earn the result that I wanted.
$stmt = $conn->prepare("UPDATE db.event SET weeklyid ="
. " (SELECT id FROM db.weekly WHERE %name%"
. " LIKE 'NJK Monday 3') WHERE name = :name;");
$stmt->bindValue('name', $event->name);
$stmt->execute();
So, it´s like an inverse LIKE. The result that I want to get from the code above would be that the select sentence return 1.
You can use CONCAT() to add the % symbols around the attribute like this
SELECT id FROM db.weekly WHERE 'NJK Monday 3' LIKE CONCAT('%', name, '%')
I'm not sure how it works with named placeholders by if you will use ? placeholder you should add % to execute values not to query:
wrong
$stmt = $conn->prepare('SELECT id FROM db.weekly WHERE name LIKE %?%');
$stmt->execute(['NJK Monday 3']);
good
$stmt = $conn->prepare('SELECT id FROM db.weekly WHERE name LIKE ?');
$stmt->execute(['%NJK Monday 3%']);
Related
In Doctrine, is it possible to bind the name of a parameter
(contrary to binding the value of a parameter)?
Why I need it
There is a table having 7 boolean columns, one for each day of the week: monday, tuesday, etc. (these correspond to the structure of the calendar entity defined by GTFS, https://gtfs.org/schedule/reference/#calendartxt).
Given a day of the week (say, monday), I want to get all rows, which are available on Mondays, i.e.:
$statement = $this
->getEntityManager()
->getConnection()
->prepare('
SELECT id
FROM calendar
WHERE monday = 1
');
Generally, I want to be able to supply the name of a day in that query, which I can do simply by:
->prepare("
SELECT id
FROM calendar
WHERE $dayName = 1
");
I wonder whether it's possible to use the parameter binding for the names of parameters, i.e. something like
$statement = $this
->getEntityManager()
->getConnection()
->prepare('
SELECT id
FROM calendar
WHERE :dayName = 1
');
$statement->bindValue('dayName', $dayName);
which does not work, see below.
What I tried
#1
WHERE :dayName = 1
which translates to the following SQL query:
SELECT calendar.id
FROM calendar
WHERE 'monday' = 1
and, because that condition is never true, returns an empty set, [].
#2
WHERE `:dayName` = 1
SELECT calendar.id
FROM calendar
WHERE `'monday'` = 1
Column not found: 1054 Unknown column ''monday'' in 'where clause'
#3
WHERE ":dayName" = 1
# no query
Invalid parameter number: number of bound variables does not match number of tokens
This is of course not possible.
Within the statement, placeholders can be used as parameter markers to indicate where data values are to be bound to the query later when you execute it. The parameter markers should not be enclosed within quotes, even if you intend to bind them to string values. Parameter markers can be used only where expressions should appear, not for SQL keywords, identifiers, and so forth.
In short: you can use parameter markers for literals (string, numbers, ..) only
If you can't change your database design I would recommend using another SQL statement with a simple bit check:
prepare("select id, (monday +
tuesday * 2 +
wednesday * 4 +
thursday * 8 +
friday * 16 +
saturday * 32 + sunday *64) as day
from calendar having (day) & (1 << :daynumber)")
Now you can simply check if a service is available on a specific weekday, by binding the daynumber (monday=0, tuesday=1, .. sunday=6).
I have a table with the following example:
ID
name
task
startDate
endDate
1
John
Day
2022-09-20
2022-09-21
2
Joe
Midday
2022-09-20
2022-09-21
3
John
Day
2022-09-22
2022-09-23
4
Sara
Night
2022-09-20
2022-09-21
5
Joe
Night
2022-09-24
2022-09-25
I would like to count the rows that have a name in a given name list AND task in a given task list AND within a date range.
I am using php and the code and sql query I am currently using is:
$taskList = list of all the tasks I want to search for
$nameList = list of all the names I want to search for
SELECT COUNT(ID) FROM table WHERE
`task` IN ('".implode("', '", $taskList)."')
AND `name` IN ('".implode("', '", $nameList)."')
AND (startDate >= '".$startDate."')
AND (startDate <= '".$endDate."')
It takes ~40 milliseconds per execution but I need to do this multiple times. Is there a way I can shorten the execution time?
Looks like your query is fast enough, but on some case it also slow.
Please make sure:
Add index group to your table columns that where query executed:
task, name, startDate
Consider don't use asterisk to select count query with the column name that not nullable values, try to use select count(primary_key_column)
Just Test The difference.
But, before start please doing escape the values before doing direct query to sql to prevent sql injection and or invalid data value.
/**
* #var PDO $pdo
*/
$taskList = array_map([$pdo, 'quote'], $taskList);
$nameList = array_map([$pdo, 'quote'], $nameList);
$startDate = $pdo->quote($startDate);
$endDate = $pdo->quote($endDate);
$quotedTaskList = implode(',', $taskList);
$quotedNameList = implode(',', $nameList);
$query = "SELECT COUNT(primary_key_or_non_nullable_column) FROM table WHERE
`task` IN ({$quotedTaskList}')
AND `name` IN ({$quotedNameList})
AND (`startDate` >= {$startDate})
AND (`startDate` <= {$endDate})
";
I am new to php and sql; i am writing a sql query to display records where the following logic follows:
1. There are 9 cells in sql table. I want to search records using combinations of 3 parameters. That are search between 2 dates, search in location and search in property category type.
2. Search criteria looks like this :
Date From : _________(date picker) - Date Till:______________(date picker)
Location: Dropdown ( dehi, mumbai,.....,)
Property Category Type : Dropdown ( Residential, Commercial)
Results Combination Required:
a. All 3 combination True - (User Fills the date, location, Prop Cat Type.)
b. Either of the combination is True. (User only fills either of one parameter.)
c. Only 2 Combination are True. (User fills 2 parameter combination ie, date and location (or) location & property type (or) date & property type)
PROBLEM:
I can able to do only one combination....
Here is my sql query and page syntax.:
if(isset($_POST['search'])){
$name=$_POST['search'];
$location=$_POST['select1'];
$date1=$_POST['d_dov1'];
$date2=$_POST['d_dov2'];
$categ=$_POST['category'];
$query="SELECT * FROM customer WHERE d_loc='$location' OR d_dov BETWEEN '$date1' AND '$date2' OR d_cate='$categ'";
$sql_Q=mysql_query($query); }else{
$Q_select = "Select * from customer Order by id DESC";
$sql_Q = mysql_query($Q_select) or die(mysql_error()); }
Please help in this regard.
you can concatenate your query and do this task.
if(isset($_POST['search'])){
$name=$_POST['search'];
$location=$_POST['select1'];
$date1=$_POST['d_dov1'];
$date2=$_POST['d_dov2'];
$categ=$_POST['category'];
$query="SELECT * FROM customer WHERE id!=0";
if($location!=''){
$query.=" AND d_loc='$location'";
}
if($date1!='' && $date2!=''){
$query.= " AND d_dov BETWEEN '$date1' AND '$date2'";
}
if($categ!=''){
$query.= " AND d_cate='$categ'";
}
if you select all values you query concatenate.The idea behind using id!=0 is to concatenate the query.the id is the primary key of your table.
You can use AND or OR its depends on your need.
I am using xampp for my database and dreamweaver for my website.
Fields in database :
field 1 = id : int, primarykey and auto increment
field 2 = name : text
field 3 = birthday : datetime
example data :
id: 01
name : jhon
birthday : 2000-06-01
In dreamweaver I have 2 textfields and 3 select/list :
One textfield for id, one textfield for name, one select/list for year in birthday, one for month and one for day.
I can get the id and name from the database and show it by using php echo.
How do I show the birthday separately in each select/list year, month and day ?
When you retrieve the datetime variable, you'll have it in a string similar to this:
$datetime = '2000-06-01';
If you have already gotten to that point, then do the following:
list($year, $month, $day) = explode("-", $datetime);
echo "year = ".$year."<br>";//year = 2000
echo "month = ".$month."<br>";//month = 06
echo "day = ".$day."<br>";//day = 01
Hope I could help! :)
If you want do this operation in SQL, in MySQL you have a fonction called DATE_FORMAT() to customize the format of you date
so to split the date into 3 fields (aliases of the orginal record), use a query like that :
SELECT
id,
name,
DATE_FORMAT(birthday,'%d') AS birth_day,
DATE_FORMAT(birthday, '%m') AS birth_month,
DATE_FORMAT(birthday, '%Y') AS birth_year
FROM the_name_of_your_table
You will find on this URL https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format all the parameters accepted by this functions and returns format.
Hope that help you.
This is my query to search the data base for candidates who meet a certain criteria. I am using php, mysql, html
$Odata = mysql_query("SELECT * FROM p_candidate WHERE(`gender` LIKE '%".$Gender."%')
AND (`verbal` LIKE '%".$Verbal."%') AND(`waiver` LIKE '%".$Waiver."%')
AND(`waiver_type` LIKE '%".$W_Type."%') AND(`sel_staff` LIKE '%".$A_Staff."%')
AND(`sel_peers` LIKE '%".$A_Peers."%')AND(`verbal` LIKE '%".$Awake."%')
AND(`ambulatory` LIKE '%".$Ambulatory."%') AND(`function` LIKE '%".$Function."%')"
) or die(mysql_error());
There is another criteria I want to add - Adult/Child.
I have date of birth as a column in the DB. If the candidate is above 18, would fall under Adult, otherwise Child.
The user may want to search for an adult with all the contents in $Odata. How can I do this?
looking through Calculate Age in MySQL (InnoDb)
and Search age range in mysql, php I understand it can be done independently, but how can I incorporate it into my above query. Is that possible?
This might help
sample data
create table dob
(
dob datetime
)
;
insert into dob select '2001-10-08' ;
insert into dob select '1976-11-28' ;
Figure out child or adult:
select
dob,
case when dob > Current_date() - INTERVAL 18 YEAR then 'child' else 'adult' end
from dob
see http://sqlfiddle.com/#!2/2df6d/12
You can find a correct answer in the official MySQL documentation:
SELECT CASE WHEN TIMESTAMPDIFF(YEAR,dob,CURDATE()) >=18 THEN 'adult' ELSE 'child' END
FROM p_candidate;