$link = mysqli_connect("localhost", "root", "", "jeetu") or die("Error " . mysqli_error($link));
if (isset($_POST['ok'])) {
$n = $_POST['name[]'];
$c = $_POST['contact[]'];
$a = $_POST['address[]'];
$count = count($n);
for ($i = 0; $i <= $count; $i++) {
print_r($n[$i]);
print_r($c[$i]);
print_r($a[$i]); die();
$query = "insert into add (name, contact, value) values ('" . $_POST['name[$i]'] . "'," . $_POST['contact[$i]'] . ",'" . $_POST['address[$i]'] . "')";
mysqli_query($link, "$query");
}
}
If you're using a form to input this data into a database there is no way your code will work since you're getting data from one form and not from many forms.
$count = count($n); will always return 1 because you are getting one name from the form. It only works if you're reading the data from the database.
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);
I want to create an array or variables that can be inserted into the sql query instead of do it manually like in my code below.
Is this possible with the simple php, not using PDO, just some kind of trick that will solve this issue.
You can see that I manually inserted 10 columns and 10 values, can I do it shorter?
So, I want to have a variable/array that will consist pt1-pt10 and another that will be consisted of a[1]-a[10].
for($j=1;$j<11;$j++) {
$a[$j] = "";
}
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'my_db';
$table = 'jos_answers';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("INSERT into ".$table."(id, title, pt1, pt2, pt3, pt4, pt5, pt6, pt7, pt8, pt9, pt10) VALUES ((select id from jos_content where title='$title'),'$title','$a[1]','$a[2]','$a[3]','$a[4]','$a[5]','$a[6]','$a[7]','$a[8]','$a[9]','$a[10]')");
?>
for($j=1;$j<11;$j++) {
$a["pt".$j] = $j;
}
"INSERT into ".$table. "(id, title,".implode(",", array_keys(a)).") VALUES ((select id from jos_content where title='$title'),'$title',".implode(",", array_values(a)).")";
Try this:
$insert = "INSERT INTO" . $table . "(id, title,";
$value = " VALUES((select id from jos_content where title='$title'),'$title',";
for($x = 1; $x < 11; $x++){
$insert .= " pt" . $x . ",";
$value .= " '$a[" . $x . "]'," //this line is iffy....
}
$insert = substr($insert, 0, -1);//to remove last comma
$value = substr($value, 0, -1);//to remove last comma
$insert .= ")";//final paren
$value .= ")";//final paren
$sql = $insert . $value; //combine parts
$result = mysql_query($sql);
The reason I think that line is iffy is becuase the ' ' surronding the varibles kinda confuses me. Do you want the varibles value to be inserted to the DB? If so I would go with this line instead:
$values .= " " . $a[$x] . ",";
If you want the ' and the values go with this:
$values .= " '" . $a[$x] . "',";
Here is a working example of the code edited a bit obviously because it is not in your SQL environment and you did not give us all the variable values: http://viper-7.com/cDAcRl
Good Luck!
I have tried several different methods of implementation for this and can't seem to get the last little bit correct. The most efficient is obviously the best scenario but at this point it's second to getting it working.
I'm attempting to pull data from the Syspro connection and inserting it into the MySQL connection. I don't need to print anything with this code, just simply insert into the MySQL database.
//MySQL Connection
$mysqlcon=mysqli_connect("localhost","root","","production");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Syspro connection
$conn=odbc_connect('syspro','','');
if (!$conn)
{exit("Connection Failed: " . odbc_error());}
//Warehouse valuation for S6/SX/SN/SW
$sql_warehouses=
"SELECT SysproCompanyJ.dbo.InvWarehouse.Warehouse, SUM(UnitCost * QtyOnHand) AS 'Value'
FROM SysproCompanyJ.dbo.InvWarehouse
WHERE SysproCompanyJ.dbo.InvWarehouse.QtyOnHand > '0'
AND SysproCompanyJ.dbo.InvWarehouse.Warehouse NOT LIKE 'A_'
AND SysproCompanyJ.dbo.InvWarehouse.Warehouse = 'S6'
OR Warehouse = 'SX'
OR Warehouse = 'SN'
OR Warehouse = 'SW'
GROUP BY Warehouse";
$test = array();
$i=0;
$rs=odbc_exec($conn,$sql_warehouses);
if (!$rs)
{exit("Error in SQL");}
while ($row = odbc_fetch_array($rs)) {
//echo $row['Warehouse'] . ':' .$row['Value'];
array_push($test,$row['Warehouse'],$row['Value']);
//echo mysqli_query($mysqlcon,"INSERT INTO inv_valuation (warehouse, value)
//VALUES ({$row['Warehouse']} ,{$row['Value']})");
}
for($i = 0, $size = count($test); $i < $size; ++$i) {
//echo "WH=" . $test[$i] . ", $=" . $test[++$i];
mysqli_query($mysqlcon,"INSERT INTO inv_valuation (warehouse, value)
VALUES ($test[$i] ,$test[++$i])");
}
//print_r($test);
//var_dump($test);
//echo count($test);
Well, I would do this way:
while ($row = odbc_fetch_array($rs)) {
mysqli_query($mysqlcon,"INSERT INTO inv_valuation (warehouse, value)
VALUES ('" . $row['Warehouse'] . "', '" . $row['Value'] . "')");
}
No need to loop again (as you previously tried :) )
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