print_r an insert statement php pdo - php

I'm using this method to insert data into my database:
function insertMenue($content, $date) {
$session = $_SESSION['aid'];
global $pdo;
$pdo->exec('SET CHARACTER SET utf8');
$query = $pdo->prepare('INSERT INTO menue(type, content, date, creator) VALUE (?,?,?,?)');
$query->bindValue(1, "menue");
$query->bindValue(2, "<p>" . $content . "</p>");
$query->bindValue(3, $date);
$query->bindValue(4, $session);
$query->execute();
}
I'm calling this method for every object in an array. Now every time when there should be a String which contains an umlaut (ä, ö, ü) the String gets cut off where the umlaut should be.
As for example I'm writing:
<p>Salat<br>Gemüse und Teigwaren</p>
The data in the database happens to be just:
<p>Salat<br>Gem
Now the question is:
How can I print_r() the whole sql statement?
print_r($query->execute());
Would display (1,1,1,1)
and I want something like:
(menue, (p)Salat(br)Gemüse und Teigwaren(/p), 2015-09-06, 2)
I'm not sure whether it doesn't get to the database or whether the database is the problem.
The db itself can handle umlaute and is written in utf-8. I dumped the file and took a closer look at it, it shouldn't be corrupted.

You cant see the full query, because it doesnt exist in the PHP side.
PHP first sends the query and then the parameters when using prepared statements
(Not sure what happens when the emulation mode is on though).
If you want to see the final query, you should enable your database's query log and check there.
This is the closest you can get with just PHP:
http://us2.php.net/manual/en/pdostatement.debugdumpparams.php

Try this...
function insertMenue($content, $date) {
$session = $_SESSION['aid'];
global $pdo;
$pdo->exec('SET CHARACTER SET utf8');
$params = ["menue", "<p>$content</p>", $date, $session];
// Check all your params are set...
// Although you may want to consider checking these before entering this block
print_r($params);
$sql = "INSERT INTO menue( type
, content
, date
, creator
)
VALUES( ?
, ?
, ?
, ?
)";
try {
$sth = $pdo->prepare($sql);
$sth->execute($params);
} catch (PDOException $e) {
throw new pdoDbException($e);
}
}

Related

PHP MYSQL -> UPDATE column with variable if that variable isn't null or empty

Sorry, but i'm new to PHP, so i will look like a noob.
As the title says, i made this method which updates user data:
function update($userid, $name){
Try{
$stmt=$this->db->prepare("UPDATE users
SET
name=:name,
WHERE userid=:userid");
$stmt->execute(array(':name'=>$name));
} Catch(PDOException $e){
echo $e->getMessage();
}
}
That code is working right, but i want to know if it's possible, the "name" column just update if the variable coming from:
$user->update($userid, $name);
From $name, is not null or not empty. If it's null or Empty, the MYSQL UPDATE function should not be done.
Try this instead.
function update($userid, $name) {
try {
if (!empty($name) and !empty($userid)) {
$stmt = $this->db->prepare("UPDATE users
SET
name=:name
WHERE userid=:userid");
$stmt->execute(array(':name' => $name, ':userid' => $userid));
}
}
Catch(PDOException $e) {
echo $e->getMessage();
}
}
Explanation
Removal of the trailing comma.
As stated by #Fred -ii- you had a trailing comma in your SQL query after the SET (i.e SET name=:name,).
The comma in SQL queries are used to separate multiple updates from one another so UPDATE table SET col1 = "val1", col2 = "val2" and so on. Since you are only updating one column, you don't need the comma
The empty method checks whether the variable $name has been set and is not false. See documentation.
Removed the SQL-Injection-Vulnerable in :userid=$userid
Why i think it is better to have an if-statement inside the function
A function should be reusable and it costs nothing to call a function
In clean code you should avoid using if-statements, which means, you should not always have surround an if-statment before calling a function which could be called in other parts of the code, too. What happens when you add another parameter?
I know this is discussable.

PHP PDO MSSQL Stored Procedure

I'm having problems trying to run a stored procedure on MSSQL2000 using PHP PDO. I've tried all the combinations, but cant get any results apart from Invalid cursor state error.
The procedure is inside a database that is used by another application. I'm just reaching inside it to pull information out to display on PHP. So modifying the stored procedure (even to instead that SET NOCOUNT ON) is a no-no.
The stored procedure takes two arguments - a start and end date. There is also a RETURN_VALUE parameter.
I can run the following command in the SQL Query Analyzer and dumps rows of data fine:
EXEC [availability_enquiry] '08-24-2015 0:0:0.000', '08-26-2015 0:0:0.000'
Seems pretty straight forward, but when I try to code it and run it, I get nothin:
$dbConn = null;
$connectionString = sprintf('%s:Driver=%s;Server=%s;Database=%s;TrustedConnection=yes;', 'odbc', '{SQL Server Native Client 10.0}', 'mypc', 'testdb');
$dbConn = new PDO($connectionString, 'root', '123qew');
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "EXEC [availability_enquiry] '08-24-2015 0:0:0.000', '08-26-2015 0:0:0.000'";
$stmt = $dbConn->query($sql, PDO::FETCH_ASSOC);
$data = $stmt->fetch();
print_r($data);
I get an PDO Expection: 'Invalid cursor state' on the $stmt->fetch() line.
$stmt = $dbConn->prepare($sql);
$stmt->execute();
$data = $stmt->fetch();
print_r($data);
Still get an PDO Expection: 'Invalid cursor state'. Must be something to do with the fetch. Try something else:
$data = array();
do {
$results[count($results)] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
while($stmt->nextRowset());
Still nothing!? Any ideas?
UPDATE1:
Tried another method:
$sql = "{CALL availability_enquiry (:startdate, :enddate)}";
$stmt = $dbConn->prepare($sql);
$startdate = "2015-08-24T00:00:00";
$enddate = "2015-08-26T00:00:00";
$stmt->execute(array(
':startdate'=>$startdate,
':enddate'=>$enddate
));
$data = $stmt->fetch();
print_r($data);
Also tried it as:
$startdate = "2015-08-24T00:00:00";
$stmt->bindParam(':startdate', $startdate, PDO::PARAM_STR);
$enddate = "2015-08-26T00:00:00";
$stmt->bindParam(':enddate', $enddate, PDO::PARAM_STR);
$stmt->execute();
But both give me an 'Invalid character value for cast specification' error message. Tried it with my own and the newly suggested date format.
If I use the same format of the date that is inside the table that the stored procedure uses:
$startdate = "2015-08-11 09:42:18.890";
I get an 'Invalid cursor state' error message. I'm hoping this is one step closer?

Insert a lot of record using single arguments and using bindParam

I have some method to insert some data into a database like this:
public function register($username, $email, $hashedPassword, $activationCode)
{
try {
$conn = Database::getConnection();
// Connect and create the PDO object
$conn->exec('SET CHARACTER SET utf8'); // Sets encoding UTF-8
// Define and prepare an INSERT statement
$sql = 'INSERT INTO users (username, email, pass, reset_token, dateAdded )
VALUES (:username, :pass, :email, :token, now())';
$sqlprep = $conn->prepare($sql);
// Adds value with bindParam
$sqlprep->bindParam(':username', $username, PDO::PARAM_STR);
$sqlprep->bindParam(':email', $email, PDO::PARAM_STR);
$sqlprep->bindParam(':pass', $hashedPassword);
$sqlprep->bindParam(':token', $activationCode);
// If the query is successfully executed, output the value of the last insert id
if ($sqlprep->execute()) {
//echo 'Succesfully added the row with id='. $conn->lastInsertId();
$this->result = true;
}
$conn = null; // Disconnect
} catch (PDOException $e) {
include('../views/error.php');
include('../views/admin/includes/footer.php');
exit();
}
}
The problem is I think it's not a good method if I have so many arguments for my function to enter into a database. So is it any good way I can enter a lot of fields just by using 1 parameter but still using bindParam? Since I see a lot of examples is only using prepare without bindParam. I think I can use an array, but I don't know the proper way to do it. So I need some help how I can do it.
since you want keep your bindparam i suggest you use input like this:
$input = array('username' => $username, 'activationHash' => $activationHash);
and in your bindParam add a code like this:
public function register($input){
//code
$sqlprep->bindParam(':username', $input['username'], PDO::PARAM_STR);
//other
}
hope this will solve your problem
https://stackoverflow.com/a/10060755/1747411
Check second example, you have to repeat values with binds
e.g
VALUES (:username1, :pass1, :email1, :token1, now()), (:username2, :pass2, :email2, :token2, now())
and bindParam with loop
You can insert the params as an array into $sqlprep->execute($param_array)
Or, simply passing each param into an array inside execute, like this: $sqlprep->execute(array($param1, $param2))
Update:
Pass values into $input as an array:
$input = array('username' => $username, 'activationHash' => $activationHash); //and so on
Now on the model side,
You can bind these values to params using foreach loop like this:
foreach ($values as $key => $value) {
$sqlprep->bindParam(':' . $key, $value , PDO::PARAM_STR);
}

php pdo prepared statment and transitions

I am trying to write a function that is supposed to receive any MySQL statement and apply it,
The basic idea is not to repeat needed code to write to Database, well what is needed to connect to Database is creating new PDO object, starting a transaction and preparing a statement, binding values to it, executing it,
so every time I want to access the Database I don't have to repeat these steps,
Here is a function that does that :
==============================================================================================
protected function applyQuery($statement, $bindparameters , &$values , $selectStatement, &$result){
try{
$dbh = DataBase::setConnection();// new PDO("MySQL= .....");
$dbh->beginTransaction();
$stmt = $dbh->prepare($statement);
if($bindparameters == true){
foreach($values as $key => $value){
$stmt->bindValue($key, $value);
}
}
$stmt->execute();
$dbh->commit();
if($selectStatement == TRUE){
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}catch (PDOException $e){
$dbh->rollBack();
throw DataBase::$Errors[0];
}
}
============================================================================================
$statement = the desired statement (e.g 'SELECT * from users WHERE username = :username')///
$bindparameters = do we need to bind values (in this examples yes) so its value TRUE///
&$values = array by reference in this case equals = (':username' => 'User');///
$selectStatement = tells if using SELECT in statement ,in this case TRUE///
$result = array by reference in this case the final fetch result will be stored in it///
so in this example we get the following call to the function :
applyQuery('SELECT * from users WHERE username = :username', TRUE ,array(':username' => 'User') , TRUE , result )
My question is : will this code work ?
is the logical sequence of what it does and should do make sense ?
whats the difference between $stmt->execute and $dbh->commit ?
is omitting any line will cause failure to achieve the desired result
Please understand that I did lookup what is PDO and read a lot but unable to answer these questions!

Inserting data to MySQL via PDO, trying to include a timestamp along with data using an array - getting errors?

I have a set of data stored in variables, and I want a page to write that data to a MySQL database, I'd like to include the time of insertion, here's my method:
$username="username"; $password="password";
try {
$pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('INSERT INTO table01
(
Time,
variable1,
variable2,
)
VALUES
(
:Time,
:variable1,
:variable2,
)');
$stmt->execute(array(
':Time' => NOW(),
':variable1' => $var1,
':variable2' => $var2,
));
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
On loading this page, the css is stripped from the page, I get a sort of garbled output of what the page should look like (white screen, plain text some images), additionally on checking the database nothing has been written to it.
Without the Time variable in there, all works perfectly.
Any advice? Thanks in advance
Sorry, took me moment to re-read that. You are using the nysql function now() to do the work, and as such you don't need to set it as a param and therefore don't need to bind it at all. Just write it into your query.
$stmt = $pdo->prepare('INSERT INTO table01
(
Time,
variable1,
variable2,
)
VALUES
(
now(),
:variable1,
:variable2,
)');
$stmt->execute(array(
':variable1' => $var1,
':variable2' => $var2,
));
Edit Re Comment
The : in a query denotes it as a parameter in a prepared query. That means you must then bind it via the bind() command. However if you are inserting the data from within the database (such as using a built in function, or pulling the data in from another row) you don't need to declare it in the initial query with : and therefore you can't pass it to the query in the bound params array.

Categories