SQL Query won't accept variables for ALL the parameters - sql

I have a database table with an event_id column and a scheduled_at column.
The query is called in php and is as such:
$columnName = 'scheduled_at';
$start = '2013-02-26';
$end = '2013-02-27';
// query to be executed
$sql = ( SELECT * FROM $table WHERE $columnName BETWEEN $start AND $end );
The query does not work when executed, however the following does work
$sql = ( SELECT * FROM $table WHERE $columnName BETWEEN $start AND '2013-02-27' );
and
$sql = ( SELECT * FROM $table WHERE $columnName BETWEEN $start AND $start );
does not work, but the following does work
$sql = ( SELECT * FROM $table WHERE $columnName BETWEEN '2013-02-27' AND '2013-02-27' );
Inserting the value manually makes it work but loses the usefulness of the function. Any ideas why it would not work?

you need to quote your variables, so that the SQL string that is created containes quotes around the date values. eg
$sql = "( SELECT * FROM $table WHERE $columnName BETWEEN '$start' AND '$end' )";

Related

Retrieve a single columnSQLl from database

Which code do I need to retrieve a single value i from a column from table in SQL?
user_comment_count
This is column name in table
table is :
zmar_hreviews_list_total
This is code I use with error:
<?php
$insert1 ="/// ";
$string = "ars <pre>{$insert1}</pre>";
$query = 'SELECT user_comment_count FROM zmar_hreviews_list_total WHERE contentid = '.$item->getId();
$db->setQuery( $query );
$result = $db->loadResult();
if($result) {
$result = str_replace('*','',$result);
print_r($insert1); print_r($result);
}
?>
try:
select user_comment_count from zmar_hreviews_list_total

LastInserID from other table insert to table [duplicate]

I have a query, and I want to get the last ID inserted. The field ID is the primary key and auto incrementing.
I know that I have to use this statement:
LAST_INSERT_ID()
That statement works with a query like this:
$query = "INSERT INTO `cell-place` (ID) VALUES (LAST_INSERT_ID())";
But if I want to get the ID using this statement:
$ID = LAST_INSERT_ID();
I get this error:
Fatal error: Call to undefined function LAST_INSERT_ID()
What am I doing wrong?
That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().
Like:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
Like this $lid = $conn->lastInsertId();
Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php

SQL - PHPmyadmin - Alter table order by 'id ascending' - Make permanent

If I run this:
ALTER TABLE `equipos11a12` ORDER BY `ID`
It only happens one time. If I change the ids, it wont change in ascending order.
I have to run the alter table everytime in order for the ids to order.
Here is my php code:
$query = "SELECT * FROM equipos11a12";
$result = mysql_query($query); ?>
while($person = mysql_fetch_array($result)) {
echo " " . $person ["name"] . " ";
You must add the order by clause to your select query :
$query = "SELECT * FROM equipos11a12 ORDER BY `ID` ASC"; // ascending order
$query = "SELECT * FROM equipos11a12 ORDER BY `ID` DESC"; // descending order

Trouble creating MySQL query in Symfony containing JOIN and RAND()

How do I do this:
SELECT t.id
FROM table t
JOIN (SELECT(FLOOR(max(id) * rand())) AS maxid FROM table)
AS tt
ON t.id >= tt.maxid
LIMIT 1
in Symfony? (I know how to do basic stuff, but this is too much.
$connection = Doctrine_Manager::getConnection()->getDbh();
won't work... Try this:
$connection = Doctrine_Manager::getInstance()->getCurrentConnection()->getDbh();
Then:
$stmt = $connection->query('SELECT * FROM some_table');
$stmt->execute();
$result = $stmt->fetchAll();
$connection = Doctrine_Manager::getConnection()->getDbh();
$result = $connection->query('SELECT ...');

How can I use placeholders for variadic SQL functions with Perl's DBI?

I don't know if "variadic" is actually the right word, but I'm talking about things that can take a list of values, like IN(). If you've been working with DBI for long, you've probably tried to do this:
(Note: All examples extremely simplified for brevity)
my $vals = join ', ', #numbers;
my $sth = $dbh->prepare( "SELECT * FROM mytbl WHERE foo IN( ? )" );
$sth->execute( $vals ); # doesn't work
DBI placeholders simply don't support these kinds of shenanigans, it's a single value for each ? or nothing, as far as I know.
This leads me to end up doing something like:
my $sth = $dbh->prepare( "SELECT * FROM mytbl WHERE foo IN ( $vals )" );
which isn't so horrible, but consider a function, like one I wrote today, that has to accept some arbitrary SQL with an IN clause and a list of values
sub example {
my $self = shift;
my ( $sql, #args ) = #_;
my $vals = join ', ', #args;
$sql =~ s/XXX/$vals/; <---- # AARRRGHGH
my $sth = $self->dbh->prepare( $sql );
...
}
This ends up getting called by stuff that looks like
my $sql = "SELECT * FROM mytbl WHERE foo IN( XXX ) AND bar = 42 ORDER BY baz";
my $result = $self->example( $sql, #quux );
This really offends my sense of aesthetics. Building custom SQL programmaticly is a big enough pain as it is; I don't want to go down the road of regexing my SQL strings if I don't have to.
Is there a better way?
Food for thought.
DBIx::Simple offers a syntax for this type of thing using a double-question mark placeholder:
$db->query( 'SELECT * FROM mytbl WHERE foo IN ( ?? )', #args );
Also, SQL::Abstract is powerful, but I find sometimes the abstractions don't result in optimal SQL.
Why not:
my $sql = "SELECT * FROM mytbl WHERE foo IN(" . join(',', ('?')x#quux) . ") AND bar = 42 ORDER BY baz";
my $sth = $dbh->prepare($sql);
$sth->execute(#quux);
If you don't mind breaking from pure DBI and using some modules, I'd take a look at SQL::Abstract for your example. SQL::Abstract can take a Perl hash and turn it into a where clause.
my $sql = SQL::Abstract->new;
my #numbers = (1 .. 10);
my ($stmt, #bind) = $sql->where({foo => {'in', \#numbers}});
# $stmt is " WHERE ( foo IN ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) )"
# #bind contains the values 1 through 10.
sprintf is handy in such situations:
my $sth = $dbh->prepare(
sprintf(
'SELECT * FROM mytbl WHERE foo IN( %s )',
join(',', ('?') x #numbers) )
);
If using placeholders and bind values gets clumsy, there's always DBI::quote().
my $sql = sprintf 'SELECT * FROM mytabl WHERE foo IN ( %s )',
join( ',', map { $dbh->quote( $_ ) } #args );