I was using PHP 5.6 and mysql 5.5, I updated to mysql 5.7 and php 7 for better speed (cause I heard php 7 is really faster than 5.6).
So I had this database function to insert my news rows on any table of my database.
public function create() {
global $database;
$attributes = $this -> sanitized_attributes();
$sql = "INSERT INTO " . static::$table_name . " (";
$sql.= join(", ",array_keys($attributes));
$sql.= ") VALUES ('";
$sql.= join("', '",array_values($attributes));
$sql.= "')";
if ( $database -> query($sql) ) {
$this -> id = $database -> insert_id();
return true;
} else {
return false;
} // END - if ( $database -> query($sql) )
} // END - public function create()
now that I made the update and I try to check where the code is broken, I realized that I cannot enter any new row in any table.
I receive this error when I try to create a new row to any table:
Database Query failed: Incorrect integer value: '' for column 'id' at
row 1
I somehow know where the problem is, my first cell on any table is an integer ID that is set to AUTO INCREMENT .. the problem at the function above is at this line I think:
$sql.= join("', '",array_values($attributes));
this first value is always an integer and PHP 7 and MYSQL 5.7 want the value withOUT the quotes. Thats what I realized .. when I was using the old PHP 5.3 - 5.6, the same database function never had a problem ..
Any solution how to fix this DATABASE function so I can escape the quotes just for the INTEGER VALUES and let the QUOTES for the STRING VALUES .. ???
Related
I've come across with a problem. My framework was working just fine with PHP 5.3.0. I upgraded my PHP version to PHP 5.4.x and I started to have few issues with some parts of my framework.
After PHP version upgrade, PDO lastInsterId() always returns 0.
I have auto-increment field called id.
It is adding the data to database without any problems.
For some reason I keep getting 0 as last insert id.
Here is my code;
databaseobjects.php
public static function create () {
global $db;
$attributes = self::sanitize(static::$fields);
$sql = "INSERT INTO ".PREFIX.static::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUE (:";
$sql .= join(", :", array_keys($attributes));
$sql .= ")";
return ($db->crudQuery($sql, $attributes)) ? true : false;
}
public static function lastInsertID () {
global $db;
return $db->handler->lastInsertId();
}
database.php
public function crudQuery($sql, $data) {
$sth = $this->handler->prepare($sql);
return $sth->execute($data);
}
First create() method is called, then crudQuery() method is called.
As I mentioned before, I can add the data successfully to MySQL database.
Unfortunately when I call lastInsterID() method, it always returns 0.
I will be really glad if you can help me out with this problem before I will get the last ID with SQL Query (:
Other than a bug in php/PDO or your framework, there are two possibilities. Either lastInsertId() is called on a different MySQL connection than the insert, or you are generating the id in your application/framework and inserting it, rather than letting auto_increment generate it for you. Which column in the table is the primary key/auto_increment? Is that column included in $attributes in your create() function?
You can test PDO to make sure that part is working correctly with this code (in a new file):
// Replace the database connection information, username and password with your own.
$conn = new PDO('mysql:dbname=test;host=127.0.0.1', 'user', 'password');
$conn->exec('CREATE TABLE testIncrement ' .
'(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50))');
$sth = $conn->prepare('INSERT INTO testIncrement (name) VALUES (:name)');
$sth->execute([':name' => 'foo']);
var_dump($conn->lastInsertId());
$conn->exec('DROP TABLE testIncrement');
When I ran this script, the output was
string(1) "1"
After you commit a transaction PDO::lastInsertID() will return 0, so best to call this method before the transaction is committed.
The one other problem could be using $pdo->exec($sql) instead of $pdo->query($sql).
exec($sql) will return always 0 when you use $pdo->lastInsertId(). So use query() instead.
I got a 0 when the last insert statement failed due to a foreign key contraint. last_error was a string.
When no exception is thrown, lastInsertId returns 0. However, if lastInsertId is called before calling commit, the right id is returned.
http://php.net/manual/es/pdo.lastinsertid.php
I want insert record into database using
I have 3 files
config.php (For database connection )
function.php (It's for create function of CRUD)
emp.php (Hear i called function from functions.php)
1. config.php file
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password) ;
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$db =mysqli_select_db($conn,"test");
?>
2. function.php
<?php
include('config.php');
function addRecord($table,$columns,$val){
$insertQuery = "INSERT INTO ".$table." ($columns) VALUES('".$val."')";
return $insertQuery;
}
?>
3. emp.php
Hear i called addRecord function from function.php file for add record into database.
<?php
include('config.php');
include('function.php');
$columns= array('employee_name','employee_salary','employee_age');
$values =array('Jack','12000','15');
$val = "".implode("','", $values)."";
$col = "`".implode("`,`", $columns)."`";
addRecord('employee',$col,$val);
It's given me warning because of i passed NULL in $values array so during add record it's display Warning: Missing argument
Note: id is auto increment in DB
When i print query it's showing
INSERT INTO employee VALUES('Jack','12000','15');
And i used same query in mysql it's given error
#1136 - Column count doesn't match value count at row 1
Someone please help me where i need to change in my code.
Your functions are slightly off.
function addRecord($table,$coloumn,$values){
$insertQuery = "INSERT INTO ".$table." VALUES('".$values."')";
}
This does not return anything, also, the variable $coloumn is never used.
I cannot see where your actual mysql insert is happening, but as that function doesn't do anything except assign a string to a variable, it cannot do anything.
It's given me warning because of i passed NULL in $values array so during add record it's display
You are calling this function as addRecord('employee',$val);, and as you can see, you are passing $val where $coloumn should be, remove $coloumn from the function, and that warning will go away
Also
$columns= array('id','employee_name','employee_salary','employee_age');
$values =array(NULL,'Jack','12000','15');
should be
$columns= array('employee_name','employee_salary','employee_age');
$values =array('Jack','12000','15');
Then:
function addRecord($table,$values){
return "INSERT INTO ".$table." VALUES('".$values."')";
}
$addQuery = addRecord('employee',$val);
and use $addQuery in your statement.
1136 - Column count doesn't match value count at row 1
This is because you are not specifying which columns to insert, and MySQL knows that there are 4 columns, including the ID, and you are giving it three values.
Your query should be:
INSERT INTO employee (employee_name, employee_salary, employee_age) VALUES('Jack','12000','15');
Change :
$columns= array('id','employee_name','employee_salary','employee_age');
$values =array(NULL,'Jack','12000','15');
to
$columns= array('employee_name','employee_salary','employee_age');
$values =array('Jack','12000','15');
I have a database class as follows:
class Db
{
public $mysqli = null;
public function __construct($port = NULL)
{
include $_SERVER['DOCUMENT_ROOT'].'/php/'.'config.php';
if($port == NULL)
$port = ini_get('mysqli.default_port');
$this->mysqli = new mysqli(HOST, USER, PASS, DB, $port)
or die('There was a problem connecting to the database');
if ($this->mysqli->connect_errno) {
echo "Error MySQLi: ( " . $this->mysqli->connect_errno . ") " . $this->mysqli->connect_error;
exit();
}
$this->mysqli->set_charset("utf8");
}
All of which works fine, I've added this function:
public function insert($sql, $bind) {
$stmt = $this->mysqli->prepare($sql);
$stmt->bind_param('sssssss', $bind[0], $bind[1], $bind[2], $bind[3], $bind[4], $bind[5], $bind[6]);
$stmt->execute();
}
The problem of course, is that this isn't very dynamic. I may only have 2 things to bind, and they won't necessarily be strings.
So for example I do this:
$db = new Db();
$strings = array ($chosenImage, $id);
$db->insert("INSERT INTO Media VALUES (NULL, ?, ?)", $strings);
So this is only two binds.
My question then is two fold:
1) How do I best turn this function into one that assesses the array for type, and size in as clean a fashion as possible?
2) Further, with a similar function (lets call it recall) How would I use a select statement to return 2 items, and bind them for the return (assuming the amount that I want to return may change depending on the query
-1. Having distinct function for insert is quite wrong idea. One actually need only helper for SET statement, to create it dynamically. The rest have to be called using conventional query() function.
0. Types aren't that important, using s for everything is quite all right.
1. call_user_func_array()
2. get_result()
I've come across with a problem. My framework was working just fine with PHP 5.3.0. I upgraded my PHP version to PHP 5.4.x and I started to have few issues with some parts of my framework.
After PHP version upgrade, PDO lastInsterId() always returns 0.
I have auto-increment field called id.
It is adding the data to database without any problems.
For some reason I keep getting 0 as last insert id.
Here is my code;
databaseobjects.php
public static function create () {
global $db;
$attributes = self::sanitize(static::$fields);
$sql = "INSERT INTO ".PREFIX.static::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUE (:";
$sql .= join(", :", array_keys($attributes));
$sql .= ")";
return ($db->crudQuery($sql, $attributes)) ? true : false;
}
public static function lastInsertID () {
global $db;
return $db->handler->lastInsertId();
}
database.php
public function crudQuery($sql, $data) {
$sth = $this->handler->prepare($sql);
return $sth->execute($data);
}
First create() method is called, then crudQuery() method is called.
As I mentioned before, I can add the data successfully to MySQL database.
Unfortunately when I call lastInsterID() method, it always returns 0.
I will be really glad if you can help me out with this problem before I will get the last ID with SQL Query (:
Other than a bug in php/PDO or your framework, there are two possibilities. Either lastInsertId() is called on a different MySQL connection than the insert, or you are generating the id in your application/framework and inserting it, rather than letting auto_increment generate it for you. Which column in the table is the primary key/auto_increment? Is that column included in $attributes in your create() function?
You can test PDO to make sure that part is working correctly with this code (in a new file):
// Replace the database connection information, username and password with your own.
$conn = new PDO('mysql:dbname=test;host=127.0.0.1', 'user', 'password');
$conn->exec('CREATE TABLE testIncrement ' .
'(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50))');
$sth = $conn->prepare('INSERT INTO testIncrement (name) VALUES (:name)');
$sth->execute([':name' => 'foo']);
var_dump($conn->lastInsertId());
$conn->exec('DROP TABLE testIncrement');
When I ran this script, the output was
string(1) "1"
After you commit a transaction PDO::lastInsertID() will return 0, so best to call this method before the transaction is committed.
The one other problem could be using $pdo->exec($sql) instead of $pdo->query($sql).
exec($sql) will return always 0 when you use $pdo->lastInsertId(). So use query() instead.
I got a 0 when the last insert statement failed due to a foreign key contraint. last_error was a string.
When no exception is thrown, lastInsertId returns 0. However, if lastInsertId is called before calling commit, the right id is returned.
http://php.net/manual/es/pdo.lastinsertid.php
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 1 year ago.
Does anyone here have some experience with this error?
Only If I use the WHERE clause, I get this error.
I use php PDO to get the results.
And this is my simple table
$sql = "CREATE TABLE samenvatting (
stem_id INTEGER PRIMARY KEY AUTOINCREMENT,
poll_id TEXT,
stem_waarde_id TEXT,
totaal INTEGER
)";
$crud->rawQuery($sql);
$poll_id = "somepoll";
$records = $crud->rawSelect('SELECT * FROM samenvatting WHERE poll_id='.$poll_id);
pdo abstract class
public function conn()
{
isset($this->username);
isset($this->password);
if (!$this->db instanceof PDO)
{
$this->db = new PDO($this->dsn, $this->username, $this->password);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
public function rawSelect($sql)
{
$this->conn();
return $this->db->query($sql);
}
Thanks, Richard
It is treating "somepoll" as a column in the table. You need to quote it, since it is declared as text. Something like
$records = $crud->rawSelect(
'SELECT * FROM samenvatting WHERE poll_id="' . $poll_id . '"'
);
perhaps?