PDO query errors - pdo

If I change the first line of my PDO code below to "SELECT count(*) from writing AS posts" I get errors that the writing.ID and writing.approved columns do not exist (which they do). And if I get rid of the AS posts, then I just get Call to undefined function execute()
Can anyone see what I am doing wrong?
$sql ="SELECT count(*) from writing
LEFT JOIN stories on writing.SID = stories.SID
LEFT JOIN wp_users ON writing.ID = wp_users.ID
WHERE (wp_users.ID != $user_ID) AND (writing.approved = 'Y') ";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':wp_users.ID', $user_ID, PDO::PARAM_INT);
$stmt->bindParam(':stories.ID', $ID, PDO::PARAM_INT);
$stmt->bindParam(':writing.ID', $ID, PDO::PARAM_INT);
$stmt->bindParam(':writing.WID', $WID, PDO::PARAM_INT);
$stmt->bindParam(':approved', $j = Y, PDO::PARAM_STR);
$stmt->bindParam(':position', $position, PDO::PARAM_INT);
$stmt-->execute();
$therow = $stmt-->fetchAll(PDO::FETCH_ASSOC);

Two issues going on...
If you define table aliases, you must reference columns using the alias (or unqualified).
SELECT table.column FROM table /* RIGHT */
SELECT a.column FROM table AS a /* RIGHT */
SELECT column FROM table /* RIGHT */
SELECT column FROM table AS a /* RIGHT */
SELECT table.column FROM table AS a /* WRONG */
SELECT a.column FROM table /* WRONG */
Regarding the undefined function:
$stmt-->execute();
What you did was $stmt-- > execute() which compares if $stmt is greater than the result of the non-object-oriented function execute().
You must use only one dash with the object-oriented method invocation syntax:
$stmt->execute();

Related

Where Clause is not working in Update but working in Select in Oracle DB

I am trying to execute the below update query
update custom_field cfe set cfe.field_value =:valueId where cp_entity_id = :cId
0 rows updated.
This is not updating any row but same where clause is working fine with select query and returns 1 row
select * from custom_field where cp_entity_id = :cId
Also, if i hardcode the value of cId parameter then update works fine but I am executing it from java program so it's not possible for me to hardcode the value
Also cp_entity_id column is a foreign key.
Try this, I faced similar issue.
Use this
select primary_key from custom_field where cp_entity_id = :cId query to find out primary key and Then use that primary key in your where clause of update query.
One of the ways to set parameter is explained here.
PreparedStatement ps = conn.prepareStatement(
"UPDATE Messages SET description = ?, author = ? WHERE id = ? AND seq_num = ?");
// set the preparedstatement parameters
ps.setString(1,description);
ps.setString(2,author);
ps.setInt(3,id);
ps.setInt(4,seqNum);
// call executeUpdate to execute our sql update statement
ps.executeUpdate();
ps.close();

Parameters can't be passed in when using perl DBI to create view

I want to use Perl DBI to create views based on a database automatically. The related code is like the following,
my $dbh = DBI->connect( "dbi:Oracle:$database", $user_passwd );
my $Directive = q{ CREATE OR REPLACE VIEW SOME_VIEW AS SELECT * FROM ID_TABLE WHERE ID=?};
my $ID = 12345;
my $sth = $dbh->prepare($Directive);
my $rv = $sth->execute($ID);
Then I found the $rv is always undef after I run the code. Anything wrong I've made in the code? When I put the parameter directly into $Directive, everything is good.
BTW, when I use some other $Directive, like "SELECT * FROM ID_TABLE WHERE ID=?", the parameter $ID could be passed in without any problem.
SQL does not allow views to be created with a placeholder in the condition as in your example. All else apart, there isn't a notation that allows you to specify the value for the placeholder when referencing the view. DDL statements in general do not take input parameters.
You will have to do things differently, probably foregoing the view.
This is not a limitation of Perl or DBI per se, nor even really the specific DBMS you're using; it is an issue with the design of SQL as a whole.
Much the simplest way to deal with this specific case is:
my $dbh = DBI->connect( "dbi:Oracle:$database", $user_passwd );
my $ID = 12345;
my $sql = qq{ CREATE OR REPLACE VIEW SOME_VIEW AS SELECT * FROM ID_TABLE WHERE ID = $ID };
my $sth = $dbh->prepare($sql);
my $rv = $sth->execute();
Simply embed the value of the parameter in the SQL statement that you prepare and execute.

mysql_db_query for mssql in php

What is mssql function that have similar with mysql_db_query()?
and what about mysql_insert_id()?
Look at the PHP Mssql documentation. The functions you're looking for are mssql_query() and the following:
<?php
function mssql_insert_id() {
$id = 0;
$res = mssql_query("SELECT ##identity AS id");
if ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
$id = $row["id"];
}
return $id;
}
?>
I think the closest you will come to this in T-SQL is the following:
Use <MyDatabase>
Exec ('Select <ColumnList> From <SomeTable>')
In MSSQL, you can use the SCOPE_IDENTITY() function to get the last ID created by the given connection, in the same scope. Put them both together so you get the ID back just after row creation.
INSERT INTO myTable (field1,field2) VALUES(val1,val2); SELECT SCOPE_IDENTITY() AS myId;
Note, you could also use ##IDENTITY, but that returns the last ID created, regardless of scope, so if you inserted a new row, and a trigger/stored procedure fired and inserted something into another table, ##IDENTITY would return that ID.

Two simple MySQL statements causing syntax error

I'm confounded. The following MySQL query:
SET #a := 0;
SELECT *
FROM users;
Gives the error:
Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT * FROM users' at line 2`
When I switch the order of the statements, I get the same error, again on line 2 (even though I switched them)
However, either line by themselves runs fine. What could possibly cause this?
I bet you're trying to perform this query in the mysql_query() (or some similar function from any programming language), but it accepts only single query. So the solution is to split this queries into 2 calls.
you can do it in one query as follows:
The trick
select #a:=#a+1, u.*
from
users u
join (select #a:=0) a
or be adventerous and use a stored procedure so it's always a single call :P
Stored procedure
drop procedure if exists list_users;
delimiter #
create procedure list_users()
begin
set #a = 0;
select #a:=#a+1, u.* from users u;
end #
delimiter ;
call list_users();
PHP script
$conn = new mysqli("localhost", "foo_dbo", "pass", "foo_db", 3306);
$result = $conn->query("call list_users()");
while($row = $result->fetch_assoc()){
...
}
$result->close();
$conn->close();

Postgresql: how to create table only if it does not already exist?

In Postgresql, how can I do a condition to create a table only if it does not already exist?
Code example appreciated.
I'm not sure when it was added, but for the sake of completeness I'd like to point out that in version 9.1 (maybe before) IF NOT EXISTS can be used. IF NOT EXISTS will only create the table if it doesn't exist already.
Example:
CREATE TABLE IF NOT EXISTS users.vip
(
id integer
)
This will create a table named vip in the schema users if the table doesn't exist.
Source
create or replace function update_the_db() returns void as
$$
begin
if not exists(select * from information_schema.tables
where
table_catalog = CURRENT_CATALOG and table_schema = CURRENT_SCHEMA
and table_name = 'your_table_name_here') then
create table your_table_name_here
(
the_id int not null,
name text
);
end if;
end;
$$
language 'plpgsql';
select update_the_db();
drop function update_the_db();
Just create the table and don't worry about whether it exists. If it doesn't exist it will be created; if it does exist the table won't be modified. You can always check the return value of your SQL query to see whether the table existed or not when you executed the create statement.
I think to check the pg_class table perhaps help you, something like that:
SELECT COUNT (relname) as a FROM pg_class WHERE relname = 'mytable'
if a = 0 then (CREATE IT)
Regards.
This is an old question. I'm only bringing back to suggest another answer. Note: other better answers already exist, this is just for educational purposes.
The easiest way is to do what others have said; perform the CREATE TABLE if you want to keep the existing data, or perform a DROP IF EXISTS and then a CREATE TABLE, if you want a freshly created table.
Another alternative is to query the system table for its existence and proceed from there.
SELECT true FROM pg_tables WHERE tablename = <table> [AND schemaname = <schema>];
In use:
-- schema independent:
SELECT true FROM pg_tables WHERE tablename = 'foo';
-- schema dependent:
SELECT true FROM pg_tables WHERE tablename = 'foo' AND schemaname = 'bar';
If it matches you'll have a true value, otherwise it should return an empty dataset. You can use that value to determine if you need to perform a CREATE TABLE.
The best answer has been given by Skalli if you're running Postgresql 9.1+.
If like me you need to do that with Postgresql 8.4, you can use a function with a 'duplicate_table' exception catch.
This will ignore the generated error when the table exists and keep generating other errors.
Here is an example working on Postgresql 8.4.10 :
CREATE FUNCTION create_table() RETURNS VOID AS
$$
BEGIN
CREATE TABLE my_table_name(my_column INT);
EXCEPTION WHEN duplicate_table THEN
-- Do nothing
END;
$$
LANGUAGE plpgsql;
What I used to check whether or not a table exists (Java & PostgreSQL)
prior to creating it. I hope this helps someone.
The create table portion is not implemented here, just the check to see if
a table already exists.
Pass in a connection to the database and the tableName and it should return whether
or not the table exists.
public boolean SQLTableExists(Connection connection, String tableName) {
boolean exists = false;
try {
Statement stmt = connection.createStatement();
String sqlText = "SELECT tables.table_name FROM information_schema.tables WHERE table_name = '" + tableName + "'";
ResultSet rs = stmt.executeQuery(sqlText);
if (rs != null) {
while (rs.next()) {
if (rs.getString(1).equalsIgnoreCase(tableName)) {
System.out.println("Table: " + tableName + " already exists!");
exists = true;
} else {
System.out.println("Table: " + tableName + " does not appear to exist.");
exists = false;
}
}
}
} catch (SQLException sqlex) {
sqlex.printStackTrace();
}
return exists;
}
The easiest answer is :
catch{
#create table here
}
This creates a table if not exists and produces an error if exists. And the error is caught.
http://www.postgresql.org/docs/8.2/static/sql-droptable.html
DROP TABLE [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ]
Try running a query on the table. If it throws an exception then catch the exception and create a new table.
try {
int a = db.queryForInt("SELECT COUNT(*) FROM USERS;");
}
catch (Exception e) {
System.out.print(e.toString());
db.update("CREATE TABLE USERS (" +
"id SERIAL," +
"PRIMARY KEY(id)," +
"name varchar(30) NOT NULL," +
"email varchar(30) NOT NULL," +
"username varchar(30) NOT NULL," +
"password varchar(30) NOT NULL" +
");");
}
return db;