I've looked all over their docks but they really like to use active records. Can someone please tell me how to do a plain old SQL insert for an INSERT in Codeigniter?
EDIT
And this is for their $this->db object;
It's a good idea to escape your inputs.
$sql = "INSERT INTO `yourtable` VALUES `foo`= ? WHERE `id` = ?";
return $this->db->query($sql, [$bar, $id]);
or for an update
$sql = "UPDATE `yourtable` SET `foo`= ?, `bar` = ? WHERE `id` = ?";
return $this->db->query($sql, [$f, $b, $id]);
Using query:
$this->db->query("INSERT INTO ...");
Using active record:
$data = array(
"attribute" => "value"
);
$this->db->insert("table_name", $data);
References:
https://www.codeigniter.com/userguide2/database/queries.html
https://www.codeigniter.com/userguide2/database/active_record.html
Related
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 have to INSERT INTO two tables at once, let's say one table is my client_enquiry and another table is the client_materials.
Until here it's okay, the INSERT command it's working in both tables. And If something bad happens when I'm inserting on the second table (client_materials)? How can I "rool back" if the INSERT command fails on table client_materials?
Basically I have this:
$sql_table1 = "INSERT INTO client_enquiry (reference, date) VALUES ('REF', '2013-05-12')";
$q = $conn->prepare($sql_table1);
$q ->execute();
$Last_ID = $conn->lastInsertId('id_enquiry');
$sql_table2 = "INSERT INTO client_materials (id_client_enquiry,description, date)
VALUES (".$Last_ID."'Description', '2013-05-12')";
$q = $conn->prepare($sql_table2);
$q -> execute();
Do the very rollback you mentioned.
$conn->beginTransaction();
try
{
$sql = "INSERT INTO client_enquiry (reference, date) VALUES (?,?)";
$q = $conn->prepare($sql);
$q ->execute(array('REF', '2013-05-12'));
$Last_ID = $conn->lastInsertId();
$sql_table2 = "INSERT INTO client_materials (id_client_enquiry,description, date)
VALUES (?,?,?)";
$q = $conn->prepare($sql);
$q -> execute(array($Last_ID, 'Description', '2013-05-12'));
$conn->commit();
}
catch (PDOException $e)
{
$conn->rollback();
throw $e;
}
You just need to be sure that engine supports transactions and PDO is set into exception throwing mode
i have tried to make sql code in CI, the problem is the ID_LABEL at t_publisher is filled with 0 where it should filled with number that taken from t_label..
$sql['query1'] = "INSERT into t_user (USER_NAME, USER_PASS, USER_STATUS, USER_TYPE) values ('$user', '$pass','1','publisher')";
$sql['query2'] = "INSERT INTO t_label (LABEL) values('$user')";
$id_label = "select id_label from t_label where label ='".$user."'";
$id = $this->db->query($id_label)->result();
$sql['query3'] = "INSERT INTO t_publisher (PUBLISHER, ARTIS, ID_LABEL) values('$user', 'Various Artist', '$id')";
$result = array();
foreach($sql as $key => $value){
$result[$key] = $this->db->query($value);
}
please help :)
to get the id_label
try this
$id_result = $this->db->query($id_label);
foreach($id_result->result_array() as $row){
$id=$row['id_label'];
}
$id is returning an object not a single value. Try inserting $id->id_label instead of just $id
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;
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 );