I'm trying to execute a prepared sql request wich should insert values into a variable table
This code will be more explicite than me :
$req = $db->prepare("INSERT INTO ?
( `id`,
`parent_id`,
`position`,
`left`,
`right`,
`level`,
`title`,
`type`,
`content` )
VALUES (NULL,
'2',
'last',
'3',
'10',
'2',
?,
'default', ?);");
$req->execute(array($_SESSION["user_id"], $result["title"], $result["content"]));
All variables are set, I checked that with some echo.
Isn't it possible to "INSERT INTO" a variable ?
(Each user has its own table named by its unique id, that's why I can't directly write the table name in the query)
You can't use a named parameter for a table name; if you want to do that, you'll have to include the name in your SQL directly:
INSERT INTO $tablename (....
However - that's still open to SQL injection attacks.
If you want to store data like that, I'd put everything into a single table, and just add an extra field as an additional key.
No, you can't do this, you need to do like below.
$table = $_SESSION["user_id"];
$req = $db->prepare("INSERT INTO $table (`id`, `parent_id`, `position`, `left`, `right`, `level`, `title`, `type`, `content`) VALUES (NULL, '2', 'last', '3', '10', '2', ?, 'default', ?);");
$req->execute(array($result["title"], $result["content"]));
Related
I want insert data by GET in my sql but I can not insert data
<?php
include("config.php");
$f=$_GET["first_name"];
$l=$_GET["last_name"];
$e=$_GET["email"];
$m=$_GET["mobile"];
$b=$_GET["birthday"];
$g=$_GET["gender"];
$insert="INSERT INTO user ( `first_name`, `last_name`, `email`, `mobile`, `birthday`, `gender`)
VALUES ('$f', '$l', '$e', '$m', '$b', '$g')";
mysqli_query($insert);
?>
I try insert data by this link :
http://localhost:8888/restfull/insert.php?f=hayoo
It's been a long time since I have used mysqli the code below should most likely run though. As others have mentioned never bind unsanitized data (Even if you think you trust the data it's safe to use prepared statements still).
<?php
//Create you db connection
$conn = new mysqli('server', 'user', 'password', 'databasename');
//Create insert statement. Never concat un-sanitized data in statements
$insert="INSERT INTO user ( `first_name`, `last_name`, `email`, `mobile`, `birthday`, `gender`)
VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
//Values corespond to ? except the first param which represents format of expected data. "s" stands for string
$stmt->bind_param(
'ssssss',
$_GET["first_name"],
$_GET["last_name"],
$_GET["email"],
$_GET["mobile"],
$_GET["birthday"],
$_GET["gender"]
);
$stmt->execute();
Your url would look like this:
http://localhost:8888/restfull/insert.php?first_name=john&last_name=Doe&email=test#test.com&mobile=0&birthday=May&gender=male
Make sure if you are putting the url above in some type of form you correctly url encode values (I notice many of the values you are collecting will like require it slashes etc).
I need to execute 2 or more not identical queries (INSERT's in this example.) using PHP's prepared statements and MySQL's transactions. So if I have a 2 INSERT statements, I want both of them executed, or none of them.
I want to traslate this example MySQL transaction to a PHP code:
START TRANSACTION;
INSERT INTO `file` (`name`, `mime_type`, `size`, `comment`) VALUES ('file.png', 'image/png', '1024', 'My comment');
INSERT INTO `complementary_file` (`file_id`, `user_id`) VALUES (LAST_INSERT_ID(), '1');
COMMIT;
PHP code I'm working on:
mysqli_autocommit($connection, FALSE);
if ($stmtFile = mysqli_prepare($connection, "INSERT INTO `file` (`name`, `mime_type`, `size`, `comment`) VALUES (?, ?, ?, ?)")) {
mysqli_stmt_bind_param($stmtFile, 'ssis', $name, $mime_type, $size, $comment);
if (mysqli_stmt_execute($stmtFile)) {
if ($stmtComplementaryFile = mysqli_prepare($connection, "INSERT INTO `complementary_file` (`file_id`, `user_id`) VALUES (?, ?)")) {
mysqli_stmt_bind_param($stmtComplementaryFile, 'ii', mysqli_insert_id($connection), $user_id);
mysqli_stmt_execute($stmtComplementaryFile);
}
} else {
mysqli_rollback($connection);
}
}
mysqli_commit($connection);
PHP code above works but what if I have more critical statements to execute? Is there are good way to execute statements with PHP's prepared statemens and transactions at the same time?
Please note that for $stmtComplementaryFile I must have a mysqli_insert_id() value. Also please note that I am not using PDO with this code — I appreciate if suggestions will be MySQLi. Thanks.
The following SQL:
START TRANSACTION;
INSERT INTO `file` (`name`, `mime_type`, `size`, `comment`) VALUES ('file.png', 'image/png', '1024', 'My comment');
INSERT INTO `complementary_file` (`file_id`, `user_id`) VALUES (LAST_INSERT_ID(), '1');
COMMIT;
Can be converted to PHP (with prepared statements) as follows:
mysqli_begin_transaction($connection, MYSQLI_TRANS_START_READ_WRITE);
if ($stmtFile = mysqli_prepare($connection, "INSERT INTO `file` (`name`, `mime_type`, `size`, `comment`) VALUES (?, ?, ?, ?)")) {
mysqli_stmt_bind_param($stmtFile, 'ssis', $name, $mime_type, $size, $comment);
if (mysqli_stmt_execute($stmtFile)) {
if ($stmtComplementaryFile = mysqli_prepare($connection, "INSERT INTO `complementary_file` (`file_id`, `user_id`) VALUES (?, ?)")) {
mysqli_stmt_bind_param($stmtComplementaryFile, 'ii', mysqli_insert_id($connection), $user_id);
mysqli_stmt_execute($stmtComplementaryFile);
}
} else {
mysqli_rollback($connection);
}
}
mysqli_commit($connection);
In general these two statements are equivalent, however it's a good idea to know what transactions are and what transactions are not.
Transactions are a mechanism to ensure that bulk operations are executed atomically and their results are reflected in the database only if ALL of them succeed. It ensures atomicity of operations.
Transactions are not a mechanism to implement a mutual exclusion lock on the tables. If a table needs to be locked then the LOCK TABLES [READ|WRITE] needs to be used. Equivalently in PHP this is achieved by doing a:
mysqli_query($connection, "LOCK TABLES tableName as TableAlias [read|write]");
followed by
mysqli_query($connection, "UNLOCK TABLES");
I know questions like this exist all over, but I can't see what's wrong with my code. The DB works and I run an update query just fine earlier on in the code.
Query 1:
mysql_query("INSERT INTO `login_history` (`memberid`, `ip`, `host`, `location`, `status`, `date`) VALUES ('".$login."', '".$ip."', '".$details->hostname."', '".$loc."', 'success', NOW()");
Query 2:
mysql_query("INSERT INTO `login_history` (`memberid`, `ip`, `host`, `location`, `status`, `date`) VALUES ('".$login."', '".$ip."', '".$details->hostname."', '".$loc."', 'failure', NOW()");
Here is an echo of the string as requested:
INSERT INTO `login_history` (`memberid`, `ip`, `host`, `location`, `status`, `date`) VALUES ('AAL', '**.60.**.**', 'c-174-**-**-**.hsd1.**.comcast.net', 'Town, US', 'success', NOW()
Looks like you are missing the final closing ). Also use prepared statements. Much cleaner and safer. Here is a quick example of what a Prepared Statement would look like (adapted from here) (you wold also need to make other changes to your PHP script to start using them)
$stmt = $mysqli->prepare("INSERT INTO `login_history` (`memberid`, `ip`, `host`, `location`, `status`, `date`) VALUES (?, ?, ?, ?, ?, NOW())")
$stmt->bind_param('sssss', $login, $ip, $details->hostname, $loc, 'failure');
$stmt->execute()
I have the following line of code that executes properly except for one hitch. It will print the variable name into the database.
I use this code in one of my scrips:
$con = mysql_connect("MyServer","MyDB","myPwd");
mysql_select_db("MyDB", $con);
$sql = "INSERT INTO `MyDB`.`Shipping` (`ID`, `FIRSTNAME`, `LASTNAME`, `ADDRESS1`, `ADDRESS2`, `CITY`, `STATE`, `ZIP`, `ORDERNUMBER`, `SHIPPINGTYPE`, `item1`, `item2`, `item3`, `item4`, `item5`, `item6`, `item7`, `item8`, `item9`, `item10`) VALUES (NULL, \'$first_name\', \'lname\', \'addr\', \'\', \'city\', \'state\', \'zip\', \'ordernum\', \'\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\');";
mysql_query("$sql");
mysql_close($con);
This code prints the followin to the database:
$first_name lname addr city state zip 0 0 0 0 0 0 0 0 0 0 0
Notice that the variable name, and not the contents of the variable are printed. How can I get it to print out the variable contents?
Notice that the variable name, and not the contents of the variable are printed
This is because you are not passing variables to the insert statement, rather you are passing undefined(?) constants; lname, addr, etc. You should pass in the variables you assigned values to: (assuming) $lname, $addr, etc.
Also, you don't need to pass in a NULL for the ID column. If it's set to auto_increment, the database will create this value for you.
You should also take advantage of the default column values defined by your table schema, so you don't end up passing in a huge list of variables with default values, for example, if you have a DEFAULT 0 as part of the schema for item1, item2, item3 etc, you can simply make the following insert:
$sql =
"INSERT INTO `MyDB`.`Shipping` (`FIRSTNAME`, `LASTNAME`, `ADDRESS1`, `CITY`, `STATE`, `ZIP`, `ORDERNUMBER`) VALUES ('$first_name', '$lname', '$addr', '$city', '$state', '$zip', '$ordernum');";
The database will populate item1, item2, etc columns with 0 for you automatically.
As cambraca mentioned, if you pass variables directly into your query like this, you run the risk of SQL injection. You should read up on how to prepare your queries, which will also force you to use mysqli (vs outdated mysql) api. Or even better, read up on PDO.
For one you have a quoting issue. You seem to have double quotes and then escaped single quotes. don't escape your single quotes if you string is double quoted.
It seems the value of $first_name should work. Is this the exact code? Because if you have single quotes around the whole thing it would create the output you're describing.
All your other columns aren't variables so it's hard to know what you're trying to do. If you aren't going to use them why reference them at all?
In your mysql_query call don't quote $sql again.
Finally check mysql_error() for errors. It could be you are seeing something old in the database and your code isn't working at all.
Consider using PDO. It has support for placeholders, better security and better debugging than the native mysql_* interface.
Change the insertion statement to:
$sql = "INSERT INTO `MyDB`.`Shipping`
(`ID`, `FIRSTNAME`, `LASTNAME`, `ADDRESS1`, `ADDRESS2`, `CITY`,
`STATE`, `ZIP`, `ORDERNUMBER`, `SHIPPINGTYPE`, `item1`, `item2`,
`item3`, `item4`, `item5`, `item6`, `item7`, `item8`, `item9`, `item10`)
VALUES (NULL, '{$first_name}', 'lname', 'addr', '', 'city', 'state',
'zip', 'ordernum', '', '0', '0', '0', '0', '0', '0', '0',
'0', '0', '0');";
Also, do check that your $first_name is properly assigned a value.
I suppose not to use inline variables in strings in PHP, and you are escaping ' when you do not need to. Try this:
$con = mysql_connect("MyServer","MyDB","myPwd");
mysql_select_db("MyDB", $con);
$sql = "INSERT INTO `MyDB`.`Shipping` (`ID`, `FIRSTNAME`, `LASTNAME`, `ADDRESS1`, `ADDRESS2`, `CITY`, `STATE`, `ZIP`, `ORDERNUMBER`, `SHIPPINGTYPE`, `item1`, `item2`, `item3`, `item4`, `item5`, `item6`, `item7`, `item8`, `item9`, `item10`) VALUES (NULL, '".$first_name."', 'lname', 'addr', '', 'city', 'state', 'zip', 'ordernum', '', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0');";
mysql_query($sql);
mysql_close($con);
Rather than using \'$first_name\' replace it with \"$first_name\" and the same follows with other variables too.
I want to be able to insert into two different mysql tables using php with the second mysql insert being dependent on the member id of the first insert.
For example:
mysql_query("
INSERT INTO `member_users` (
`id`,
`first_name`,
`last_name`,
`username`,
`password`,
`address1`,
`address2`,
`postcode`,
`access`,
`expires`
) VALUES (
NULL,
'$fname',
'$lname',
'$email',
'$passhash',
'$add1',
'$city',
'$postcode',
'',
''
)"
);
Then I want to take the id of this member user to create a mysql_query insert on the same page eg:
mysql_query("
INSERT INTO `member_orders` (
`order_id`,
`member_id`,
`date`,
`item`,
`size`,
`quantity`,
`price`,
`tracking_id`,
`status`,
`item_sent`,
`notes`
) VALUES (
NULL,
'$userid',
'',
'',
'',
'',
'',
'',
'',
'',
''
)
");
its probably a really easy answer and a really silly question but cannot seem to find the answer anywhere
thanks in advance
If I have understood correctly, and you need to get the member_id from the first query, to use in the second query, you can use the PHP function
$the_member_id = mysql_insert_id();
http://php.net/manual/en/function.mysql-insert-id.php
You can also do it without using that PHP function
$sql = "SELECT LAST_INSERT_ID()";
// add code here to run the query.
You can use the php function mysql_insert_id() to get the last id you input into the database.
EG:
$sql = "INSERT INTO `table` VALUES (NULL, 'Thomas', 'Male')";
$query = mysql_query($sql);
$id = mysql_insert_id();
So in your question after the first INSERT you need this:
$userid = mysql_insert_id();
Then your second query will work.
You can use mysql_insert_id() to get id, generated by last insert.
mysql_insert_id — Get the ID generated from the previous INSERT operation
You could use the LAST_INSERT_ID MySQL function in your second SQL statement to get the last insert ID from the first.
mysql_query("
INSERT INTO `member_orders` (
`order_id`,
`member_id`,
`date`,
`item`,
`size`,
`quantity`,
`price`,
`tracking_id`,
`status`,
`item_sent`,
`notes`
) VALUES (
NULL,
LAST_INSERT_ID(),
'',
'',
'',
'',
'',
'',
'',
'',
''
)
");
I would recommend that if you use this approach then you execute the queries within a transaction. That way there's no way that another insert can occur between your first insert and your second, thus throwing off the result of LAST_INSERT_ID.
After executing mysql_query() function you can get lastly inserted id of lastly inserted table by mysql_insert_id().
You can do something like what is done in this example
$sql = "INSERT INTO users(name,gender) VALUES ('$name','$gender')";
$result = mysql_query( $sql,$conn );
$user_id = mysql_insert_id( $conn );
$sql = "INSERT INTO website(site,user) VALUES ('$site',$user_id)";
$result = mysql_query( $sql,$conn );
Manual for mysql_insert_id