I'm using this and it works fine.
$stmt1 = $conn->prepare("SELECT * FROM Authors WHERE First=:id");
$stmt1->bindParam(':id', $_GET['name'], PDO::PARAM_STR);
blah blah...
It also works when I change WHERE 'First=:id' to 'Last=:id' but it fails when I include an OR clause as below.
$stmt1 = $conn->prepare("SELECT * FROM Authors WHERE First=:id OR Last=:id");
$stmt1->bindParam(':id', $_GET['name'], PDO::PARAM_STR);
I found this below in Stack #3030650.
$stmt = $dbh->prepare("SELECT * FROM REGISTRY WHERE firstname = :name OR lastname = :name");
$stmt->bindParam(':name', $name);;
Since these appear the same, what am I overlooking.
Thanks for any advice.
I would bind it twice, perhaps with different placeholders even though it's the same value:
$query = "SELECT * FROM REGISTRY WHERE firstname = :fname OR lastname = :lname";
$stmt = $dbh->prepare($query);
$stmt->bindParam(':fname', $name);
$stmt->bindParam(':lname', $name);
Related
I have the following code and the output will be in array. How can I find arrays that match between $pesara and $ahli. the condition between it is CURRENT_ID_NO is equal to ic_no
$sql = "SELECT CURRENT_ID_NO, NAME, MOBILE_NO FROM pesara";
$dbCommand = Yii::app()->db->createCommand($sql);
$pesara = $dbCommand->queryAll();
$sql2 = "SELECT name, ic_no, ic_type, tel_no, pesara, created_dt, created_by, updated_dt, updated_by FROM ost_ahli";
$dbCommand2 = Yii::app()->db->createCommand($sql2);
$ahli = $dbCommand2->queryAll();
$result = array_intersect($pesara->CURRENT_ID_NO, $ahli->ic_no);
print_r($result);
Sorry for my bad English but I hope someone can help me on this.
You can use array_uintersect() for custom comparison
and also have sample code for that here
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
I am new to zend framework,
Following is the plain mysql query which takes particular column from table,
SELECT jobs_users.id,jobs_users.first_name from jobs_users left join friends on jobs_users.id=friends.friend_id where friends.member_id=29
I tried with zend to implement the above query like below,
public function getFriendsProfileList($id){
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select();
$select->from('jobs_users')
->joinLeft(
'friends',
'jobs_users.id=friends.friend_id',
array('jobs_users.id','jobs_users.first_name','jobs_users.last_name','jobs_users.photo')
)
->where("friends.member_id = ?", $id);
$result = $db->fetchAll($select);
return $result;
}
Here i got result with all column name , not with exact column name which i have given in query.
Kindly help me on this.
Use this instead:
$select->from('jobs_users', array('jobs_users.id','jobs_users.first_name','jobs_users.last_name','jobs_users.photo'))
->joinLeft('friends', 'jobs_users.id=friends.friend_id')
->where("friends.member_id = ?", '20');
You may also try this:
$select = $db->select();
$select->setIntegrityCheck(false);
$select->joinLeft('jobs_users','',array('jobs_users.id','jobs_users.first_name','jobs_users.last_name','jobs_users.photo'));
$select->joinLeft('friends','jobs_users.id=friends.friend_id', array());
$select->where("friends.member_id = ?", $id);
$result = $db->fetchAll($select);
return $result;
How to write SQL LIKE Query in drupal ,
SELECT title FROM { node } WHERE type='%s'
i want to add the LIKE CONDITION IN THAT
SELECT title FROM { node } WHERE type='%s' AND LIKE '%S%'
i think i writtern wrong like query formnat, can rewrite and tell me,
Just use % to escape.
$result = db_query('SELECT title FROM {node} WHERE type = "%s" AND title LIKE "%%%s%%"', 'type', 'title');
while ($row = db_fetch_object($result)) {
// do stuff with the data
}
Node type does not need escaping.
And here is an example with how to use LIKE in a dynamic query (Drupal 7 Only):
$query = db_select('node', 'n')
->fields('n', array('title'))
->condition('type', 'my_type')
->condition('title', '%' . db_like(search_string) . '%', 'LIKE');
$result = $query->execute()->fetchCol();
db_like() is used to escapes characters that work as wildcard characters in a LIKE pattern.
drupal_query replace %% to % and %s to value string
so your code will be
$sql = "SELECT title FROM node WHERE type='%%%s' AND title LIKE '%%%S%%'";
$type = "type to use in query";
$title = "title to use in query";
$result = db_result(db_query($sql, $type, $title));
OK, so you want the LIKE operator to refer to the title column. Use this query:
$sql = "SELECT title FROM node WHERE type='%s' AND title LIKE '%S%'";
$type = "type to use in query";
$title = "title to use in query";
$result = db_result(db_query($sql, $type, $title));
This is because the LIKE operator requires a column name to be specified. Otherwise, your database doesn't have any idea what value you want to perform the comparison on. See here.
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 );