Update
I have updated my code according to phant0m's suggestion. It still doesn't quite work yet, though: question_id is always 0 in the database, even though it's not in the array:
var_dump($_POST['question_id'])
array(2) { [0]=> string(2) "22" [1]=> string(2) "23" }
The query:
string(122) "INSERT INTO student_score(course_uid, student_uid, question_uid, answer) VALUES
(1, 4, 0, 'answer1'),
(1, 4, 0, 'answer4')
This is the new code:
$sql_data = array();
$sql_prefix = "INSERT INTO student_score(course_uid, student_uid, question_uid, answer) VALUES";
foreach($_POST['answer'] as $id => $answer){
// don't use $_REQUEST!
$course_id = (int) $_POST['course_id'][$i];
$student_id = (int) $_POST['student_id'][$i];
$question_id = (int) $_POST['question_id'][$i];
$answer = mysql_real_escape_string($answer);
$sql_data[] = "($course_id, $student_id, $question_id, '$answer')";
}
$sql = $sql_prefix.implode(", \n", $sql_data);
var_dump($sql);
if(!mysql_db_query($dbName, $sql, $connect)){
$_SESSION['msg'] = "Could not save information, Please try again";
header("Location:student_assignment.php");
//replaced die with else clause
}
else{
$_SESSION['msg'] = "Question successfully created";
header("Location:student_assignment.php");
}
Initial question:
I have a problem adding the values of an array into a mysql database. The thing is
I have two loops and if I add the INSERT in one of the then the other one gives the wrong value. But if I echo inside each loop it gives the right values.
At the moment it adds two double rows of each value where I only want one row of each value.
Here is my code:
<?php
require_once("settings.inc.php");
// require_once("student_session.inc.php");
session_start();
for ($d = 0; $d <= count($_POST[answer]); $d++) {
$answer = $_POST[answer][$d];//I want to insert this value
//echo $answer;
$ids = $_REQUEST['question_id'];
foreach ($ids as $value) {
//echo $value; //and this value into the INSERT
$sql = "INSERT INTO student_score(answer) VALUES ('$answer')";
$results = mysql_db_query($dbName, $sql, $connect);
}
}
if (!$results) {
$_SESSION['msg'] = "Could not save information, Please try again";
header("Location:student_assignment.php");
die;
}
$_SESSION['msg'] = "Question successfully created";
header("Location:student_assignment.php");
die;
?>
You're using the wrong variable:
"INSERT INTO student_score(answer) VALUES ('$answer')";
You comment that the variable you'd like inserted is called $value, so you meant to write:
"INSERT INTO student_score(answer) VALUES ".
"('".mysql_real_escape_string($value)."')";
(mysql_real_escape_string is to prevent SQL injection attacks)
make use of MySQL transactions:
PHP + MySQL transactions examples
Also can you post the output of the following?:
print_r($_POST); and print_r($_POST[answer]);
Using $_REQUEST is bad Idea. either use POST or GET explicitly!
Your code does not make much sense.
This might more closely resemble what you want it to do:
// you will not want <=, that will create an index error upon the last
// iteration, also, you need to quote the key!
// This is fixed:
//for ($d = 0; $d < count($_POST['answer']); $d++) {
// this is a better way
// this assumes, that the indices of the POST array nicely correspond with each
// other.
$sql_data = array();
$sql_prefix = "INSERT INTO student_score(question_id, student_id, course_id, answer) VALUES";
foreach($_POST['answer'] as $id => $anwer){
// don't use $_REQUEST!
$question_id = (int) $_POST['question_id'][$i];
$student_id = (int) $_POST['student_id'][$i];
$course_id = (int) $_POST['course_id'][$i];
$answer = your_escape_function($answer)
$sql_data[] = "($question_id, $student_id, $course_id, '$answer')";
}
$sql = $sql_prefix.implode(", \n", $sql_data);
if(!mysql_db_query($dbName, $sql, $connect)){
$_SESSION['msg'] = "Could not save information, Please try again";
header("Location:student_assignment.php");
//replaced die with else clause
}
else{
$_SESSION['msg'] = "Question successfully created";
header("Location:student_assignment.php");
}
Attention
This code is mostly based on guesswork and assumptions what you want it to do.
You need to have a function that properly escapes your code based on whether magic_quotes are enabled. Simply calling mysql_real_escape_string()as suggested in the other answer is incorrect.
Please note that mysql_* functions are outdated. Consider using parameterized queries using PDOs or myqsli.
PS: do not use $_REQUEST.
Related
I am on point where I have to usk on forum.
So, I have an array that is my return from join table sql query.
i am displaying it correctly without the problem.
but some of those values I want to put in different table of mysql database.
$array = joint_table();
$array_value = array['key'];
I can echo array_value and it's displaying correctly, also checked variable type and it returns STRING.
however when I am inserting it into the table, it's empty cell.
I am inserting other stuff like date() and such and that is inserted correctly.
So my sql query works fine, besides I am using same query in other places without problem.
Only values I have from that array are not inserting, but still can echo them.
<?php
$page_title = 'Complete Task';
require_once('includes/load.php');
// Checkin What level user has permission to view this page
page_require_level(2);
$task = join_task_table((int)$_GET['id']);
?>
<?php
if(isset($_POST['complete_task'])){
$area = $task['area'] ;
$jig = $task['jig'];
$desc = $task['description'];
$freq = $task['freq'];
$date = make_date();
$user = current_user();
$user_done = remove_junk(ucfirst($user['name']));
$comment = remove_junk($db->escape($_POST['comment']));
if(empty($errors)){
$sql = "INSERT INTO tpm_history (area_name,jig_name,description,frequency,date_done,done_by_user,comment)";
$sql .= " VALUES ('{$area}','{$jig}','{$desc}','{$freq}','{$date}','{$user_done}','{$comment}')";
$result = $db->query($sql);
if($result && $db->affected_rows() === 1){
$session->msg('s',"Job Completed");
redirect('home.php', false);
} else {
$session->msg('d',' Sorry failed to complete the task!');
redirect('task_complete.php?id='.$task['id'], false);
}
} else{
$session->msg("d", $errors);
redirect('task_complete.php?id='.$task['id'],false);
}
}
?>
I am lost. Help.
Here I'm trying to insert the datas again into database new table (with quantity & customer details). $grocery_id and $grocery_item values are fetch from database. $customername, $customermobile, $groqty values are user will enter the details in that appropriate textfield.
When I execute this code ($groceryid, $groceryitem) -> These two column always stored the last row values. Because I've put the query outside of foreach loop. Here is my problem. If I put the query inside the foreach it works fine. But, quantity values doesn't work properly. So, How can I execute the query properly (outside of foreach loop)?
<?php
if(isset($_POST['submit']))
{
$grocery_id = $rowid;
$grocery_item = $rowsitem;
$customername = $_POST['customername'];
$customermobile = $_POST['customermobile'];
$groqty = $_POST['groceryquantity'];
for($i = 0; $i < sizeof($groqty); $i++)
{
$groqtys = $groqty[$i];
foreach($grocery_id as $key => $index_id )
{
}
$sql = "INSERT INTO ".customer_order." SET grocery_id = '$index_id' , grocery_item = '$grocery_item[$key]', customername = '$customername', customermobile = '$customermobile', quantity = '$groqtys' ";
mysql_query($sql,$CN);
$response = asort_form_ok("Your order successfully submitted. We will deliver you soon.");
}
}
?>
You could simply use one foreach loop considering the index values of $grocery_id and $groqty are the same.
Try:
<?php
if (isset($_POST['submit']))
{
$grocery_id = $rowid;
$grocery_item = $rowsitem;
// sanitizing your values
$customername = mysql_real_escape_string($_POST['customername']);
$customermobile = mysql_real_escape_string($_POST['customermobile']);
$groqty = array_map('mysql_real_escape_string', $_POST['groceryquantity']);
foreach($grocery_id as $key => $index_id)
{
$sql = "INSERT INTO " . customer_order . " SET grocery_id = '$index_id' , grocery_item = '$grocery_item[$key]', customername = '$customername', customermobile = '$customermobile', quantity = '$groqty[$key]' ";
mysql_query($sql, $CN);
$response = asort_form_ok("Your order successfully submitted. We will deliver you soon.");
}
}
?>
Also note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
I am trying to make a script to check if an int is already added to my database. If so, it will re-generate another random number and check again. If it doesn't exist, it'll insert into the database.
However, I am having troubles. If a number exists, it just prints out num exists, how would I re-loop it to check for another and then insert that? I have tried to use continue;, return true; and so on... Anyway, here is my code; hopefully someone can help me!
<?php
require_once("./inc/config.php");
$mynum = 1; // Note I am purposely setting this to one, so it will always turn true so the do {} while will be initiated.
echo "attempts: ---- ";
$check = $db->query("SELECT * FROM test WHERE num = $mynum")or die($db->error);
if($check->num_rows >= 1) {
do {
$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')")or die($db->error);
echo "$newnum - CAN INSERT#!#!#";
break;
}
} while(0);
}
?>
I think the logic you're looking for is basically this:
do {
$i = get_random_int();
} while(int_exists($i));
insert_into_db($i);
(It often helps to come up with some functions names to simplify things and understand what's really going on.)
Now just replace the pseudo functions with your code:
do {
$i = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $i")or die($db->error);
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
$db->query("INSERT test (num) VALUES ('$i')") or die($db->error);
Of course, you can do a little more tweaking, by shortening...
// ...
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
...to:
// ...
$int_exists = $newcheck->num_rows >= 1;
} while($int_exists);
(The result of the >= comparison is boolean, and as you can see, you can assign this value to a variable, too, which saves you 4 lines of code.)
Also, if you want to get further ahead, try to replace your database calls with actual, meaningful functions as I did in my first example.
This way, your code will become more readable, compact and reusable. And most important of all, this way you learn more about programming.
The logic is incorrect here. Your do-while loop will get executed only once (as it's an exit-controlled loop) and will stop on the next iteration as the while(0) condition is FALSE.
Try the following instead:
while($check->num_rows >= 1) {
$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if ($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')") or die($db->error);
echo "$newnum - CAN ISNERT#!#!#";
break;
}
}
Sidenote: As it currently stands, your query is vulnerable to SQL injection and could produce unexpected results. You should always escape user inputs. Have a look at this StackOverflow thread to learn how to prevent SQL injection.
Here is an example of some code that I threw together using some of my previously made scripts. You will notice a few changes compared to your code, but the concept should work just the same. Hope it helps.
In my example I would be pulling the database HOST,USER,PASSWORD and NAME from my included config file
require_once("./inc/config.php");
echo "attempts: ---- ";
$running = true;
while($running == true) {
//create random number from 1-5
$newnum = rand(1,5);
//connect to database
$mysqli = new mysqli(HOST, USER, PASSWORD, NAME);
//define our query
$sql = "SELECT * FROM `test` WHERE `num` = '".$$newnum."'";
//run our query
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//check results, if num_rows >= our number exists
if (mysqli_num_rows($check_res) >= 1){
echo $newnum . " exists! \n";
}
else { //our number does not yet exists in database
$sql = "INSERT INTO `test`(`num`) VALUES ('".$newnum."')";
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
if ($check_res){
echo $newnum . " - CAN ISNERT#!#!#";
// close connection to datbase
mysqli_close($mysqli);
}
else{
echo "failed to enter into database";
// close connection to database
mysqli_close($mysqli);
}
break;
}
}
I would also like to note that this will continue to run if all the numbers have been used, you may want to put in something to track when all numbers have been used, and cause a break to jump out of the loop.
Hope this helps!
I am fairly new at php and I have been trying to insert a series of variables into a mysql database. However, it seems that while the table is being created the data isn't getting entered into the table. I was hoping that someone could tell me why. Any help would be much appreciated.
The php code:
<?php
$team = $_POST['team'];
$int1 = $_POST['int1'];
$int2 = $_POST['int2'];
$int3 = $_POST['int3'];
$int4 = $_POST['int4'];
$int5 = $_POST['int5'];
$int6 = $_POST['int6'];
$int7 = $_POST['int7'];
$int8 = $_POST['int8'];
$int9 = $_POST['int9'];
$int10 = $_POST['int10'];
$int11 = $_POST['int11'];
$int12 = $_POST['int12'];
$int13 = $_POST['int13'];
$int14 = $_POST['int14'];
$con=mysqli_connect("127.0.0.1:3306","root","password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sqli="CREATE TABLE $team(int1 INT,int2 INT,int3 INT,int4 INT,int5 INT,int6 INT,int7 INT,int8 INT,int9 INT,int10 INT,int11 INT,int12 INT,int13 INT,int14 INT)";
if (mysqli_query($con,$sqli))
{
echo "<br />Table created successfully";
}
else
{
echo "<br />Error creating table: " . mysqli_error();
}
$sql="INSERT INTO $team (int1, int2 ,int3 ,int4 ,int5 ,int6 ,int7 ,int8 ,int9 ,int10 ,int11 ,int12 ,int13 ,int14 )
VALUES ($int1,$int2,$int3,$int4,$int5,$int6,$int7,$int8,$int9,$int10,$int11,$int12,$int13,$int14)";
if (mysqli_query($con,$sql))
{
echo "<br />Record added";
}
else
{
echo "<br />Error adding record";
}
?>
Firstly, you should never insert $_POST values directly into a database, without using strip_tags, htmlentities or some other function to get rid of possible malicious code.
Secondly, I'd recommend looking at the MySQL docs for the proper syntax for creating tables. http://dev.mysql.com/doc/refman/5.1/en/create-table.html
Firstly,its a big security risk to insert data without sanitization(validation).
Secondly, make use of mysqli_error http://php.net/manual/en/mysqli.error.php in php to log or print the error.
because you are inserting data without validation, if any of the variable in $int1.... $int14 is blank or not filled from the form which is requesting the script, your sql query becomes incorrect and fail by generating some sort of syntax error, can be traced using mysqli_error as discussed above.
if (mysqli_query($con,$sql))
{
echo "<br />Record added";
}
else
{
echo "<br />Error ".mysqli_error($con);
}
to see what may become wrong when any of the field is left blank, consider
the values submitted as:
$team = 'tbl_team';
$int1 = 1;
$int2 = 2;
$int3 = 3;
$int4 = 4;
$int5 = '';
$int6 = 6;
$int7 = 7;
$int8 = 8;
$int9 = 9;
$int10 = '';
$int11 = 11;
$int12 = 12;
$int13 = 13;
$int14 = 14;
now see what happens to your sql query if we print it in this case:
$sql="INSERT INTO $team
(int1, int2 ,int3 ,int4 ,int5 ,int6 ,int7 ,
int8 ,int9 ,int10 ,int11 ,int12 ,int13 ,int14 )
VALUES
($int1,$int2,$int3,$int4,$int5,$int6,$int7,
$int8,$int9,$int10,$int11,$int12,$int13,$int14)";
print $sql
will result in:
INSERT INTO tbl_team (int1, int2 ,int3 ,int4 ,int5 ,int6 ,int7 ,int8 ,int9 ,int10 ,int11 ,int12 ,int13 ,int14 )VALUES (1,2,3,4,,6,7,8,9,,11,12,13,14)";
which is by the way a SQL syntax problem.
if you are totally a newbie and have not understood a word yet, you may try to use the following line of code as replacement in your original to have better chances.
$sql="INSERT INTO $team (int1, int2 ,int3 ,int4 ,int5 ,int6 ,int7 ,
int8 ,int9 ,int10 ,int11 ,int12 ,int13 ,int14 )
VALUES
('$int1','$int2','$int3','$int4','$int5','$int6','$int7',
'$int8','$int9','$int10','$int11','$int12','$int13','$int14')";
I know there isn't enough validation in here just going through some testing. $result always returns empty? Is my query bad? I'm new to PHP and concatenating variables into strings is not something I have grasped full. Going with the OOP form since I'm pretty familiar with it and the concepts.
Also, I know this code is terribly sloppy... just trying to dive right in =)
`
$page = new Page();
$page->title = "Add a New Item";
$page->DisplayHeader();
$page->DisplaySidebar();
if (isset($_POST['submit']))
{
// make short variable names
$name = trim($_POST['name']);
$level = intval($_POST['level']);
$slot = strtolower($_POST['slot']);
$hp = intval($_POST['hp']);
$mana = intval($_POST['mana']);
$mvs = intval($_POST['mvs']);
$int = intval($_POST['int']);
$wis = intval($_POST['wis']);
$str = intval($_POST['str']);
$dex = intval($_POST['dex']);
$con = intval($_POST['con']);
$p_ac = intval($_POST['p_ac']);
$m_ac = intval($_POST['m_ac']);
$saves = intval($_POST['saves']);
$hit = intval($_POST['hit']);
$dam = intval($_POST['dam']);
$queryOk = 1;
if (empty($name) || empty($level) || empty($slot))
{
echo '<h3>Please enter all the required fields</h3>';
$queryOk = 0;
}
// Instantiate database object and connect
# $db = new mysqli('*host*', '*user*', '*pass*', '*database*');
// Check connection to
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database, try again later';
}
$query = "INSERT INTO items (name, level, slot, hp, mana, mvs, int, wis, str, dex, con, p_ac, m_ac, saves, hit, dam)".
"V ALUES ('$name', $level, '$slot', $hp, $mana, $mvs, $int, $wis, $str, $dex, $con, $p_ac, $m_ac, $saves, $hit, $dam)";
$result = $db->query($query);
if (!$result)
{
echo '<h3>Error: Item was not entered. (Your webmaster sucks)</h3>';
}
else {
echo "<p>The items \"$name\" was successfully entered into the database. <a href=\"equipment.php\>Back to Equipment or add another item.</a></p>";
}
$db->close();
}`
If the space in V ALUES is actually in your code that would cause your query to fail
UPDATE
If that isn't the cause of the error use $mysqli->error to see what error occurred.
if (!$result)
{
echo '<h3>'$mysqli->error' (Your webmaster sucks)</h3>';
}
int is a reserved word in mysql, and you're using it as a fieldname. You'll have to escape it with backticks:
INSERT INTO ... (..., `int`, ...)
^---^-- escapes
your query:
INSERT INTO items (name, level, slot, hp, mana, mvs, int, wis, str, dex, con, p_ac, m_ac, saves, hit, dam)
^^^^--- problem here
VALUES ('$name', $level, '$slot', $hp, $mana, $mvs, $int, $wis, $str, $dex, $con, $p_ac, $m_ac, $saves, $hit, $dam)";
^^^^^---NOT here