Is there a way to execute a SQL String as a query in Zend Framework?
I have a string like that:
$sql = "SELECT * FROM testTable WHERE myColumn = 5"
now I want to execute this string directly withput parsing it and creating a Zend_Db_Table_Select object from it "by hand". Or if thats possible create a Zend_Db_Table_Select object from this string, to execute that object.
How can I do that? I didn't find a solution for this in the Zend doc.
If you're creating a Zend_DB object at the start you can create a query using that. Have a look at this entry in the manual : https://framework.zend.com/manual/1.12/en/zend.db.statement.html
$stmt = $db->query(
'SELECT * FROM bugs WHERE reported_by = ? AND bug_status = ?',
array('goofy', 'FIXED')
);
Or
$sql = 'SELECT * FROM bugs WHERE reported_by = ? AND bug_status = ?';
$stmt = new Zend_Db_Statement_Mysqli($db, $sql);
If you are using tableGateway, you can run your raw SQL query using this statement,
$this->tableGateway->getAdapter()->driver->getConnection()->execute($sql);
where $sql pertains to your raw query. This can be useful for queries that do not have native ZF2 counterpart like TRUNCATE / INSERT SELECT statements.
You can use the same query in Zend format as
$select = db->select()->from(array('t' => 'testTable'))
->$where= $this->getAdapter()->quoteInto('myColumn = ?', $s);
$stmt = $select->query();
$result = $stmt->fetchAll();
Here is an example for ZF1:
$db =Zend_Db_Table_Abstract::getDefaultAdapter();
$sql = "select * from user"
$stmt = $db->query($sql);
$users = $stmt->fetchAll();
Related
i'm trying to retrieve info from my database using PDO.
The code i'm using is
$input = $_GET['input'];
$inputvalue = $_GET['inputvalue'];
$db = DB::get_instance();
$query = $db->prepare('SELECT * FROM hwidex7 WHERE :input=:inputvalue');
$query->bindParam(':inputvalue', $inputvalue);
$query->bindParam(':input', $input);
$query->execute();
You can't bind table or column as parameter in PDO
You can build your query as
$query = $db->prepare("SELECT * FROM hwidex7 WHERE `$input` =:inputvalue");
$query->bindParam(':inputvalue', $inputvalue);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
print_r($result);
Both ways are wrong.
SELECT * FROM hwidex7 WHERE `HWID`='3087793810'
Just try above query.
You will get Idea for same.
Lets say I have the following variable:
$where = "where `hats`='red'";
I want to inject this variable into a PDO statement. What is the proper way of doing this?
Is it like so?:
$sql = "select * from `clothing` :where";
$stm = $this->app->db->prepare($sql);
$stm->bindParam(':where', $where);
$stm->execute();
Any help would be greatly appreciated.
You can only bind values, not keywords, object names or syntactic elements. E.g., if you're always querying according to hats, you could bind the 'red' value:
$color = 'red';
$sql = "select * from `clothing` where hats = :color";
$stm = $this->app->db->prepare($sql);
$stm->bindParam(':color', $color);
$stm->execute();
If your where clause is really that dynamic, you'd have to resort to string manipulation (and face the risk of SQL injection, unfortunately):
$where = "where `hats`='red'";
$sql = "select * from `clothing` $where";
$stm = $this->app->db->prepare($sql);
$stm->execute();
// create a new PDO object by name $PDO in your connection file
In your function
function nameOfFunction($var,$value)
{
global $PDO;
$st=$PDO->prepare('SELECT * from clothing WHERE ? = ?');
$rs=$st->execute(array($var,$val));
return $st->fetchAll();
}
I hope it will work. It will return the array, Traverse it as you like
I'm sorry if this is a duplicate question but I don't know how to solve my problem. Every time I try to correct my error I fail. My code is:
if (isset($_GET["comment"])) {$id = $_GET["comment"];}
$query = "SELECT * FROM posts WHERE id = {$id['$id']};";
$get_comment = mysqli_query($con, $query);
Can anybody correct the code to not show an error anymore and tell me what did I wrong?
Try this:
$id = isset($_GET['comment']) ? $_GET['comment'] : 0;
$query = "SELECT * FROM `posts` WHERE `id` = " . intval($id);
The use of intval will protect you from SQL injection in this particular case. Ideally, you should learn PDO as it is extremely powerful and makes prepared statements much easier to handle to prevent all injections.
An example using PDO might look like:
$id = isset($_GET['comment']) ? $_GET['comment'] : 0;
$query = $pdo->prepare("SELECT * FROM `posts` WHERE `id` = :id");
$query->execute(array("id"=>$id));
$result = $query->fetch(PDO::FETCH_ASSOC); // for a single row
// $results = $query->fetchAll(PDO::FETCH_ASSOC); // for multiple rows
var_dump($result);
First of all you should prevent injestion.
if (isset($_GET["comment"])){
$id = (int)$_GET["comment"];
}
Notice, $id contanis int.
$query = "SELECT * FROM posts WHERE id = {$id}";
Assuming your $id is an integer and you only want to make the query if it is set, here's how you could do it using prepared statements, which protect you from MYSQL injection attacks:
if (isset($_GET["comment"])) {
$id = $_GET["comment"];
$stmt = mysqli_prepare($con, "SELECT * FROM posts WHERE id = ?");
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $get_comment);
while (mysqli_stmt_fetch($stmt)) {
// use $get_comment
}
mysqli_stmt_close($stmt);
}
Most of these functions return a boolean indicating whether they were successful or not, so you might want to check their return values.
This approach looks a lot more heavy duty and is arguably overkill for a simple case of a statement containing a single integer but it's a good practice to get into.
You might want to look at the object-oriented style of mysqli which you might find a little cleaner-looking, or alternatively consider using PDO.
This is my first time using symfony 2. For database integration i am thinking of using propel as I doctrine and annotations seems really difficult for me. But it seems to me that to make a query you have to use propels own functions. I have used codeigniter. In codeigniter I used to send query string and it used to send me data. Is there something similar in propel symfony 2?
Like -
$query = 'select * from table where column1 natural join column2';
$this->db->query($query);
You should look at docs of sf2:
http://symfony.com/doc/current/book/propel.html
If you want to use raw SQL:
$em = $this->getDoctrine()->getEntityManager();
$connection = $em->getConnection();
$statement = $connection->prepare("SELECT something FROM somethingelse");
$statement->execute();
$results = $statement->fetchAll();
Or "propel way":
$connection = Propel::getConnection();
$query = 'SELECT MAX(?) AS max FROM ?';
$statement = $connection->prepareStatement($query);
$statement->setString(1, ArticlePeer::CREATED_AT);
$statement->setString(2, ArticlePeer::TABLE_NAME);
$resultset = $statement->executeQuery();
$resultset->next();
$max = $resultset->getInt('max');
Does $this-db->query() have mysql injection protection? I was wondering because I use this in instances and have not done anything to protect against sql injection.
The ActiveRecord style of querying with CodeIgniter escapes parameters, but not query().
You can use active record in this manner:
$someAge = 25;
$this->db->select('names, age');
$query = $this->db->get_where('people', array('age' => '>' . $someAge));
Read more about it here: https://www.codeigniter.com/userguide2/database/active_record.html
No, db->query() is not SQL Injection protected by default, you got few options.
Use Query Bindings
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));
For more complex quires where you have to build the query as you go on, use compile_bind() to get chunk of SQL.
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$safe_sql = $this->db->compile_bind($sql, array(3, 'live', 'Rick'));
etc.
Or use escape $this->db->escape() on parameters
$sql = "INSERT INTO table (title) VALUES(".$this->db->escape($title).")";
It's always best practise to use form validation first and include things like xss_clear, max_length etc either way in combination with one of the above.
you can use query bindings.
Example from CI 3 user guide:
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));