Reccently I have been attempting to insert an array into a database, I keep getting the error message "Notice: Array to string conversion", I not really sure how to resolve this issue, any advice would be greatly appreciated
<?php
try{
$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$db ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
echo $e->getMessage();
die();
}
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$sort = $_POST['sort'];
$count = $_POST["count"];
$error = $_POST["error"];
$audit = array( ':sort' => $sort,
':count' => $count,
':error' => $error
);
foreach($audit as $completeAudit => $display) {
//print_r($display);
$sql = implode("INSERT INTO `audits` (`sort`, `count`, `error`, `timeentered`) VALUES ('$sort','$count','$error', NOW())");
}
$query = $db->prepare($sql);
$query->execute(array(
':sort' => $sort,
':count' => $count,
':error' => $error
));
}
EDIT
$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$db ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$sql = "INSERT INTO `audits` (`sort`, `count`, `error`, `timeentered`) VALUES (?,?,?, NOW())";
$stmt = $db->prepare($sql);
$query->execute(array($_POST['sort'], $_POST["count"], $_POST["error"]));
}
This is how it looks now, I deleted everything and used code supplied below
The problem is probably with the implode() call. It requires an array as parameter but you're passing a string.
However, you're overriding the $sql variable in every iteration inside the loop so I'm not sure what it's supposed to do.
Last thing, your code is subject to SQL inejctions so have a look at using prepared statements.
this error has nothing to do with PDO - it's just basic PHP syntax.
However, your PDO is wrong as well. Here is the proper code:
$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$db ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$sql = "INSERT INTO `audits` (`sort`, `count`, `error`, `timeentered`) VALUES (?,?,?, NOW())");
$stmt = $db->prepare($sql);
$stmt->execute(array($_POST['sort'], $_POST["count"], $_POST["error"]));
}
Related
I looked all over for solutions but couldn't find any. I checked my code and can't seem to find any errors with it.
try
{
$handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD);
$handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (Exception $e)
{
trigger_error($e->getMessage(), E_USER_ERROR);
exit;
}
$sendData = $handle->prepare("INSERT INTO 'posts' (body, user, comments, likes, username, datetime) VALUES(:body, :userid, 'none', 'none', :username, :datetime)");
$sendData->bindParam(':body',$this->body);
$sendData->bindParam(':userid',$this->userID);
$sendData->bindParam(':username',$this->username);
$sendData->bindParam(':datetime',$this->datetime);
$sendData->execute();
I determined that the code stops before it even reaches the "bindParam" part. It stops right after the prepare call.
EDIT: As it turns out the error was in the $handle part. I declared handle elsewhere and didn't use "global" to add it inside this function. I feel so stupid.
Try:
try {
$db = new PDO('mysql:host=localhost;dbname=DATEBASE;charset=utf8', 'USER', 'PASSWORD');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex) {
echo "something";
die();
}
$body = $_POST['body'];
$userID = $_POST['userID'];
$username = $_POST['username'];
$datetime = $_POST['datetime'];
$none = "none";
$sendData = $sb->prepare("INSERT INTO `posts` (body, user, comments, likes, username, datetime) VALUES(:body, :userid, :none, :none, :username, :datetime)");
$sendData->bindValue(':body', $body);
$sendData->bindValue(':none', $none);
$sendData->bindValue(':userid', $userID);
$sendData->bindValue(':username', $username);
$sendData->bidnValue(':datetime', $datetime);
$sendData->execute();
Edited:
`posts` instead 'posts'
mysql_connect('localhost', 'root', '')
or die(mysql_error());
mysql_select_db('shuttle_service_system')
or die(mysql_error());
$insert="INSERT INTO inactive (ID_No, User_Password, First_Name, Last_Name, Email, Contact_Number)
VALUES('". $ID_No ."','". $UserPassword ."','". $FirstName ."','". $LastName ."','". $Email ."','". $ContactNumber ."')";
$result=mysql_query($insert);
$sql="DELETE FROM users WHERE ID_No = '$ID_No'";
$result2=mysql_query($sql);
if($result && $result2){
echo"Successful!";
} else {
echo "  Error";
}
Hi guys I have been stuck in delete function of MySQL, I have tried searching the net but when I ran my code it always goes to the else part which means there is an error, the insert is already okay but the delete is not.
PHP variables are allowed in double quotes. Hence try this,
$sql="DELETE FROM users WHERE ID_No = $ID_No";
Your first query was not properly escaped. Rewrite like
$insert="INSERT INTO inactive (`ID_No`, `User_Password`, `First_Name`, `Last_Name`, `Email`, `Contact_Number`)
VALUES('$ID_No','$UserPassword','$FirstName','$LastName','$Email','$ContactNumber')";
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
First, use PDO.
Make your connection Database like this:
function connectToDB(){
$host='localhost';
try {
$user = 'username';
$pass = 'password';
$bdd = 'databaseName';
$dns = 'mysql:host='.$host.';dbname='.$bdd.'';
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
return $connexion = new PDO($dns, $user, $pass, $options);
}catch ( Exception $e ) {
echo "Fail to connect: ", $e->getMessage();
die();
}
}
To delete something, here is an example:
function deleteUserWithId($ID_No){
$connexion = connectToDB();
try{
$connexion->exec('DELETE FROM users WHERE ID_No = '.$ID_No);
}catch(Exception $e){
echo "Error: ".$e->getMessage();
}
}
To insert something:
function addInactiveUser($UserPassword,$FirstName ,$LastName ,$Email,$ContactNumber){
$connexion = connectToDB();
$insert = $connexion->prepare('INSERT INTO inactive VALUES(:ID_No,
:User_Password,
:First_Name,
:Last_Name,
:Email,
:Contact_Number
)');
try {
// executing the request
$success = $insert->execute(array(
'ID_No'=>'',
'User_Password'=>$UserPassword,
'First_Name'=>$FirstName ,
'Last_Name'=>$LastName ,
'Email'=>$Email,
'Contact_Number'=>$ContactNumber
));
if($success)
// OK
else
// KO
}
catch (Exception $e){
echo "Error: ".$e->getMessage();
}
}
To make a select:
// If you want to display X user per pages for example
function getAllInactiveUsers($page, $numberInactiveUserPerPage){
$connexion = connectToDB();
$firstInactiveUser = ($page - 1) * $numberInactiveUserPerPage;
$selectAllInactiveUsers = $connexion->prepare('SELECT * FROM inactive ORDER BY ID_No DESC LIMIT '.$firstInactiveUser.','.$numberInactiveUserPerPage);
return $selectAllInactiveUsers ;
}
To get the results of this methods, just do something like this:
$inactiveUsers= getAllInactiveUsers(1,15); // for page 1, display 15 users
$inactiveUsers->execute();
while($row = $inactiveUsers->fetch(PDO::FETCH_OBJ)){
$id = $row->ID_No;
$first_name = $row->First_Name;
// etc...
}
Hope that's help :)
I am not sure if this helps you, but as an alternative you could delete the last entry in the table:
$delQ = mysql_query("SELECT * FROM ph ORDER BY id DESC LIMIT 1" );
while(( $ar = mysql_fetch_array($delQ)) !== false){
mysql_query("DELETE FROM ph WHERE id= $ar[id]");
}
I am trying to be as efficient with code as possible. Unfortunately, I can't seem to figure out a good way of doing this. I have tried using Sammitch's code which does look cleaner but unfortunately it doesn't seem to work.
I would like a way to stop having to use prepare, execute, every time and a function to me makes the most sense. Using Simmitch's suggestion, I removed the initial connection to database to stop unnecessary overheads but the code still does not work. Showing a "SQLSTATE[HY093]: Invalid parameter number: parameter was not defined" error.
My code at present (some parts omitted as not necessary):
/*Function to talk to database*/
function doQuery($myDB, $myQuery, $myValues)
{
try
{
$st = $myDB->prepare($myQuery);
$st->execute($myValues);
//echo $success;
}
catch (PDOException $e)
{
echo "Failed because: " . $e->getMessage();
}
}
$db = new PDO('mysql:host=localhost;dbname='dbanme';charset=utf8', 'dbuser', 'dbpass');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Set error mode
$query = "INSERT INTO users(login,pass,email,county) VALUES(:username,:password,:email,:count)";
$values = array('username' => $_POST['username'],
'password' => $_POST['password1'],
'email' => $_POST['email'],
'county' => $_POST['county']
);
doQuery($db, $query, $values);
<?php
function doQuery($db, $query, $arguments) {
try {
//Prepare and execute an insert into DB
$st = $db->prepare($query);
$st->execute(array($values));
echo $success; // 4. use echo
// you should probably return something here...
} catch (PDOException $e) {
// 5. Fail ~descriptively~
echo "Failed because: " . $e->getMessage();
// you should probably return something here...
}
}
// 1. Don't create the database inside of the same function that does the queries,
// creation/destruction of the objects/connections will cause unnecessary overhead,
$myDb = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'dbuser', 'dbpassword');
$myDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Set error mode
$myQuery = "INSERT INTO users(login,pass,email,county) VALUES(:username,:password,:email,:count)";
// 2. You can't define an array like that.
// 3. You do not need to add colons to the array indexes.
$myValues = array(
'username' => $_POST['username'],
'password' => $_POST['password1'],
'email' => $_POST['email'],
'county' => $_POST['county']
);
doquery($myDb, $myQuery, $myValues)
Don't forget to include " : " in your parameters array ?
/*Function to talk to database*/
function doQuery($myDB, $myQuery, $myValues)
{
try
{
$st = $myDB->prepare($myQuery);
$st->execute(array($myValues));
//echo $success;
}
catch (PDOException $e)
{
echo "Failed because: " . $e->getMessage();
}
}
$db = new PDO('mysql:host=localhost;dbname='dbanme';charset=utf8', 'dbuser', 'dbpass');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Set error mode
$query = "INSERT INTO users(login,pass,email,county) VALUES(:username,:password,:email,:count)";
$values = array(':username' => $_POST['username'],
':password' => $_POST['password1'],
':email' => $_POST['email'],
':county' => $_POST['county']
);
doQuery($db, $query, $values);
I hope this worked!
i want to get the current max size of my DB. I have found the statements an checked it out. It works fine in VS2012 SQL Explorer. But when im using php im geting no data.
This is my function:
function getLoad() {
$conn = connect();
$string = 'DATABASEPROPERTYEX ( 'database' , 'MaxSizeInBytes' )';
$stmt = $conn->query($string);
return $stmt->fetchAll(PDO::FETCH_NUM);
}
The problem is that i get an error in fetching the $stmt. Error is:
can not fetchAll(11)
This code will print the database edition and max size in GB:
<?php
function get_database_properties($server, $database, $username, $password) {
try {
$conn = new PDO ("sqlsrv:server=tcp:{$server}.database.windows.net,1433; Database={$database}", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(constant('PDO::SQLSRV_ATTR_DIRECT_QUERY'), true);
$query = "SELECT CONVERT(NVARCHAR(128), DATABASEPROPERTYEX ('{$database}', 'Edition')) as 'Edition', " .
"CONVERT(DECIMAL,DATABASEPROPERTYEX ('{$database}', 'MaxSizeInBytes'))/1024/1024/1024 AS 'MaxSizeInGB'";
$stmt = $conn->query($query);
$row = $stmt->fetch();
$conn = null;
return $row;
}
catch (Exception $e) {
die(print_r($e));
}
}
$db_properties = get_database_properties("yourserver", "yourdatabase", "youruser", "yourpassword");
print("Edition={$db_properties['Edition']} MaxSizeInGB={$db_properties['MaxSizeInGB']}\n");
?>
I'm pretty new in PHP coding, and I cannot find the error in the following code... could you help me please ?
Fatal error: Cannot use object of type PDOStatement as array in C:\wamp\www\membre\inscription_post.php on line 14 Call Stack # Time Memory Function Location 1 0.0006 682688 {main}( ) ..\inscription_post.php:0
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=test', 'root', '');
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
$mem = $bdd -> query('SELECT * FROM membres');
while ($data = $mem -> fetch())
{
if($mem['pseudo'] == $_POST['pseudo'])
{
echo "Pseudo existant";
}
else
{
$pass_hache = sha1($_POST['pass']);
$req = $bdd->prepare('INSERT INTO membres (pseudo, pass, email, date_inscription) VALUES(?, ?, ?, CURDATE())');
$req->execute(array($_POST['pseudo'], $pass_hache, $_POST['email']));
header('Location: inscription.php');
echo "Membre ajouté";
}
}
$mem -> closeCursor();
?>
membres table structure is the following
id(=INT, primary key),
pseudo (VARCHAR(255)),
pass (VARCHAR(255)),
date_inscription (date)
Thank you for your help
something like this
<?php
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$bdd = new PDO($dsn,'root','', $opt);
$stm = $bdd->prepare('SELECT 1 FROM membres WHERE pseudo=?');
$stm->execute(array($_POST['pseudo']));
$row = $stm->fetch();
if ($row) {
echo "Pseudo existant";
} else {
$pass_hache = sha1($_POST['pass']);
$sql = 'INSERT INTO membres VALUES(NULL, ?, ?, ?, CURDATE())';
$req = $bdd->prepare($sql);
$req->execute(array($_POST['pseudo'], $pass_hache, $_POST['email']));
header('Location: inscription.php');
}
insert query can be wrong, depends on the table schema
if($mem['pseudo'] == $_POST['pseudo'])
^^^--- should be $data instead
But this is bad code. You're basically buying up the entire contents of a grocery store (your members table), driving it all home, then throwing away everything EXCEPT the one chocolate bar you wanted. You should be doing this in the DB, essentially
SELECT * FROM members WHERE pseudo=...
if($mem['pseudo'] == $_POST['pseudo']) should be if($data['pseudo'] == $_POST['pseudo']) as you are reading each line from $mem as $data. However, this doesn't seem like the best option for doing what it looks like you are trying to do - why not search for $_POST['pseudo'] in the database directly instead of looping through them all?