I need to save the values from my dynamic textbox in different tables at the same time. Can someone help me do this? I have 4 tables that needs to be filled. This is my tables and its fields:
table1
- desk_id
- desk_user
- desk_report
- desk_action
table2
- print_id
- print_brand
- print_model
- print_report
- print_action
table3
- tel_id
- tel_local
- tel_user
- tel_report
- tel_action
table4
- remarks_id
- remarks
My PHP code:
<?php
$con = mysql_connect ("localhost","root","nasi") or die
('cannot connect to database error: '.mysql_error());
if (isset($_POST['desk_user']) &&
isset($_POST['desk_report']) &&
isset($_POST['desk_action']) &&
isset($_POST['print_brand']) &&
isset($_POST['print_model']) &&
isset($_POST['print_report']) &&
isset($_POST['print_action']) &&
isset($_POST['tel_local']) &&
isset($_POST['tel_user']) &&
isset($_POST['tel_report']) &&
isset($_POST['tel_action']) &&
isset($_POST['remarks']))
{
$desk_user = $_POST['desk_user'];
$desk_report = $_POST['desk_report'];
$desk_action = $_POST['desk_action'];
$print_brand = $_POST['print_brand'];
$print_model = $_POST['print_model'];
$print_report = $_POST['print_report'];
$print_action = $_POST['print_action'];
$tel_local = $_POST['tel_local'];
$tel_user = $_POST['tel_user'];
$tel_report = $_POST['tel_report'];
$tel_action = $_POST['tel_action'];
$remarks = $_POST['remarks'];
if (!empty($desk_user)&& !empty($desk_report)&& !empty($desk_action) && !empty($print_brand) && !empty($print_model) && !empty($print_report) && !empty($print_action) && !empty($tel_local) && !empty($tel_user) && !empty($tel_report) && !empty($tel_action) && !empty($remarks)) {
mysql_select_db("csr", $con);
$queries = array();
for($i=0; $i<count($desk_user || $print_brand || $tel_local || $remarks); $i++)
{
$queries [] = "('" .$desk_user [$i ] . "', '" .$desk_report [$i ] . "', '" .$desk_action [$i ] . "')" ;
$queries1 [] = "( '" .$print_brand [$i ] . "', '" .$print_model [$i ] . "', '" .$print_report [$i ] . "', '" .$print_action [$i ] . "')" ;
$queries2 [] = "('" .$tel_local [$i ] . "', '" .$tel_user [$i ] . "', '" .$tel_report [$i ] . "', '" .$tel_action [$i ] . "')" ;
$queries3 [] = "('" .$remarks [$i ] . "')" ;
}
if(count($queries) == 0)
{
# Nothing passed
# exit
}
$query = "insert into desktoplaptop (desk_user, desk_report, desk_action tel_local) values " . implode(", ", $queries) ;
$query1 = "insert into printer (print_brand, print_model, print_report, print_action) values " . implode(", ", $queries1) ;
$query2 = "insert into tel (tel_user, tel_report, tel_action) values " . implode(", ", $queries2) ;
$query3 = "insert into remarks (remarks) values " . implode(", ", $queries3) ;
if ($sql_run = mysql_query($query) || $sql_run = mysql_query($query1) || $sql_run = mysql_query($query2) || $sql_run = mysql_query($query3)) {
echo 'ok.';
}
else {
echo '*Sorry, we couldn\'t register you at this time. Try again later.';
}
}
}
?>
If there are four tables, there needs to be a unique INSERT statement for each one. With the code you provided, you only name one table: desktoplaptop
If there actually are four unique tables as suggested by your list above, you will need to write a unique INSERT statement which refers to each table's schema.
For example:
$queries = array();
if(!empty($desk_user)) {
$queries[] = "INSERT into desktop (desk_user, desk_report, desk_action) VALUES ('" . $desk_user . "', '" .$desk_report . "', '" . $desk_action . "')'";
}
repeat for other 3 tables
foreach($queries as $query) {
if ($sql_run = mysql_query($query)) {
echo 'ok.';
} else {
echo '*Sorry, we couldn\'t register you at this time. Try again later.';
}
}
Note that if you are taking input from a web form, you will also want to mysql_escape_string() each $_POST variable to prevent injection. In addition, it seems you are using the count() function incorrectly-- you are passing it a Boolean expression when it expects an array. Overall I would suggest taking another look over exactly how your code operates.
Do four INSERT as a loop?
$query[0] = "INSERT INTO TABLE1 (...) VALUES (...)";
$query[1] = "INSERT INTO TABLE2 (...) VALUES (...)";
//etc...
foreach ($query as $x)
{
if ($sql_run = mysql_query($x)) {
echo 'ok.';
} else {
echo '*Sorry, we couldn\'t register you at this time. Try again later.';
}
}
Related
I have a table which includes a row for each day of the week.
Each row contains 2 input fields.
I am wanting to click one save button which will update all rows from the table into seperate MySQL rows.
I have the below code to insert new rows (which works fine) but wondering how this can be changed to an UPDATE statement?
$insertArr = array();
for ($i=0; $i<$cnt; $i++) {
$insertArr[] = "('"
. mysql_real_escape_string($_GET['Actual'][$i]) .
"', '"
. mysql_real_escape_string($_GET['Period'][$i]) .
"', '"
. mysql_real_escape_string($_GET['AddedBy'][$i]) .
"', '"
. mysql_real_escape_string($_GET['Date'][$i]) .
"', '"
. mysql_real_escape_string($_GET['Employee'][$i]) .
"', '"
. mysql_real_escape_string($_GET['Rotered'][$i]) . "')";
}
$query = "INSERT INTO hr_employee_rostered_hours (Actual, PeriodID, AddedBy, DateOfHours, EmployeeUniqueID, Rotered) VALUES " . implode(", ", $insertArr);
mysql_query($query) or trigger_error("Insert failed: " . mysql_error());
}
The mysql extension has been deprecated in PHP, and I strongly advice against using it.
Assuming that you're still getting the values that you want to update using the array,
Here is a link about PDO (not official docummentation) that helped me out when I first started with PHP and PDO
Here's an example using PDO
$updateq = "UPDATE hr_employee_rostered_hours SET (Actual = :actualvalue, PeriodID = :periodid, AddedBy = :addedby,DateOfHours = :dateofhrs, Rotered = :rotered ) WHERE EmployeeUniqueID = :employeeid";
$updatex = $dbh->prepare($updateq);
$updatex->bindValue(":actualvalue",$insertArr[0]);
$updatex->bindValue(":periodid",$insertArr[1]);
$updatex->bindValue(":addedby",$insertArr[2]);
$updatex->bindValue(":dateofhrs",$insertArr[3]);
$updatex->bindValue(":periodid",$insertArr[5]);
$updatex->bindValue(":employeeid",$insertArr[4]);
$updatex->execute();
You can use this code to update in MySQL.
for ($i = 0; $i < count($insertArr); $i++){
$var_to_update = implode(", ", $insertArr[$i]);
$actual = $var_to_update[0];
$periodID = $var_to_update[1];
$addedby = $var_to_update[2];
$dateofhour = $var_to_update[3];
$employeeUniqueID = $var_to_update[4];
$rotered = $var_to_update[5];
$query = "UPDATE hr_employee_rostered_hours SET (Actual = $actual , PeriodID = $periodID, AddedBy = $addedby, DateOfHours = $dateofhour, EmployeeUniqueID = $employeeUniqueID, Rotered = $rotered) WHERE EmployeeUniqueID = $employeeUniqueID";
$result = mysql_query($sql);
if ($result === FALSE)
{
die(mysql_error());
}
}
I'm currently trying to compare two sets of returned values from user selects, but when I go to compare the data from the results, the elseif statement defaults, despite the information being clearly the opposite. It doesn't matter what the values are, the program always refers to the elseif. Any help would be very much appreciated. Thank you!
// DB Constant Defines
define('DB_NAME','NurseData');
define('DB_USER','root');
define('DB_PASSWORD','root');
define('DB_HOST','localhost');
$state1 = $_REQUEST['state1'];
$state2 = $_REQUEST['state2'];
$city1 = $_REQUEST['city1'];
$city2 = $_REQUEST['city2'];
$jobTitle1 = $_REQUEST['job1'];
$jobTitle2 = $_REQUEST['job2'];
function showerror() {
die("Error " . mysql_errno() . " : " . mysql_error());
}
$connection = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME, $connection) or die(mysql_error());
$query1 = "SELECT DISTINCT
TOT_EMP,
JOBS_1000,
A_MEAN,
A_PCT90
FROM Nurse_Local
WHERE PRIM_STATE='" . $state1 . "'
AND AREA_NAME='" . $city1 . "'
AND OCC_TITLE='" . $jobTitle1 . "'";
$query2 = "SELECT DISTINCT
TOT_EMP,
JOBS_1000,
A_MEAN,
A_PCT90
FROM Nurse_Local
WHERE PRIM_STATE='" . $state2 . "'
AND AREA_NAME='" . $city2 . "'
AND OCC_TITLE='" . $jobTitle2 . "'";
if (!($getPosts1 = mysql_query ($query1, $connection))) {
showerror();
}
if (!($getPosts2 = mysql_query ($query2, $connection))) {
showerror();
}
while($rows1 = mysql_fetch_array($getPosts1)) {
while($rows2 = mysql_fetch_array($getPosts2)) {
//Retrieve array values
for ($i1 = 0; $i1 < count($rows1); $i1++) {
for ($i2 = 0; $i2 < count($rows2); $i2++) {
//Assign array values
$tot_EMP1 = $rows1['TOT_EMP'];
$tot_EMP2 = $rows2['TOT_EMP'];
$jobs_PER1 = $rows1['JOBS_1000'];
$jobs_PER2 = $rows2['JOBS_1000'];
$a_MEAN1 = $rows1['A_MEAN'];
$a_MEAN2 = $rows2['A_MEAN'];
$A_PCT901 = $rows1['A_PCT90'];
$A_PCT902 = $rows2['A_PCT90'];
//Convert array values to numbers
$tot_EMP1 = 0 + $tot_EMP1;
$tot_EMP2 = 0 + $tot_EMP2;
//Functions for calculating differences
/*
function compareEMP1($diffEMP1) {
$diffEMP1 = $rows1['TOT_EMP'] - $rows2['TOT_EMP'];
return $diffEMP1;
}
function compareEMP2() {
$diffEMP2 = $rows2['TOT_EMP'] - $rows1['TOT_EMP'];
return $diffEMP2;
}
*/
}
}
if($tot_EMP1 > $tot_EMP2 || $tot_EMP2 < $tot_EMP1) {
echo $tot_EMP1;//"In " . $state1 . " there are " . compareEMP1() . " more jobs than in " . $state2;
}
elseif ($tot_EMP2 > $tot_EMP1 || $tot_EMP1 < $tot_EMP2) {
echo $tot_EMP2;//"In " . $state2 . " there are " . compareEMP2() . " more jobs than in " . $state1;
}
else {
echo "<p>There was a problem comparing the employment numbers.</p>";
}
}
}
Found the answer, it was because the "numbers" were being outputted as strings, and PHP wasn't recognizing them as numbers. I resolved it by first performing a str_replace on both $tot_EMP1 and $tot_EMP2 to remove the commas and then performing a intval() on both variables. This converts them to an integer, and the logic performs as desired. Now I will need to figure out how to add the commas back in and preserve the int status of the results.
The actual code that did the converting, but please keep in mind that my DB has the info stored as strings, so part of the problem was my own failure to properly store the data:
//Assign individual array values
$tot_EMP1 = $rows1['TOT_EMP'];
$tot_EMP2 = $rows2['TOT_EMP'];
$jobs_PER1 = $rows1['JOBS_1000'];
$jobs_PER2 = $rows2['JOBS_1000'];
$a_MEAN1 = $rows1['A_MEAN'];
$a_MEAN2 = $rows2['A_MEAN'];
$a_PCT901 = $rows1['A_PCT90'];
$a_PCT902 = $rows2['A_PCT90'];
//Convert individual array values to numbers
$tot_EMP1 = str_replace(",", "", $tot_EMP1);
$tot_EMP2 = str_replace(",", "", $tot_EMP2);
$tot_EMP1 = intval($tot_EMP1);
$tot_EMP2 = intval($tot_EMP2);
$jobs_PER1 = floatval($jobs_PER1);
$jobs_PER2 = floatval($jobs_PER2);
$a_MEAN1 = str_replace(",", "", $a_MEAN1);
$a_MEAN2 = str_replace(",", "", $a_MEAN2);
$a_MEAN1 = intval($a_MEAN1);
$a_MEAN2 = intval($a_MEAN2);
$a_PCT901 = str_replace(",", "", $a_PCT901);
$a_PCT902 = str_replace(",", "", $a_PCT902);
$a_PCT901 = intval($a_PCT901);
$a_PCT902 = intval($a_PCT902);
Well it seems I've found the problem.
Because the values for the fields where automatically produced by taking substrings of the names of an HTML form fields, one of the values was appearing as id (it can be seen in the echo I've posted bellow). The update as it seems, didn't fail but produced this unexpected behavior.
Thanks to all who tried to help and sorry for the stupid question.
After I execute an update statement like
UPDATE tablename SET field='value' WHERE field='value'
without ever touching my primary key, it change's value from what it was before to 0.
Any ideas?
MySQL Server version: 5.5.37-0+wheezy1
This is the code that generates the query
$query2 = "UPDATE student SET ";
foreach ($_POST as $the_key => $a_post_arg) {
if (strcmp($the_key, "student_password") === 0) {
//without activation
$a_post_arg = md5($a_post_arg);
//with activation
//$a_post_arg = "Not activated!";
}
if (strcmp($the_key, "student_registration_year") === 0)
$a_post_arg = $a_post_arg . "-00-00";
if (strcmp(substr($the_key, 0, 14), "student_stats_") === 0 || strcmp($the_key, "student_validationImageTextfield") === 0) {
$student_stats[$the_key] = $a_post_arg;
continue;
}
if (strcmp(substr($the_key, 0, 7), "student") === 0 && strcmp($the_key, "student_email_retype") !== 0 && strcmp($the_key, "student_password_retype") !== 0) {
if (strcmp($the_key, "student_email") !== 0) {
if (strcmp($the_key, "student_select_dept") === 0) {
$query2 .= "dept='" . addslashes($a_post_arg) . "', ";
} else if (strcmp($the_key, "student_semester") === 0) {
$query2 .= "studying_semester='" . addslashes($a_post_arg) . "', ";
} else if (strcmp($the_key, "student_father_name") === 0) {
$query2 .= "fathers_name='" . addslashes($a_post_arg) . "', ";
} else if (strcmp($the_key, "student_academic_id") === 0) {
$query2 .= "academicIDNumber='" . addslashes($a_post_arg) . "', ";
} else {
$query2 .= substr($the_key, 8) . "='" . addslashes($a_post_arg) . "', ";
}
}
}
}
$query2 .= "status='registered' WHERE email='" . $_POST['student_email'] . "';";
This is an echo of $query2. The PK for the table is the auto increment field id and the email field.
query 2 = UPDATE student SET name='Όνομα', surname='Επώνυμο', dob='1970-09-09',
fathers_name='Ονοματεπώνυμο πατέρα', mother_name='Ονοματεπώνυμο μητέρας',
nationality='Υπηκοότητα', adt='Α.Δ.Τ.', password='0cc175b9c0f1b6a831c399e269772661',
dept='biology', id='Αριθμός μητρώου', studying_semester='6', registration_year='2001-00-00',
atlas_id='1234', academicIDNumber='123456789012', perm_address_road='Οδός',
perm_address_number='Αριθμός', perm_address_area='Περιοχή/Πόλη', perm_address_PObox='Τ.Κ.',
perm_address_Country='Χώρα', study_address_road='Οδός', study_address_number='Αριθμός',
study_address_area='Περιοχή/Πόλη', study_address_PObox='Τ.Κ.', study_address_Country='Χώρα',
telephone='+305555555555', cellphone='+305555555555', fax='+305555555555', afm='Α.Φ.Μ.',
eforia='Δ.Ο.Υ.', amka='Α.Μ.Κ.Α.', amika='Α.Μ.ΙΚΑ', status='registered' WHERE email='20#send.com';
I am working on a php script that stores message ids (Msg_ID, Ref_ID) in their corresponding user account tables.
What I've is, the Msg_ID is properly written, but the Ref_ID is always blank.
How ever when I run the query separately it works, but doesn't work in the script for some odd reason.
Here is the code :
$qry = "SELECT Ref_ID FROM Chat WHERE Msg_ID = " .$MsgID. ")";
$resp = mysqli_query($con, $qry);
$xx = mysqli_fetch_array($resp);
$ref_id = $xx['Ref_ID'];
foreach ($Array as $user){
$query = "Insert into ".$user."(POST_ID, REF_ID) values ('". $MsgID . "', '" .$ref_id. "')";
mysqli_query($con, $query);
}
The $ref_id is always blank and as a result, the blank value is written to the respective database.
Some help with what is wrong will be helpful.
Here is the full code :
<?php
function PostMainThread($Heading, $Message, $Author, $MarkedList){
$con=mysqli_connect("mysql.serversfree.com", "u521497173_root", "123456", "u521497123_mydb");
$Array = explode(',', $MarkedList);
if (mysqli_connect_errno()){
$response["success"] = 0;
$response["message"] = "Connection Failed.";
echo json_encode($response);
}else{
here:$MsgID = rand(1, 9999999);
$query = "Insert into Chat(Msg_ID, Header, MsgBody, Author) values (". $MsgID . "," . "'" . $Heading . "' ," .
"'" . $Message . "', '". $Author . "')";
$result=mysqli_query($con, $query);
if (!$result){
goto here;
}else{
//Put the MsgID in the respective user tables.
$qry = "SELECT Ref_ID FROM Chat WHERE Msg_ID = " .$MsgID. ")";
$resp = mysqli_query($con, $qry);
$xx = mysqli_fetch_array($resp);
$ref_id = $xx['Ref_ID'];
foreach ($Array as $user){
$query = "Insert into ".$user."(POST_ID, REF_ID) values ('". $MsgID . "', '" .$ref_id. "')";
mysqli_query($con, $query);
}
$response["success"] = 1;
$response["message"] = "Submission successful.";
mysqli_close($con);
echo json_encode($response);
}
}
}
function PostReplyToThread($PostID, $Author, $Reply){
$con=mysqli_connect("mysql.serversfree.com", "u521497123_root", "123456", "u521497123_mydb");
if (mysqli_connect_errno()){
echo 2;
}else{
$query = "Insert into Chat(Msg_ID, Header, MsgBody, Author) values (". $PostID . "," . "'" . " " . "' ," .
"'" . $Reply . "', '". $Author . "')";
$result=mysqli_query($con, $query);
if ($result){
echo 3;
}else{
echo 4;
}
mysqli_close($con);
}
}
if (isset($_POST['what_to_do'])){
if ($_POST['what_to_do'] == 0){
if ((isset($_POST['Title'])) &&(isset($_POST['Body']))&&(isset($_POST['Marked']))&&(isset($_POST['_Author']))){
PostMainThread($_POST['Title'], $_POST['Body'], $_POST['_Author'], $_POST['Marked']);
}
}else if ($_POST['what_to_do'] == 1){
if ((isset($_POST['Thread_ID'])) &&(isset($_POST['Answer']))&&(isset($_POST['_Author']))){
PostReplyToThread($_POST['Thread_ID'], $_POST['_Author'], $_POST['Answer']);
}
}
}else{
$response["success"] = 0;
$response["message"] = "Unspecified action";
echo json_encode($response);
}
Definition of the Chat table :
Create table Chat(Ref_ID INT Auto_Increment, Msg_ID INT, Header varchar(50), MsgBody varchar(500
), Author varchar(30), Primary Key(Ref_ID, Msg_ID));
$xx = mysqli_fetch_array($resp);
Will only return a numerically indexed array, as in $xx[0], $xx[1].
To use the column names, you need to use:
$xx = mysqli_fetch_array($resp, MYSQLI_ASSOC);
Or the shorter version:
$xx = mysqli_fetch_assoc($resp);
As a side note, don't forget security, when inserting data that comes from outside the function and could possibly have a quotes or SQL, it needs to be escaped!
$Heading = mysqli_real_escape_string($con, $Heading);
Otherwise it will come back to bite you.
Hi I'm really new to php/mysql.
I'm working on a php/mysql school project with 39 fields all in all in a single table.
I want to shorten my codes especially on doing sql queries.
$sql = "INSERT into mytable ('field_1',...'field_39') Values('{$_POST['textfield_1']}',...'{$_POST['textfield_39']}')";
I don't know how to figure out this but , i want something like:
$sql = "Insert into mytable ("----all fields generated via loop/array----") Values("----all form elements genrated via loop/array---")";
Thank you in advance.
<?php
function mysql_insert($table, $inserts) {
$values = array_map('mysql_real_escape_string', array_values($inserts));
$keys = array_keys($inserts);
return mysql_query('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
}
?>
For example:
<?php`enter code here`
mysql_insert('cars', array(
'make' => 'Aston Martin',
'model' => 'DB9',
'year' => '2009',
));
?>
try this it i thhink it il work
You could use implode:
$sql = "
INSERT into mytable
('" . implode("', '", array_keys($_POST) . "')
VALUES
('" . implode("', '", $_POST . "')";
(This assumes the indices of the POST array are also the names of the db table fields)
However, this is extremely insecure since you would directly insert post data into the database.
So the least you should do beforehand is escape the values and make sure they are ok/valid table fields:
// Apply mysql_real_escape_string to every POST value
array_walk($_POST, "mysql_real_escape_string");
and
// Filter out all POST values with invalid indices
$allowed_fields = array('field_1', 'field_2', /* ... */ );
$_POST = array_intersect_key($_POST, $allowed_fields);
<?php
$sql = "Insert into mytable (";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "field_$i";
} else {
$sql .= "field_$i,";
}
}
$sql .= "Values(";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "'" . $_POST[textfield_$i] . "'";
} else {
$sql .= "'" . $_POST[textfield_$i] . "',";
}
}
?>
< ?php
$sql = "Insert into mytable (";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "field_$i";
} else {
$sql .= "field_$i,";
}
}
$sql .= "Values(";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
if(is_int($POST[textfield$i])){
$sql .= $POST[textfield$i];
}
else{
$sql .= "'" . $POST[textfield$i] . "'";
}
} else {
if(is_int($_POST[textfield_$i])){
$sql .= $_POST[textfield_$i] .",";
}
else{
$sql .= "'" . $_POST[textfield_$i] . "',";
}
}
}
?>
it will work for numeric values. you can insert numeric values in single quotes but some times it will create some problems