I am trying to pass variable values to a MySQL database table. I am using a PDO to get access to the database, and am able to echo the variable values that I want to insert to my browser. The only thing I can think of is that my syntax is wrong. I am clearly a novice at using PHP/MySQL.
I am not getting any errors. The info isn't going into my table. What am I doing wrong?
$sql = "INSERT INTO testquiz (version, points, passing_percent, gained_score, username, email, quiz_title, date)
VALUES ('$version', $points, $passing_percent, $gained_score, '$username', '$email', '$quiz_title', CURDATE() )";
Query to create table:
MySQL CREATE TABLE Query:
CREATE TABLE testquiz (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
version TEXT,
points INT,
passing_percent DOUBLE,
gained_score DOUBLE,
username TEXT,
email TEXT,
quiz_title TEXT,
date DATE NOT NULL
) DEFAULTCHARACTER SET utf8 ENGINE=InnoDB
When using PDO, the generally accepted practice is to use prepared statements for SQL, which essentially are a method used to sanitize your string input.
If your database connection object is $dbo then it would usually go like this.
Create a prepared statement by calling the prepare method on your database connection object:
$sql = $dbo->prepare("INSERT INTO testquiz (version, points, passing_percent, gained_score, username, email, quiz_title, date)
VALUES (:version, :points, :passing_percent, :gained_score, :username, :email, :quiz_title, CURDATE())");
As you can see, instead of passing in the variables I want for the values directly, I've created placeholders. Then, call the execute method on the $sql obect and pass the values in for the placeholders as key-value pairs in an array.
$sql->execute(array(":version" => $version, ":points" => $points, ":passing_percent" => $passing_percent, ":gained_score" => $gained_score, ":username" => $username, ":email" => $email, ":quiz_title" => $quiz_title));
This code passes in the values you define instead of the placeholders, and it properly escapes and sanitizes the variables you pass in for security, while executing your INSERT statement.
http://us1.php.net/pdo.prepared-statements
Change the insert statement to the below format and try.
$sql = "INSERT INTO testquiz (version, points, passing_percent, gained_score, username, email, quiz_title, date)
VALUES ('".$version."', '".$points."', '".$passing_percent."', '".$gained_score."', '".$username."', '".$email."', '".$quiz_title."', CURDATE())";
Related
I'm not a big fan of Doctrine, but I need to use it for a specific project.
I have to migrate data from an old oracle database to a brand new postgresql database.
I use the query builder or raw queries with prepared statements. It's ok for most of the request, but I'm not ok with null values...
In the following request birthday can be null.
insert into public.mytable (id, name, birthday) values ('foo', 'bar', null);
I use bindValue, but Doctrine change the null into empty string, and Postgresql can't accept that...
That's how I try :
$rawQuery = "insert into public.mytable (id, name, birthday) values (:id, :name, :birthday);"
$statement = $pgsql->prepare($rawQuery);
$statement->bindValue('id', $id);
$statement->bindValue('name', $name);
$statement->bindValue('birthday', $birthday); // Can be null
$statement->execute();
It's fine if $birthday is not null, it crash otherwise.
How can I do that?
The SQL statement is as follows:
$sql = "
INSERT INTO usertable
(
userid,,
name,
username,
password,
typeofuser,
dateofaddition,
createdby,
status
)
VALUES (
$userid,
'$empname',
'$username',
'$password',
'$usertype',
'$doa',
'$createdby',
'$radiobt'
)
";
Remove the comma from after userid and correctly include your variables
$sql = "INSERT INTO usertable
(
userid,
name,
username,
password,
typeofuser,
dateofaddition,
createdby,
status
)
VALUES
(
".$userid.",
".$empname.",
".$username.",
".$password.",
".$usertype.",
".$doa.",
".$createdby.",
".$radiobt."
)";
Make sure you prepare this statement before getting it into the DB! (more info: Prepared statement (Wikipedia))
There is a double ,, after userid.
$sql = "INSERT INTO usertable(userid,name,username,password,typeofuser,dateofaddition,createdby,status) VALUES ($userid,'$empname','$username','$password','$usertype','$doa','$createdby','$radiobt')"
Let us take things step by step:
Field names in the query match the field name in the table (they should exactly be the same even the case should match).
What and from where are the values for the varaibles getting generated?
Do the values correspond to the datatype of the fields in the table?
For eg. If there is a variable which expects to receive integer as values and it is made to store strings or characters, mysql is bound to give an error message.
Check for these and let me know.
Is it possible to submit data to two tables with the same query?
My existing code looks like this:
private function adduser() {
if (!empty($this->error)) return false;
$params = array(
':user_level' => parent::getOption('default-level'),
':name' => $this->name,
':email' => $this->email,
':username' => $this->username,
':password' => parent::hashPassword($this->password)
);
parent::query("INSERT INTO `login_users` (`user_level`, `name`, `email`, `username`, `password`)
VALUES (:user_level, :name, :email, :username, :password);", $params);
I didn't write this code so it is a bit confusing to me as I don't usually use PDO. What I would like to do in addition to this is add two values to my 'url_alias' table, the first is the UID (which is auto incremented from the first query) and the second is another variable value.
All of the examples I have found while searching dont seem to work for me because of the way this existing code looks.
Can anyone give me a hand?
It doesn't matter what db driver your are using (PDO, Mysqli, etc.) you question is purely about mysql capabilities. Mysql may update and delete rows from multiple tables in a single query but not insert. I.e. INSERT table_1, table_2 ... is not allowed.
You have to run one query for each table you want to insert data.
I sometimes have arrays with null or empty values. In MySql they are set up to be non-nullable, but they have default values assigned. Why then, does MySql give me an error, e.g. Column user_type can not be null. (I'm not running in strict mode).
I realise that I could use the keyword DEFAULT in place of some values when preparing the query, but I don't really want to do that. I would like to be able to write my SQL statements verbatim, rather than put them together with foreach loops, etc. For example, I would like to use "INSERT INTO users (user_type, first_name, last_name, password) VALUES (:user_type, :first_name, :last_name, :password)";
As far as I recollect, this was working fine (i.e. substituting in the correct defaults) until I moved from using ? query markers to named parameters...
Thanks...
I would create a function that accepts the values as parameters. It would have the default values in an associative array. If the value for any of the parameters is null, it would replace it with the default.
eg
function setUpQuery($user_type_in, $first_name_in, $last_name_in, $password_in){
$default_values('user_type' => 'Admin', 'first_name' => 'John', 'last_name' => 'Doe', 'password' => 'XXX');
$user_type = ($user_type_in == NULL)? $default_values['user_type']:$user_type_in;
.....
return "INSERT INTO users (user_type, first_name, last_name, password) VALUES ('$user_type', '$first_name', '$last_name', '$password');"
}
Good Point. How about the following:
INSERT INTO users(user_type, first_name, last_name,password) values
(ifnull('$user_type',default(user_type)), ifnull('$first_name', default(first_name)),
ifnull('$last_name',default(last_name)), ifnull('$password', default(password));
In PHP, I am using PDO with the pgSQL drivers. I wanted to know how to get the value of the "RETURNING" clause given in the INSERT sql query.
My current code looks like this,
$query = 'INSERT INTO "TEST" (firstname, lastname) VALUES ('John', 'Doe') RETURNING user_id';
$queryHandle = $connection->prepare($query);
$queryHandle->execute();
Obviously
$queryHandle->execute();
returns TRUE or FALSE. But I wanted to get the value of "user_id" if the insert was successful. Can you guys give me a pointer as to how to go about it? Thanks.
$ret = $queryHandle->fetchColumn();
Will return a single value instead of an array.
Did you tried to treat the command as a select returning, running
$ret=$queryHandle->fetchAll();
I am doing it like this (PHP 8.1.13, PostreSQL 15):
$query = "INSERT INTO test (firstname, lastname) VALUES ('John', 'Doe') RETURNING id";
$queryHandle = $connection->prepare($query);
$queryHandle->execute();
$last_id = $connection->lastInsertId('test_id_seq');
I took 'test_id_seq' from the following SQL, i.e. it is [table]_[column]_seq
CREATE TABLE IF NOT EXISTS public.test
(...
id integer NOT NULL DEFAULT 'nextval('test_id_seq'::regclass)',
CONSTRAINT test_pkey PRIMARY KEY (id)
)