This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed last year.
I am trying to insert data from modal after user clicks submit button. But it is not working, I have 2 files index to display modal and PHP file to run connect MySQL and insert data into it. I don't think it recognizes submit action. I also have question how do I insert primary key id into database or does it adds automatically.
HTML submit code:
<button type="submit" action="add.php"class="btn">Finish!</button>
PHP code:
<?php
include 'db.php';
$cName = $_POST['form-name'];
$ser = $_POST['form-s-name'];
$link = $_POST['form-t'];
$info = $_POST['form-des'];
$sql = "INSERT INTO crewlist(id, name,sname,linkname,description)
VALUES ('','".$cName."','".$ser."','".$link."','".$info."')";
mysqli_query($conn,$sql);
if(mysqli_affected_rows($conn) > 0){
echo "<p>Added</p>";
The textbook way to do this is to use prepared statements:
$stmt = mysqli_prepare($conn,
"INSERT INTO crewlist(name,sname,linkname,description) VALUES (?,?,?,?)"
);
mysqli_stmt_bind_param($stmt, 'ssss',
$_POST['form-name'],
$_POST['form-s-name'],
$_POST['form-t'],
$_POST['form-des']
);
$result = mysqli_stmt_execute($stmt);
If you use prepared statements correctly you're guaranteed that your values are inserted with the proper escaping. Here I've used s for string, but there are other types listed in the documentation.
You'll want to enable exceptions for errors in case you make a mistake.
If you're doing a lot of database work I'd strongly encourage you to use an ORM like Doctrine or Propel as they make interfacing with your records a lot more pleasant.
you are not using variables in sql query you should use it like this
$sql = "INSERT INTO crewlist(id, name,sname,linkname,description)
VALUES ('','{$cName}','{$ser}','{$link}','{$info}')";
Insert query not matching your column use this it will work:
$sql = "INSERT INTO crewlist(id, name,sname,linkname,description)
VALUES ('',cName,ser,link,info)";
this will insert cName,ser,link,info in table if you want the data use:
'".$cname."'
Related
This question already has answers here:
How to view query error in PDO PHP
(5 answers)
Closed 2 years ago.
I'm trying to update some data from my database but nothing I've tried/found has been of any success to me. There are no errors or anything, literally nothing happens. The page reloads but it does not store anything into the database. How can I fix this problem?
The code:
function AddToBook() {
$get_post_id = filter_var(htmlentities($_GET['pid']), FILTER_SANITIZE_NUMBER_INT);
$book_id = filter_var(htmlentities($_GET['bid']), FILTER_SANITIZE_NUMBER_INT);
$get_episodes = filter_var(htmlentities($_GET['ep']), FILTER_SANITIZE_NUMBER_INT);
$episode = $get_episodes + 1;
// Insert book data into wpost
$odb = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$updatePostRecord = "UPDATE wpost SET book_id=:book_id, episode_number=:episode WHERE id=:get_post_id";
$UpdatePost = $odb->prepare($updatePostRecord);
$UpdatePost->bindParam(':book_id',$book_id,PDO::PARAM_INT);
$UpdatePost->bindParam(':episode',$episode,PDO::PARAM_INT);
$UpdatePost->bindParam(':get_post_id',$get_post_id,PDO::PARAM_INT);
$UpdatePost->execute();
// Insert post data into books
$updateBookRecord = "UPDATE books SET episodes='$episode' WHERE id='$book_id'";
$UpdateBook = $conn->prepare($updateBookRecord);
$UpdateBook->execute();
}
You want to use the PDO class that you have defined there instead of $conn (that is not defined), might as well put the variables into brackets just to make sure they are interpreted correctly, if you use a string literal.
$updateBookRecord = "UPDATE books SET episodes='{$episode}' WHERE id='{$book_id}'";
$UpdateBook = $obd->prepare($updateBookRecord);
$UpdateBook->execute();
Also, as it stand right now this is not a proper prepared statement. You should use bindParam function like on the initial UpdatePost.
Here is how it would look as a proper prepared statement.
$updateBookRecord = "UPDATE books SET episodes=:episode WHERE id=:book_id";
$UpdateBook = $obd->prepare($updateBookRecord);
$UpdateBook->bindParam(':episode',$episode,PDO::PARAM_INT);
$UpdateBook->bindParam(':book_id',$book_id,PDO::PARAM_INT);
$UpdateBook->execute();
An update can successfully update 0 rows. I would triple check your WHERE clause to see if it is actually trying to match existing rows.
When you use single quotes '' with variable, php understand it as a string not variable. so you might want to change your update statement to
$updateBookRecord = "UPDATE books SET episodes = $episode WHERE id= $book_id ";
or alternatively
$updateBookRecord = "UPDATE books SET episodes = ". $episode . " WHERE id= ".$book_id;
However this is not the standard way to do things, and invite sql injections, you better use PDO or other mechanism to make it more secure. https://www.w3schools.com/sql/sql_injection.asp
I generate the below query in two ways, but use the same function to insert into the database:
INSERT INTO person VALUES('','john', 'smith','new york', 'NY', '123456');
The below method results in CORRECT inserts, with no extra blank row in the sql database
foreach($_POST as $item)
$statement .= "'$item', ";
$size = count($statement);
$statement = substr($statement, 0, $size-3);
$statement .= ");";
The code below should be generating an identical query to the one above (they echo identically), but when I use it, an extra blank row (with an id) is inserted into the database, after the correct row with data. so two rows are inserted each time.
$mytest = "INSERT INTO person VALUES('','$_POST[name]', '$_POST[address]','$_POST[city]', '$_POST[state]', '$_POST[zip]');";
Because I need to run validations on posted items from the form, and need to do some manipulations before storing it into the database, I need to be able to use the second query method.
I can't understand how the two could be different. I'm using the exact same functions to connect and insert into the database, so the problem can't be there.
below is my insert function for reference:
function do_insertion($query) {
$db = get_db_connection();
if(!($result = mysqli_query($db, $query))) {
#die('SQL ERROR: '. mysqli_error($db));
write_error_page(mysqli_error($db));
} #end if
}
Thank you for any insite/help on this.
Using your $_POST directly in your query is opening you up to a lot of bad things, it's just bad practice. You should at least do something to clean your data before going to your database.
The $_POST variable often times can contain additional values depending on the browser, form submit. Have you tried doing a null/empty check in your foreach?
!~ Pseudo Code DO NOT USE IN PRODUCTION ~!
foreach($_POST as $item)
{
if(isset($item) && $item != "")
{
$statement .= "'$item', ";
$size = count($statement);
$statement = substr($statement, 0, $size-3);
$statement .= ");";
}
}
Please read #tadman's comment about using bind_param and protecting yourself against SQL injection. For the sake of answering your question it's likely your $_POST contains empty data that is being put into your query and resulting in the added row.
as #yycdev stated, you are in risk of SQL injection. Start by reading this and rewrite your code by proper use of protecting your database. SQL injection is not fun and will produce many bugs.
I have moved to IIS 8 in PHP 5.4. I am trying to collect data from a table and insert them to a different one, i know my code is correct, but seems to be not working, probably because of the php version, can anyone help me?
here's my code
$query = odbc_exec($conn, "SELECT * FROM member");
while($rows = odbc_fetch_array($query)) {
$querystring = "INSERT INTO oldusers (username, password, regdate) VALUES ('$rows['userid']', '$rows['passwd']', '$rows['registdate']')";
$query2 = odbc_exec($conn, $querystring);
odbc_free_result($query2);
//echo $rows['userid']." ".$rows['passwd']." ".$rows['registdate']."<br>";
}
thanks in advance.
instead trying to insert one by one record, better to insert like below:
INSERT INTO oldusers (username, password, regdate) SELECT userid,passwd,registdate FROM member
for more information :http://dev.mysql.com/doc/refman/5.5/en/insert-select.html
You're placing $rows['passwd'] inside of a double-quoted string. Instead you should do:
$str = "some sql $rows[passwd] rest of sql"; // notice the absence of single quotes
or:
$str = "some sql {$rows['passwd']} rest of sql";
or (I think this way is most readable):
$str = 'some sql' . $rows[passwd] . ' rest of sql';
If your column contains text you'll need to add surrounding single quotes where necessary.
Having said all that, you should instead use parameterized queries (if your database supports it) as it's safer (from SQL injection). If that's unavailable you will at the very least need to escape the data before concatenating it to the string.
I have multiple fields with names that look like name_$i and I am trying to figure out a way to "on submit", send them all to the database. The thing is that the form is looped and the insert has to be able to adapt to the number of fields in the form. Is there a way to do this???
<?php
$fldcnt = $_POST['fldcnt'];
$i = $_POST['i'];
for ($i = 0; $i < $fldcnt; $i++){
$NAME = $_POST['name_$i'];
$AGE = $_POST['age_$i'];
$ADDRESS = $_POST['address_$i'];
$TELEPHONE = $_POST['telephone_$i'];
$EMAIL = $_POST['email_$i'];
$q_register_new_users = "insert into registration set
NAME = '$NAME',
AGE = '$AGE',
ADDRESS = '$ADDRESS',
TELEPHONE = '$TELEPHONE',
EMAIL = '$EMAIL'";
mysql_query($q_new_products,$connection) or die(mysql_error());
};
?>"
HTML and PHP
You can enter input fields into an array by simply calling the field name[]. Like so:
<input name="name[]" />
You can then use PHP to loop through the fields like so:
foreach($_POST['name'] as $key=>$value){
// Insert the value of the form field into a string or query
// i.e. build the query
$query .= $value;
}
// Then execute the query for each set of fields
The logic above is actually incorrect, but it should give you an idea of what I mean.
MySQL
Your SQL syntax is incorrect, the correct syntax for inserting into a MySQL database is:
INSERT INTO `table` (`field_1`, `field_2`)
VALUES ('value_1', 'value_2')
PLEASE NOTE
The use of the mysql_ functions is hugely discouraged due to there impending deprecation. Instead, most PHP programmers are now using the PDO / SQLite Classes. Whilst these might seem complex, they are actually pretty simple and offer a much more secure way of executing SQL statements.
PDO
SQLite
The syntax for INSERT statement should be like this,
INSERT INTO registration (NAME , AGE , ADDRESS, TELEPHONE, EMAIL)
VALUES ('$NAME', '$AGE', '$ADDRESS','$TELEPHONE', '$EMAIL')
but hte query above is vulnerable with SQL INJECTION, please read the article below to learn how to protect from it,
How can I prevent SQL injection in PHP?
If you are going to keep structure of your code, you need to use double quotes instead of apostrophes
$NAME = $_POST["name_$i"];
or put the variable out
$NAME = $_POST['name_'.$i];
Using array is best way to do this. But if you still want to go head with a counter then you could use
for($i = 0;isset($_POST["name_{$i}"]);$i++)
{
// name found
}
Please note that this code may not be optimal if the name_xx fields are coming from checkboxes, where a user selected items and skipped some in between.
PS. I posted this a comment but it is more suitable as an answer.
I'm in a bit of a pickle here, its just that I'm trying to enter some data that I get from users into a table, but for some reason it won't let me insert the data, however I have exactly the same query for another part of the table and that seems to work perfectly fine.
for example when I execute this query, it doesn't work:
$updateibtask2 = "UPDATE ibtask_task2_75beep SET
Trial1_tone_actual= '$taskerror[0]', Trial2_tone_actual= '$taskerror[1]', Trial3_tone_actual= '$taskerror[3]',
Trial4_tone_actual= '$taskerror[4]', Trial5_tone_actual= '$taskerror[5]', Trial6_tone_actual= '$taskerror[6]',
Trial7_tone_actual= '$taskerror[7]', ... WHERE user_id = '$memberid'";
However, when I try this query it works perfectly fine:
$updateibtask2_estimate = "UPDATE ibtask_task2_75beep SET
Trial1_tone_estimate= '$taskerror[0]', Trial2_tone_estimate= '$taskerror[1]', Trial3_tone_estimate= '$taskerror[3]',
Trial4_tone_estimate= '$taskerror[4]', Trial5_tone_estimate= '$taskerror[5]', Trial6_tone_estimate= '$taskerror[6]',
Trial7_tone_estimate= '$taskerror[7]', ... WHERE user_id = '$memberid'";
I'm just wondering where I'm going wrong?
Also if it helps the PHP code that I'm using to run these queries are:
$task2 = array();
$task2 = $_SESSION['task2'];
$task2estimate = array();
$task2estimate = $_SESSION['estimatedpress2'];
$task2actual = array();
$task2actual = $_SESSION['actualpress2'];
addacutalerror_75($memberid, $task2actual);
addestimatederror_75($memberid, $task2estimate);
Also to check whether there was data present for $task2actual I had done an echo ..[0], .. [1].. etc and there was data present in the array.
Updated
For those who are searching for solutions and have the same problem, here's what I did:
function addacutalerror_75($memberid, $task2actual) {
$insertmember = "INSERT INTO ibtask_task2_75beep (user_id, Trial1_tone_actual,
Trial2_tone_actual, Trial3_tone_actual, Trial13_tone_actual,
Trial14_tone_actual, ..., Trial40_notone_actual) VALUES ('$memberid', '$task2actual[0]', '$task2actual[1]', '$task2actual[3]', '$task2actual[18]', '$task2actual[21]', '$task2actual[22]', '..., '$task2actual[24]', '$task2actual[29]', '$task2actual[33]','$task2actual[38]' )";
mysql_query($insertmember) or die(mysql_error());
}
by the way, UPDATE is very different from INSERT.
UPDATE - modify the existing record(s) on the table.
INSERT - adds new record(s) on the table.
Your query is fine but you are doing update. But you want to insert record not to update record right? The query when you insert record looks like this,
$updateibtask2 = "INSERT INTO ibtask_task2_75beep
(Trial1_tone_actual, Trial2_tone_actual,
Trial3_tone_actual,...)
VALUES ('$taskerror[0]', '$taskerror[1]',...)";
and your query is vulnerable with SQL Injection. Please take time to read the article below to protect against SQL injection,
Best way to prevent SQL injection in PHP?