PHP mysql trouble adding data to table - php

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')";

Related

PHP Array to string to mysql - empty record

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.

Deleting records inside a foreach loop

I have an array that I am passing through a $_POST variable. In the foreach loop, I would like to check to see if "delete" has been checked. If so, I will delete the record. If delete is not checked, I will update the record. When I run this the update works perfect. If I have delete checked - it will delete the first record in the array - not the record with the corresponding id of the record with the checked box. If I have 2 checked - it will take the first 2. If I have them all checked - it will obviously then delete all the records. I have been wrestling with this one all day - looking for a little help. Thanks.
if (isset($_POST['update'])) {
$slo_id = $_POST['slo_id'];
foreach ($_POST['score_id'] as $key=>$score_id) {
$del = $_POST['del'][$key];
if ($del == 'checked') {
$sql2 = " DELETE FROM slo_score WHERE score_id = $score_id ";
#execute SQL statement
$result = mysql_query($sql2);
# check for error
if (mysql_error()) { print "Database ERROR in SQL Update Statement: " . mysql_error(); }
}
else {
$growth_target = $_POST['growth_target'][$key];
$final_score = $_POST['final_score'][$key];
$meets = $_POST['meets'][$key];
//update table
$sql1 = "UPDATE slo_score SET growth_target='$growth_target',final_score='$final_score',meets='$meets' WHERE score_id = $score_id";
#execute SQL statement
$result = mysql_query($sql1);
# check for error
if (mysql_error()) { print "Database ERROR in SQL Update Statement: " . mysql_error(); }
}
}
header("location:...);
}
try this
if (isset($_POST['update'])) {
$slo_id = $_POST['slo_id'];
foreach ($_POST['score_id'] as $key=>$score_id) {
if (isset($_POST['del'][$key])) {
//use mysqli to delete the record
}
else {
$growth_target = $_POST['growth_target'][$key];
$final_score = $_POST['final_score'][$key];
$meets = $_POST['meets'][$key];
//update table
use mysqli to update the record
}
}
header("location:...);
}
You should avoid looping deletes to MySQL at all costs.
If you are receiving an array of IDs to delete, why not just send that in one (or a few, if this is thousands of IDs we're talking about; chunk them) query:
$score_ids = isset($_POST['score_id']) ? $_POST['score_id'] : array();
$score_ids_in = implode("', '", $score_ids);
$sql = sprintf("DELETE FROM slo_score WHERE score_id IN ('%s')", $score_ids_in);
$result = mysql_query($sql);
Of course, this won't give you line by line feedback but it will keep your database from being choked to death.
Also, you already know you should use Mysqli to keep people from destroying your database, extracting sensitive data from it, or both. It's not a huge change from what you're doing now, except it's a lot more secure.

outside of foreach loop query doesn't work properly

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.

MySQL & PHP Insert Query Failing

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

How to do a INSERT with two different loops?

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.

Categories