I need to perform multiple queries on a database table, basically my PHP script has to:
insert into the table a new user storing his id, name, email;
get the id of the newly created user using his email;
associate the id with a key and a timestamp.
I am pretty new to PDO and my problem is I can't figure out a smart way to get that one id without using a foreach, so basically my code is:
$query = "INSERT INTO users(name, surname, email) VALUES('" . $name . "', '" . $surname . "', '" . $email . "')";
$this->dbconn->query($query);
$query = "SELECT id FROM users WHERE email='" . $email . "'";
$data = $this->dbconn->query($query);
$id = $data['id'];
$query = "INSERT INTO users(name, surname, email) VALUES('" . $name . "', '" . $surname . "', '" . $email . "')";
$this->dbconn->query($query);
$id = $this->dbconn->lastInsertId();
Related
PHP version 5.3.3, mysql 5.0.95
Need to migrate data from an existing table to two identical tables. Data from original needs parsing before insert into the two new tables. (That code not shown as I'm hoping to isolate this problem.)
Wanted to use transaction to insure new tables are identical.
task_id field is autoincrement in test_timecard and is unsigned mediumint in test_timecar_2.
Engine is InnoDB for both tables.
Separate queries works:
$timecard_data_results = array();
$fill_old_data_array_def = " SELECT task_id, company_id, employee_id, location, task_name, task_start_time, task_end_time, tccomment FROM timecard WHERE company_id = '" . $company_request . "' AND employee_id = '" . $employee_request . "' AND DATE(task_start_time) < '" . $new_text_format_date . "' AND (DATE(task_end_time) > '2014-12-31' OR DATE(task_end_time) = '2000-01-01') ORDER BY task_start_time";
$timecard_data_results = mysqli_query($conn, $fill_old_data_array_def);
while($timecard_record = mysqli_fetch_assoc($timecard_data_results)) {
$company_id = $timecard_record['company_id'];
$employee_id = $timecard_record['employee_id'];
$location = $timecard_record['location'];
$task_name = $timecard_record['task_name'];
$task_start_time = $timecard_record['task_start_time'];
$task_end_time = $timecard_record['task_end_time'];
$tccomment = $timecard_record['tccomment'];
$troubleshoot_def = "INSERT INTO test_timecard (company_id, employee_id, location, task_name, task_start_time, task_end_time, tccomment) VALUES ('" . $company_id . "', '" . $employee_id . "', '" . $location . "', '" . $task_name . "', '" . $task_start_time . "', '" . $task_end_time . "', '" . $tccomment . "')";
$troubleshoot_2_def = "INSERT INTO test_timecard_2 (task_id, company_id, employee_id, location, task_name, task_start_time, task_end_time, tccomment) VALUES (LAST_INSERT_ID(), '" . $company_id . "', '" . $employee_id . "', '" . $location . "', '" . $task_name . "', '" . $task_start_time . "', '" . $task_end_time . "', '" . $tccomment . "')";
$troubleshoot = mysqli_query ($conn, $troubleshoot_def);
$troubleshoot_2 = mysqli_query ($conn, $troubleshoot_2_def);
}
transaction with mysqli_multi_query inserts one row only to both tables. No errors reported.
$timecard_data_results = array();
$fill_old_data_array_def = " SELECT task_id, company_id, employee_id, location, task_name, task_start_time, task_end_time, tccomment FROM timecard WHERE company_id = '" . $company_request . "' AND employee_id = '" . $employee_request . "' AND DATE(task_start_time) < '" . $new_text_format_date . "' AND (DATE(task_end_time) > '2014-12-31' OR DATE(task_end_time) = '2000-01-01') ORDER BY task_start_time";
$timecard_data_results = mysqli_query($conn, $fill_old_data_array_def);
while($timecard_record = mysqli_fetch_assoc($timecard_data_results)) {
$company_id = $timecard_record['company_id'];
$employee_id = $timecard_record['employee_id'];
$location = $timecard_record['location'];
$task_name = $timecard_record['task_name'];
$task_start_time = $timecard_record['task_start_time'];
$task_end_time = $timecard_record['task_end_time'];
$tccomment = $timecard_record['tccomment'];
$troubleshoot_def = "START TRANSACTION; INSERT INTO test_timecard (company_id, employee_id, location, task_name, task_start_time, task_end_time, tccomment) VALUES ('" . $company_id . "', '" . $employee_id . "', '" . $location . "', '" . $task_name . "', '" . $task_start_time . "', '" . $task_end_time . "', '" . $tccomment . "'); INSERT INTO test_timecard_2 (task_id, company_id, employee_id, location, task_name, task_start_time, task_end_time, tccomment) VALUES (LAST_INSERT_ID(), '" . $company_id . "', '" . $employee_id . "', '" . $location . "', '" . $task_name . "', '" . $task_start_time . "', '" . $task_end_time . "', '" . $tccomment . "'); COMMIT;";
$troubleshoot = mysqli_multi_query ($conn, $troubleshoot_def);
}
Stumped.
$troubleshoot_def = "INSERT INTO test_timecard (company_id, employee_id, location, task_name, task_start_time, task_end_time, tccomment) VALUES ('" . $company_id . "', '" . $employee_id . "', '" . $location . "', '" . $task_name . "', '" . $task_start_time . "', '" . $task_end_time . "', '" . $tccomment . "')";
$troubleshoot_2_def = "INSERT INTO test_timecard_2 (task_id, company_id, employee_id, location, task_name, task_start_time, task_end_time, tccomment) VALUES (LAST_INSERT_ID(), '" . $company_id . "', '" . $employee_id . "', '" . $location . "', '" . $task_name . "', '" . $task_start_time . "', '" . $task_end_time . "', '" . $tccomment . "')";
There are lot's of problems here. First is that it does not make any sense at all to insert nearly identical data into two different tables. In fact when the operation completes you have three tables with nearly identical data namely test_timecard_2, test_timecard and timecard
Secondly you are inserting unescaped data. Since data comes from another of your tables there isn't much chance of an sql injection but there is still a likelyhood that the queries will fail. Specifically I am talking about code like this:
VALUES ('" . $company_id . "', '" . $employee_id . "', '" . $location . "', '" . $task_name . "', '" . $task_start_time . "', '" . $task_end_time . "', '" . $tccomment . "')";
Thirdly, you almost never need to do SELECT - LOOP - INSERT because mysql has a built in INSERT SELECT command.
INSERT INTO test_timecard (company_id, employee_id, location, task_name, task_start_time, task_end_time, tccomment)
SELECT * FROM time_card
take care to get the columns right (the above is just a copy paste from two sections of your code)
i can't make this insert into work. can someone tell me where i'm doing wrong?
$id_application = 1;
foreach ($array_account as $rows) {
$e_mail = $rows["EMAIL"];
$pwd = $rows["PWD"];
$salt = $rows["SALT"];
$values = "(" . $e_mail . ", " .$pwd . ", " .$salt . ", " . $id_application . ")";
$query = "INSERT INTO DBNAME..ACCOUNT (EMAIL, PWD, SALT, ID_APPLICATION) "
. " VALUES " . $values;
$result = sybase_query($query);
}
these are the errors that iget:
Column names are illegal. (severity 15, procedure N/A
The identifier that starts with '...' is too long. Maximum length is 30
The name '...' is illegal in this context. Only constants, constant expressions, or variables
allowed here
i'm able to insert a single row in sybase central like:
insert into DBNAME..ACCOUNT (EMAIL, PWD, SALT, ID_APPLICATION)
select EMAIL, PWD, SALT, 3 from ACCOUNT where ID = 10 go
Do this $values = "('" . $e_mail . "', '" .$pwd . "', '" .$salt . "', '" . $id_application . "')";
I need to save a color code to my color_codes table but I also want to save the name of who saved it. I have a users_table with the information on it.
<?php
include("db_connect.php");
$color = $_POST['color'];
$colorName = $_POST['colorName'];
$sql = "INSERT INTO color_codes (color_code, color_name) VALUES ('" . $color . "', '" . $colorName . "')";
if ($conn->query($sql) === TRUE) {
} else {
}
?>
1) add another column as user_id in the 'color_codes' table.
2) get the current user id from the SESSION or from the users_table.
3) change your query to this
$sql = "INSERT INTO color_codes (color_code, color_name, user_id) VALUES ('" . $color . "', '" . $colorName . "', '" . $user_id . "')";
I am stuck with this.
Here is the code:
This is how I call the function,
$res = DataManager::agregarPropiedad($_POST);
here is the function that generate the query and send it,
public static function agregarPropiedad($datos){
$sql = "INSERT INTO propiedades (id_propiedad, nombre, tipopropiedad, descripcion, dormitorios, baños, direccion, localidad, provincia, fecha_alta, sup_cubierta, sup_total)
VALUES (null, '" . $datos['nombre'] . "', '" . $datos['tipo'] . "', '" . $datos['descripcion'] . "', '" . $datos['dormitorios'] . "', '" . $datos['baños'] . "', '" . $datos['direccion'] . "', '" . $datos['localidad'] . "', '" . $datos['provincia'] . "', CURRENT_TIMESTAMP, '" . $datos['supcubierta'] . "', '" . $datos['suptotal'] . "')";
//$sql = "insert into prueba values(null,'".$datos['nombre']."')";
echo $sql;
return DataManager::consulta($sql);
}
When I copy the echo$sql and paste in phpMyAdmin works fine, but when I try to send my function is not inserting anything, but I have no errors. mysql_erros() its empty too.
U can see that, there is a commented $sql. I use that just for test with another table which is much simpler and query the function "consulta" which works fine too.
This is maybe the 40 function that insert things in mysql database, but the first with which I have problems, and I don't know why =(
helppppp...
From personal experience, MySQL queries that work when dumped / copied / pasted into PhPMyAdmin that don't work in code are caused by:
autoincrement / unique field issues
unexpected characters in unprocessed form data
duplicate POST values ( like an array )
mismatched field count
encoding / character set issues
It may well be that if you address the second issue the problem might fix itself. In any case at a minimum you should process you POST(ed) data with strip_tags and add_slashes, but for MySQL mysql_real_escape_string() is strongly recommended.
http://php.net/manual/en/function.mysql-real-escape-string.php
http://www.adminsehow.com/2010/03/prevent-mysql-injection-in-php
There is a problem with your quotes inside the VALUES() and its vulnerable.
<?php
public static function agregarPropiedad($datos)
{
$tipo = mysql_real_escape_string($datos['tipo']);
$nomber = mysql_real_escape_string($datos['nombre']);
$dormitorios = mysql_real_escape_string($datos['descripcion']);
$baños = mysql_real_escape_string($datos['baños']);
$direccion = mysql_real_escape_string($datos['direccion']);
$localidad = mysql_real_escape_string($datos['localidad']);
$provincia = mysql_real_escape_string($datos['provincia']);
$supcubierta = mysql_real_escape_string($datos['supcubierta']);
$suptotal = mysql_real_escape_string($datos['suptotal']);
$sql = "INSERT INTO propiedades (id_propiedad, nombre, tipopropiedad, descripcion, dormitorios, baños, direccion, localidad, provincia, fecha_alta, sup_cubierta, sup_total)";
$sql .= "VALUES (null,'$tipo','$nomber ','$dormitorios ','$baños ','$direccion ','$localidad','$provincia ',CURRENT_TIMESTAMP,'$supcubierta','$suptotal')";
if(mysql_query($sql))
{
return TRUE;
}else{ return FALSE; }
}
?>
I have part of the code below:
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO".TBL_USERSDONTPAY."VALUES ($array[\"username\"], $array[\"password\"], '0',$array[\"userid|\"], )";
$second_result = $database->query($second_query);
}
The query doesn't seem to work. Any clues? I think it's a problem with the quotes or something. How can actually pass array elements?
here is my whole code i want to move one row to another table
$q = "SELECT * FROM ".TBL_USERS." WHERE username = '$subuser'";
$result = $database->query($q);
if($result && $result->num_rows == 1){
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO" . TBL_USERSDONTPAY . "VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] ."')";
$second_result = $database->query($second_query);
if($second_result){
// it worked!
$q = "DELETE FROM ".TBL_USERS." WHERE username = '$subuser'";
$database->query($q);
}
}
}
You need to clean that query up and remove the final comma.
$second_query = "INSERT INTO " . TBL_USERSDONTPAY . " VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] . "')";
I see several issues with your query code
escaping of the array indexes in your string:
you can either end the string and concatenate the parts together:
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] . "')";
or use the {$var} syntax:
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" VALUES ('{$array['username']}', '{$array['password']}', '0', '{$array['userid']}')";
missing spaces (see example code above .. you were missing the spaces before and after the table name)
missing field names. your query may work without if you specify all fields in the right order, but will fail misteriously when you alter the table later (e.g. add a field to the table)
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" (username, password, foo, user_id)".
" VALUES ('{$array['username']}', '{$array['password']}', '0', '{$array['userid']}')";
please note you should actually insert the correct field names in the second line of my example above. You can find more information on this in the MySQL docs for INSERT