<?php
$sent = $_GET['sent'];
if($sent == "yes") {
require('database_connection.php');
$name = $_GET['name'];
$desc = $_GET['desc'];
$email = $_SESSION['Memberid'];
date_default_timezone_set('Europe/London');
$date = date("d.m.y");
$sql = 'INSERT INTO `'.$email.'` (`id`, `Note`, `Share Url`, `Name`, `Description`, `Date`, `Type`) VALUES (\'\', \'Enter Note Here.\', \'\', \''.$name.'\', \''.$desc.'\', \''.$date.'\', \'Text\')';
$i = mysqli_query($dbc, $sql);
if($i) {
echo '<h2>Created note.</h2>';
header( 'Location: https://daccaa.com/edits' ) ;
} else {
echo '<h2>Failed to create a note for you.</h2>';
echo $name.'<br />';
echo $desc.'<br />';
echo $email.'<br />';
echo $date.'<br />';
echo $sql.'<br />';
echo $i.'<br />';
echo '<h1 style="visibility: hidden;">_</h1>';
echo 'Let us Know.';
}
} else {
echo '<div class="holder">
<h1>Lets create a new note:</h1>
<h3 style="visibility: hidden;">_</h3>
<form method="GET" action="#">
<input type="text" name="name" class="myBox" placeholder="Enter Name Here" />
<input type="text" name="desc" class="myBox" placeholder="Enter Description Here" /> <br />
<input type="hidden" value="yes" name="sent" />
<input type="submit" value="Generate" class="select" /><br />
Go Back
</form>
</div>
</div>';
}
?>
The code above is from my website, the idea behind the code is that it will create a new row in the database with the information upon its execution.
This is what the testing upon failure will echo:
new_test_name
new_test_desc
49
02.07.14
INSERT INTO `49` (`id`, `Note`, `Share Url`, `Name`, `Description`, `Date`, `Type`) VALUES ('', 'Enter Note Here.', '', 'new_test_name', 'new_test_desc', '02.07.14', 'Text')
But I still cannot seem to get the value to enter, This similar method works fine on another page, I can pretty much eliminate the fact that it could be in the database file as it works fine on another page in the same directory.
The structure of the MYSQL database is:
id | Note | Share Url | Name | Description | Date | Type
Please note I will be going over this later to add more ways to prevent SQL injection, I just want to get the basic code sorted out first.
From your error message: Duplicate entry '0' for key 'PRIMARY'
I'm assuming id is your primary key. Make sure you have auto increment setup on this column and then just exclude the id field completely in the query.
Right now your inserting a blank ID. Without strict enforcement, MySQL will convert an empty value to a 0 for an integer field. So you are trying to insert into ID 0 every time rather than creating a new row.
Dangers of your query
You are using unsanitized user input in your query (GET). GET, POST, REQUEST, and COOKIE variables should always be used with prepared queries.
Right now I could load your url with something like ?name="'; DELETE FROM 49 WHERE 1;" and wipe out your entire table. Research SQL injections and how to use MySQLi to make prepared queries.
Related
i have this two text fields that ask the user to put in two numbers that are limited to 49 numbers, so that i can have an array of number 1 to 50, or 151 to 200, or 27551 to 27600 any number but a series of 49 consecutive numbers, my problem is i dont know how to put them inside the database, i have no clue i have been searching for everything about inserting arrays but they dont work on my case,
This is my form
<form id="form3" name="form1" method="post" action="">
<p>From:
<input type="text" name="from" id="form_number" class="from" />
- To:
<input type="text" name="to" id="form_number" class="to" />
</p>
<p>Waybill Booklet:
<select name="waybill_booklet[]" id="form_list">
<?php
do {
?>
<option value="<?php echo $row_Booklet['id_waybill_booklet']?>"><?php echo $row_Booklet['booklet_no']?></option>
<?php
} while ($row_Booklet = mysql_fetch_assoc($Booklet));
$rows = mysql_num_rows($Booklet);
if($rows > 0) {
mysql_data_seek($Booklet, 0);
$row_Booklet = mysql_fetch_assoc($Booklet);
}
?>
</select>
</p>
<p>
<input type="hidden" name="status[]" value="4" />
<input type="submit" name="button" id="form_button" value="OK!" />
</p>
</form>
the 49 series of consecutive numbers will be inserted into the database with a foreign key what is chosen from the drop down menu, and a value of 4 that is in the hidden field, so basically there are 4 columns to my table 1 for primary key 1 for the series of numbers and 1 for the foreign key and the last will be the value of the numbers.
This is my php code to get the series of numbers
<?php
$booklet = $_POST['waybill_booklet'];
$status = $_POST['status'];
$from = $_POST['from'];
$to = $_POST['to'];
$number = range($from,$to);
$count = 0;
$myArray = range($from,$to);
while($count<=49){
if($count<49){
echo $myArray[$count]. ", ";
}else{
echo $myArray[$count];
}
$count++;
}
?>
i dont know how to insert the data's
$waybill = mysql_real_escape_string($_POST['waybill_booklet'][0]);
$status = mysql_real_escape_string($_POST['status'][0]);
foreach (range($from, $to) as $number) {
$sql = "INSERT INTO yourTable (id, waybill, status) VALUES($number, '$waybill', '$status')");
mysql_query($sql) or die(mysql_error());
}
You should also switch to PDO or mysqli, so you can use parametrized queries instead of substituting strings into the query. Then you don't need to escape the values like that.
Instead of storing this as an array (since you want to store this as bulk, I assume it will not involve any direct database level aggregation or computation), you can store it as a json string using the json_encode($myArray_series_of_numbers). This gives you the flexibility to store them as a string column and when you retrieve it back, you can use json_decode($model->series_of_numbers_column,true) to get it back as an array for easy computation back in PHP.
Hope this helps
Here is a tutorial on using mysql in php http://www.w3schools.com/php/php_mysql_insert.asp specifically the INSERT command. just build your data into variables instead of echo'ing it and then follow the guide to interact with a database
here is the auto increment tutorial to generate primary ids for each array element http://www.w3schools.com/sql/sql_autoincrement.asp
you can greatly increase the speed of the inserts and do it in one submit by building a multiple insert sql string.. and then using the insert guide above to run it.
INSERT INTO Table ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
I have some simple PHP code that will generate new text boxes with the naming scheme of 'car_init$i' and 'car_num$i'. Where $i = 1 and I use i++ to increment it up. The problem I'm having is that while a user can have a maximum of 70 text boxes generated, it can be any number between 1 and 70. So I can have 46 text boxes as an example on a page if the user wanted just 46. So I would have car_num1, car_num2, car_init1, car_init2, etc. as my form names.
Car_ID would be my auto-incremented primary key, and I'd have 2 columns car_num and car_init. Is it possible to do something like this: INSERT INTO dbo (car_init, car_num) VALUES (car_init$i, car_num$i) and then use $i = 1 and i++ to increment it while adding all the values to new rows? Car_id = 1 would contain car_num1 and car_init1 information in their respective columns, Car_id = 2 would contain car_num2 and car_init2 information, and so on and so forth.
EDIT:
So this is the code I have now:
$car_num = $_POST["car_num"];
foreach($_POST['car_init'] as $key => $car_init)
{
// your insert query
$sql = "INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')";
}
What happens is every time I add to my database, only the last thing I entered gets inputted. So if I have 3 cars needed, that's 6 text boxes, but only the last text boxes on the page are the ones that get inputted.
EDIT 2: This is how my text boxes are generated. All text boxes have it the way you said, using the 'car_init[]' and 'car_num[]'.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$i = 1;
while ($i <= $_POST['carAmount'] AND $i <= 70) {
// Now print the text box to the screen
echo "<b>$i</b>. Car Initial: <input type=\"text\" class='element text small' name=\"car_init[]\" maxlength='4' id='car_init[]' /> ";
echo "Number: <input type=\"text\" class='element text small' name=\"car_num[]\" maxlength='6' id='car_num[]' /><br>";
$i++;
}
}
Ah, I think I got it.
This is a problem:
foreach($_POST['car_init'] as $key => $car_init)
{
// your insert query
$sql = "INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')";
}
I assume you're then running the query $sql? If so, that is running only the last value $sql contained! You need to:
foreach($_POST['car_init'] as $key => $car_init)
{
// your insert query
$sql = "INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')";
// actually run the query!
}
Change your html to something like this:
<input name="car_init[]" />
<input name="car_init[]" />
<input name="car_init[]" />
<input name="car_init[]" />
<input name="car_init[]" />
Then in php, your variable will be an array!
$_POST['car_init'] // is an array!
Loop through those and do multiple INSERTs.
foreach ($_POST['car_init'] as $car_num => $car_init) {
// "INSERT INTO dbo (car_init, car_num) VALUES ('$car_init', $car_num)"
}
Edit based on your updates:
INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')"
Use PDO with prepared statements instead of using string interpolation. You seem to be susceptible to sql injection attacks.
hi im running a mysql insert query, the idea is users can submit reviews to users profiles, but i wanted to know if there was a way i could block offensive words, links and prevent a way of people spamming it with blog links etc.
would i use a php if statement that says ignore these keywords; "f*ck" etc, i feel the only problem with something like this is i would have to have every word covered in the ignore statement,
or would i include something in my mysql, either way i want to block all links being inserted into the form,
can somone give me some guidance and show me how i woudld do this please thanks
html:
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<textarea name="review_recipient" id="review_recipient" maxlength="180" cols="33" rows="5" style=""></textarea><label style="">Who is the Review from?</label>
<br/>
<textarea name="review_content" id="review_content" maxlength="180" cols="33" rows="5" style=""></textarea>
<label style="">Say Something...</label>
<input name="add_review" type="image" src="http://www.playtimeboys.com/assets/img/icons/save-edit.png" BORDER="0" ALT="SUBMIT!"class="review_submit4" /></form>
php/mysql:
<?php ob_start(); ?>
<?php
// check if the review form has been sent
if(isset($_POST['review_content']))
{
$content = $_POST['review_content'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$content = stripslashes($content);
}
//We check if all the fields are filled
if($_POST['review_content']!='')
{
{
$sql = "INSERT INTO ptb_reviews (id, from_user_id, to_user_id, content) VALUES (NULL, '".$_SESSION['user_id']."', '".$profile_id."', '".$content."');";
mysql_query($sql, $connection);
$_SESSION['message']="<div class=\"infobox-wallpost\"><strong>Thank You</strong> - Your review has been sent and is awaiting approval.</div><div class=\"infobox-close4\"></div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
} } } } ?>
$blocked_words="test1,test2,test3,test4";//list of offensive word
$review_from_user ="Your reviews test2 is following hello test1"; //review from user
$blocked_words_expo = explode(",", $blocked_words);
foreach($blocked_words_expo as $rmv)
{
if(strpos($review_from_user,$rmv)==true)
{
$review_from_user = str_replace($rmv,'',$review_from_user);
}
}
echo $review_from_user;
//and then insert $review_from_user
You can try to get the values from the bad words table .something like below
$blocked_words=array();
$q="select words from block";
$rs=mysql_query($q);
while($rd=mysql_fetch_object($rs))
{
$blocked_words[]=$rd->words;
}
$string_words=explode(" ", $_POST['review_content']);
$result = array_intersect($blocked_words, $string_words);
By the above code you will get all words from table 'block' into $blocked_words.You might need to change with respect to your needs
Brief:
Based on a query, I have multiple checkboxes generated dynamically. The value of each checkbox is a string from one of the query's rows;
upon form submission, another script is ran (del.php). This script gets the array of checkboxes that were checked and loops through them so it can ran another two queries, which is the delete and update queries.
They don't work! if I try the INSERT query, it works fine. But the DELETE AND UPDATE don't.
Here is my code:
index.php:
<?php
$gettips = mysql_query('SELECT body FROM tips WHERE body!="" and approved!="yes" and approved!="no"')or die(mysql_error());
$i=0;
while($tips = mysql_fetch_array($gettips))
{ ?>
<input type="checkbox" name="checkboxes[]" value="<?php print $tips[0] ?>" />
<input type="checkbox" name="checkboxesno[]" value="<?php print $tips[0] ?>" />
<a class="names"> - <span><?php print $tips[0] ?></span></a><br />
<? $i++;
}
?>
and del.php :
foreach($_POST['checkboxes'] as $check) {
mysql_query("INSERT INTO approved (body) VALUES ('$check') ");
mysql_query("UPDATE tips SET approved='yes' WHERE body='$check'");
}
foreach($_POST['checkboxesno'] as $key) {
mysql_query("DELETE FROM tips WHERE body='$key' ")or die(mysql_error());
}
mysql_error() doesn't throw any errors. Database connection works in both files. The values of the checkboxes are strings. I'm able to delete the record by adding the string itself rather than the POST $variable to the query.
(I have also noticed that I'm not able to delete older records, only the newly added ones).
UPDATE:
I realized that trying to delete records where row='string' wasn't the best practice, at least in my case. So, instead of passing strings as values to the checkboxes in the form, I decided to give the id value of the table.
here is the new code:
<?php
$gettips = mysql_query('SELECT id,body FROM tips WHERE body!="" and approved!="yes" and approved!="no"')or die(mysql_error());
$i=0;
while($tips = mysql_fetch_array($gettips))
{ ?>
<input type="checkbox" name="checkboxes[]" value="<?php print $tips[0] ?>" />
<input type="checkbox" name="checkboxesno[]" value="<?php print $tips[0] ?>" />
<a class="names"> - <span><?php print $tips[1] ?></span></a><br />
<? $i++;
}
?>
and the delete queries:
foreach($_POST['checkboxes'] as $check) {
// echo "INSERT INTO approved (body) VALUES ('$check') <br>";
// echo "UPDATE tips SET approved='yes' WHERE body='$check'<br>";
mysql_query("INSERT INTO approved (body) VALUES ('$check') ");
mysql_query("UPDATE tips SET approved='yes' WHERE body='$check'");
}
foreach($_POST['checkboxesno'] as $key) {
// echo "DELETE FROM tips WHERE id=$key <br>";
mysql_query("UPDATE tips SET approved='no' WHERE id=$key");
mysql_query("DELETE FROM tips WHERE id=$key ")or die(mysql_error());
}
I still don't know why the other way wasn't working, so if someone out there has a chance to explain, it would be awesome!
If you add some echo statements to your forloops and comment out the queries, you'll be able to see what exactly is being sent to mysql, and then you'll be better able to solve your problem.
foreach($_POST['checkboxes'] as $check) {
echo "INSERT INTO approved (body) VALUES ('$check') <br>";
echo "UPDATE tips SET approved='yes' WHERE body='$check'<br>";
//mysql_query("INSERT INTO approved (body) VALUES ('$check') ");
//mysql_query("UPDATE tips SET approved='yes' WHERE body='$check'");
}
foreach($_POST['checkboxesno'] as $key) {
echo "DELETE FROM tips WHERE body='$key' <br>";
//mysql_query("DELETE FROM tips WHERE body='$key' ")or die(mysql_error());
}
Try and protect yourself from SQL Injections: http://php.net/manual/en/security.database.sql-injection.php, can you please output the exact generated SQL query, it may be because of the SQL string not escaped.
Try escaping it with mysql_real_escape_string();
I'm building a website where people can place orders and this is the first time I've had to insert multiple rows at a time and I'm lost. I know that I need a FOR loop to perform this, but I'm lost as to how to construct the loop. I'm using PHP, MySQL (obviously) with jQuery. I'm using the jQuery to .append() a new select box into the form to allow the client to choose another item.
This is how I usually construct my code to allow users to insert into the database. My question is how and where would I insert a loop that way multiples rows can be submitted all at once without having to insert them one by one. Anything would be helpful, thank you.
<?php
if (isset($_POST['submit'])) {
if (!$_POST['col1'] | !$_POST['col2'] | !$_POST['col3']) { die ("error"); }
if (!get_magic_quotes_gpc()) {
$_POST['col1'] = addslashes ($_POST['col1']);
$_POST['col2'] = addslashes ($_POST['col2']);
$_POST['col3'] = addslashes ($_POST['col3']);
}
$insert = "insert into table (col1, col2, col3) values ('".$_POST['col1']."', '".$_POST['col2']."', '".$_POST['col3']."')";
mysql_query ($insert);
} else {
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<table>
<tr>
<td><input type="text" name="col1"></td>
<td><input type="text" name="col2"></td>
<td><input type="text" name="col3"></td>
//I'm using jQuery .append() to insert more text boxes with names (col1, col2, col3) here
</tr>
</table>
<input type="submit" name="submit" value="Submit">
</form>
<?php
}
?>
My confusion is where to put the loop... I know it should be a FOR loop, but I could never get one to work. Thanks again for any help.
Be sure you name your inputs uniquely. But you can name every column like this (see here for example):
<input type="text" name="column1[]" />
<input type="text" name="column2[]" />
<input type="text" name="column3[]" />
That way you can access the columns via PHP using a for loop.
for($i = 0; $i < $n; $i++) // If you have $n rows
{
echo($_POST["column1"][$i]);
echo($_POST["column2"][$i]);
echo($_POST["column3"][$i]);
}
To insert multiple rows into your mySQL database use the following syntax (also: see here).
INSERT INTO
tbl_name (column1, column2, column3)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
Now you should be set to build your SQL query.
First thing you want to avoid is use same set of names. You may want to name them rowNcolM and then extract them where you check post variables.