PDO::exec() expects parameter 1 to be string, object given - php

This is the code that makes the error:
$sql = 'INSERT INTO pedidos (pagado, instalado) VALUES ("'.$_POST['email'].'", "'.$_POST['b'].'") WHERE email="'.$_POST['2'].'"';
$stm = $conn->prepare($sql);
$conn->exec($stm);

That's not the proper way to use prepare and execute. The reason this was created was so that you wouldn't need to put logic and data together and put yourself at risk of an SQL injection attack.
$sql = 'INSERT INTO pedidos (pagado, instalado) VALUES (:pagado, :instalado)';
$stm = $conn->prepare($sql);
$stm->bindParam(':pagado', $_POST['email']);
$stm->bindParam(':instalado', $_POST['b']);
$stm->execute();
It also doesn't make sense to put a WHERE in an INSERT query. You're inserting into your table, you're not getting data.
However, if you're updating data based on other data, then you should use an UPDATE query.
UPDATE pedidos SET pagado=?, instalado=? WHERE email=?
An example of this would be:
$sql = 'UPDATE pedidos SET pagado=:padago, instalado=:instalado WHERE email=:email';
$stm = $conn->prepare($sql);
$stm->bindParam(':pagado', $_POST['email']);
$stm->bindParam(':instalado', $_POST['b']);
$stm->bindParam(':email', $_POST['2']);
$stm->execute();

UPDATE - 2:
$sql = 'INSERT INTO pedidos SET pagado = ?, instalado = ? WHERE email = ?';
$stm = $conn->prepare($sql);
$stm->bindParam(1,$_POST['email']);
$stm->bindParam(2,$_POST['b'] );
$stm->bindParam(3,$_POST['2'] );
$stm->execute(); // here your code generate error
Reason: You put $stm in execute() , which makes an error.

Related

Using a query result in another query

This is my first query, i want to use the multiple itemID's extracted for another query.
$conn = new mysqli(server, dbuser, dbpw, db);
$email = $_GET['email'];
$querystring = "SELECT itemID from mycart where email = '".$email."' ";
$result = $conn->query($querystring);
$rs = $result->fetch_array(MYSQLI_ASSOC);
The second query that need
$query = "SELECT * from CatalogueItems where itemID = '".$itemID."'";
How do i make these 2 query run?
Firstly, Your code is open to SQL injection related attacks. Please learn to use Prepared Statements
Now, from a query point of view, you can rather utilize JOIN to make this into a single query:
SELECT ci.*
FROM CatalogueItems AS ci
JOIN mycart AS mc ON mc.itemID = ci.itemID
WHERE mc.email = $email /* $email is the input filter for email */
PHP code utilizing Prepared Statements of MySQLi library would look as follows:
$conn = new mysqli(server, dbuser, dbpw, db);
$email = $_GET['email'];
$querystring = "SELECT ci.*
FROM CatalogueItems AS ci
JOIN mycart AS mc ON mc.itemID = ci.itemID
WHERE mc.email = ?"; // ? is the placeholder for email input
// Prepare the statement
$stmt = $conn->prepare($querystring);
// Bind the input parameters
$stmt->bind_param('s', $email); // 's' represents string input type for email
// execute the query
$stmt->execute();
// fetch the results
$result = $stmt->get_result();
$rs = $result->fetch_array(MYSQLI_ASSOC);
// Eventually dont forget to close the statement
// Unless you have a similar query to be executed, for eg, inside a loop
$stmt->close();
Refer to the first query as a subquery in the second:
$query = "SELECT * from CatalogueItems WHERE itemID IN ";
$query .= "(" . $querystring . ")";
This is preferable to your current approach, because we only need to make one single trip to the database.
Note that you should ideally be using prepared statements here. So your first query might look like:
$stmt = $conn->prepare("SELECT itemID from mycart where email = ?");
$stmt->bind_param("s", $email);
This creates a variable out of your result
$query = "SELECT itemID FROM mycart WHERE email = :email";
$stm = $conn->prepare($query);
$stm->bindParam(':email', $email, PDO::PARAM_STR, 20);
$stm->execute();
$result = $stm->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $pers) {
$itemID = $pers->itemID;
}

Combining two prepared statements not working

First, according to another SO post, I tried combining the two statements into one.
<?php
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
$sql = "UPDATE users SET pass = :password WHERE usrn = :id;
SELECT prim FROM users WHERE usrn = :id;";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->bindParam(":password", password_hash($_POST["password"], PASSWORD_DEFAULT));
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC); //// line 71
?>
However, this kept throwing the error: Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error on line 71.
I couldn't find any relevant solutions to this issue, so I decided to simply split up the two statements.
<?php
$sql = "UPDATE users SET pass = :password WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->bindParam(":password", password_hash($_POST["password"], PASSWORD_DEFAULT));
$stmt->execute();
$sql = "SELECT prim FROM users WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION["session"] = $result["prim"];
?>
But a var_dump($result) is returning Bool(false), so obviously something is not working right with fetching the result and storing it as a variable, it seems, in both cases.
I'm new to PHP and MySQL, so I'm at a loss right now.
Change this,
$sql = "SELECT prim FROM users WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION["session"] = $result["prim"];
To this,
$sql = "SELECT prim FROM users WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->execute(); // Your problem
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION["session"] = $result["prim"];
You are missing the execution of the query.

SQL insert into select issue

So i think i'm close to figuring this out but my query won't add the item from the "pending" table to the "items" table. can you guys help me out with this please. Also if i want it to delete after it gets added should i add the code below the INSERT INTO SELECT query? thanks
action.php:
$sql = "INSERT INTO items (photo,title,description, name) SELECT (photo,title,description, name) FROM pending";
$stmt = $conn->prepare($sql);
$stmt->execute();
Example for delete query after it takes the item from the "pending" into items:
$idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT);
//try deleting record using the record ID we received from POST
$sql = "DELETE FROM pending WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $idToDelete, PDO::PARAM_INT);
$stmt->execute();
I think you are leaving yourself open to mistakes doing it this way.
Consider what would happen if a new row is added to the pending queue after you have issued the INSERT SELECT but before you have started your delete.
I think you need to do this in a more controlled way inside a single loop to make sure you are only deleting what you have copied from pending into items.
$sql = "SELECT photo,title,description, name FROM pending";
$select_pending = $conn->prepare($sql);
$select_pending->execute();
$sql = "INSERT INTO items (photo,title,description, name)
VALUES (:photo,:title,:description, :name)";
$insert_items = $conn->prepare($sql);
$sql = "DELETE FROM pending WHERE id = :id";
$delete_pending = $conn->prepare($sql);
// only if you are using INNODB databases.
//$conn->beginTransaction();
while( $row = $select_pending->fetch_object() ) {
$insert_items->bindParam(':photo', $row->photo, PDO::PARAM_STR);
$insert_items->bindParam(':title', $row->title, PDO::PARAM_STR);
$insert_items->bindParam(':description', $row->description, PDO::PARAM_STR);
$insert_items->bindParam(':name', $row->name, PDO::PARAM_STR);
$insert_items->execute();
$delete_pending->bind_param(':id', $row->id, PDO::PARAM_INT);
$delete_pending->execute();
}
// only if you are using INNODB databases.
//$conn->commit();
$sql = "INSERT INTO items (photo,title,description, name)
SELECT photo,title,description, name FROM pending";
remove the () in the SELECT statement.

Insert Data in Oracle DB using PHP

Inserting data in oracle DB using oci_8. Sample query to insert string with special characters or quotes
update TABLENAME set COMMENTS = 'As per Mark's email dated 28-Feb-2015 - Bill Gates & Team's effort' where ID = 99;
To insert/update
$query = 'update TABLENAME set COMMENTS = '$_POST[comments]';
$result = customexecute($new_query);
public function customexecute($query)
{
$resutlt = parent::customquery($query);
return $resutlt;
}
public static function customquery($query)
{
try{
$stmt = oci_parse($conn, $query);
oci_execute($stmt,OCI_COMMIT_ON_SUCCESS);
oci_commit(db_singleton::getInstance());
oci_free_statement($stmt);
}catch (Exception $e)
{
print_r($e);
}
}
Executing it on ORACLE DB it says SQl command not properly ended. Looked into Parameterized queries mentioned here but not able to integrate it succesfully.
$query = 'UPDATE tablename SET field = :field WHERE id = :id';
$stmt = oci_parse($oracleConnection, $query);
oci_bind_by_name($stmt, ':field', "The field value with 'apostrophes' and so");
oci_bind_by_name($stmt, ':id', '125');
$result = oci_execute($stmt);
I can pass :bind_comments in my query which is in my controller. But $stmt resides in my db_singleton file (general for all DB queries) and can not pass seperately for a individual query.
How can I sanitize user input or do not allow data to be used in creating SQL code
From the update function, pass everything needed to the execute function:
$result = customExecute(
'update xxx set comments=:COMMENTS where id=:ID',
[
':COMMENTS' => $_POST['comment'],
':ID' => 99
]
);
Then in the execute function simply iterate the array to bind all params:
public static function customExecute($sql, array $params = [])
{
$stmt = oci_parse($conn, $sql);
foreach ($params as $key => &$value) {
oci_bind_by_name($stmt, $key, $value);
}
$result = oci_execute($stmt);
...
}
No, unsurprisingly, MySQL functions won't work with Oracle DB :)
You need to parameterise things, e.g.:
$query = 'update TABLENAME set COMMENTS = :bind_comments where id = :bind_id';
$stmt = $dbh->prepare($query);
$stmt->bindParam(':bind_comments', $_POST['comments']);
$stmt->bindParam(':bind_id', $_POST['id']);
$stmt->execute();
The correct way of using the OCI8 PHP extensions is:
$query = 'UPDATE tablename SET field = :field WHERE id = :id';
$stmt = oci_parse($oracleConnection, $query);
oci_bind_by_name($stmt, ':field', "The field value with 'apostrophes' and so");
oci_bind_by_name($stmt, ':id', '125');
$result = oci_execute($stmt);
More information: http://php.net/manual/book.oci8.php

How can I properly use a PDO object for a parameterized SELECT query

I've tried following the PHP.net instructions for doing SELECT queries but I am not sure the best way to go about doing this.
I would like to use a parameterized SELECT query, if possible, to return the ID in a table where the name field matches the parameter. This should return one ID because it will be unique.
I would then like to use that ID for an INSERT into another table, so I will need to determine if it was successful or not.
I also read that you can prepare the queries for reuse but I wasn't sure how this helps.
You select data like this:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
You insert in the same way:
$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));
I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db object:
$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well.
$nametosearch = "Tobias";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name");
$sth->bindParam(':name', $nametosearch);
// Or sth->bindParam(':name', $_POST['namefromform']); depending on application
$sth->execute();
You can use the bindParam or bindValue methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
A litle bit complete answer is here with all ready for use:
$sql = "SELECT `username` FROM `users` WHERE `id` = :id";
$q = $dbh->prepare($sql);
$q->execute(array(':id' => "4"));
$done= $q->fetch();
echo $done[0];
Here $dbh is PDO db connecter, and based on id from table users we've get the username using fetch();
I hope this help someone, Enjoy!
Method 1:USE PDO query method
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Getting Row Count
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
Method 2: Statements With Parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Method 3:Bind parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
**bind with named parameters**
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
or
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->execute(array(':name' => $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Want to know more look at this link
if you are using inline coding in single page and not using oops than go with this full example, it will sure help
//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw);
//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";
//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);
//view the entire array (for testing)
print_r($result);
//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}

Categories