Create and insert variables into mysql from for loop using php - php

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!

Related

how to insert multiple record in databse using php

$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.

Update Multiple Rows at once MySQL

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());
}
}

Is it possible to add multiple rows in one field in a database using MySQL?

So my problem is that I want to add multiple members in one team, but I cannot seem to figure out how or whether if it is even possible to do so. Here is my code for you to get my question.
<?php
$tname = $_POST['tname'];
$maxnum = $_POST['maxnum'];
$host = "localhost";
$sqluname = "root";
$sqlpass = "";
$db = "teams";
$tablename = "team info";
$mem1 = $_POST['mem1'];
$mem2 = $_POST['mem2'];
$mem3 = $_POST['mem3'];
$mem4 = $_POST['mem4'];
$connect = mysqli_connect("$host","$sqluname","$sqlpass","$db") ;
if(mysqli_connect_errno())
{
echo "Problem". mysqli_connect_error();
}
$sql = "INSERT INTO teaminfo (TeamName,MaxNum,Members)
VALUES
('$tname','$maxnum','$mem1')";
/* Inside Members, I would like to add more than just $mem1, like $mem2, $mem3, $mem4.
*/
if(!mysqli_query($connect,$sql)){
die('Error: ' .mysqli_error($connect));
}
echo "Team is added";
mysqli_close($connect);
header("location: TeamDummyClient.html");
?>
$sql = "INSERT INTO teaminfo (TeamName,MaxNum,Members) VALUES";
$sql .= "('$tname','$maxnum','$mem1'),";
$sql .= "('$tname','$maxnum','$mem2'),";
$sql .= "('$tname','$maxnum','$mem3'),";
$sql .= "('$tname','$maxnum','$mem4')";
You should be escaping the strings before you insert their values to prevent SQL injections. Here's an example for one of the rows:
$sql .= "(
'" . mysqli_real_escape_string($tname) . "',
'" . mysqli_real_escape_string($maxnum) . "',
'" . mysqli_real_escape_string($mem1) . "'
),";

Why can't I get my chunks of pdf into the mysql database?

So, here is the code I'm trying to use to break up a big pdf file into chunks and store it in my database. Is there any reason why it isn't working. I've worked all day to figure it out and have gone in circles a bunch. Would appreciate any help! Thanks!
<?
$username="something";
$password="something";
$database="something";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die("Unable to select database");
$STARTFILE = 1;
$ONFILE = "file" . $STARTFILE;
while (isset($HTTP_POST_FILES["$ONFILE"])) {
// Try!
$SrcPathFile = $HTTP_POST_FILES["$ONFILE"]["tmp_name"];
$SrcFileType = $HTTP_POST_FILES["$ONFILE"]["type"];
$DstFileName = $HTTP_POST_FILES["$ONFILE"]["name"];
clearstatcache();
$time = filemtime($SrcPathFile);
$storedate = date("Y-m-d H:i:s", $time);
// File Processing
if (file_exists($SrcPathFile)) {
// Insert into file table
$SQL = "insert into tbldocuments(Type,Description,Size,DateTime) values ('";
$SQL .= $SrcFileType . "', '" . $DstFileName . "', " . filesize($SrcPathFile);
$SQL .= ", '" . $storedate . "')";
if (!$RES = mysql_query($SQL, $linkid)) {
die("Failure on insert to file table!");
}
$fileid = mysql_insert_id($linkid);
// Insert into the filedata table
$fp = fopen($SrcPathFile, "rb");
while (!feof($fp)) {
// Make the data mysql insert safe
$binarydata = addslashes(fread($fp, 65535));
$SQL = "insert into tblDocumentChunks (documentId,chunkData) values (";
$SQL .= $fileid . ", '" . $binarydata . "')";
if (!mysql_query($SQL, $linkid)) {
die("Failure to insert binary inode data row!");
}
}
fclose($fp);
}
$STARTFILE ++;
$ONFILE = "file" . $STARTFILE;
}
echo "Upload Complete";
?>
First of all, $HTTP_POST_FILES has been deprecated for quite a while. Use $_FILES instead.
Second, you're declaring a variable $ONFILE, but you're not referencing it in the array.
Try removing the quotes ($ONFILE instead of "$ONFILE")

complicated query entry mysql php

I'm having great trouble with "INSERT INTO"...
I have a variable part number so this my code...:
<?php
include ("db_conn.php");
$mem_id = "1";
$descript = "chair";
$qualifier = "sitting";
$major = "Y";
$value = "6";
//$mesh_cell_string = "tree_0,tree_1,tree_2,tree_3,tree_4";
//$mesh_values_string = "'C23','550','291','687','500'";
$part_number = "C23.550.291.687.500";
$parts = explode('.', $part_number);
$n = 0;
foreach ($parts as $something => $number)
{
$mesh_cell_string .= "tree_" . $n . ",";
$mesh_values_string .= "'" . $number . "'," ;
$n++;
}
$mesh_values_string = substr($mesh_values_string, 0, -1);
$mesh_cell_string = substr($mesh_cell_string, 0, -1);
$insert_string = "mem_id,mesh_heading_name," . $mesh_cell_string . ",qualifier_name,major,rank";
$values_string = "'$mem_id','$descript'," .$mesh_values_string. ",'$qualifier','$major','$value'";
$sql = "INSERT INTO mesh_table (" . $insert_string .") VALUES (" . $values_string .")";
$result = mysqli_query($cxn,$sql) or die ("couldn't execute the query");
?>
The strange thing is... i don't get an error ("couldn't execute the query") so i thought it went alright but when i look into my database there aren't any values written... when i un-comment the the 2 variables:
//$mesh_cell_string = "tree_0,tree_1,tree_2,tree_3,tree_4";
//$mesh_values_string = "'C23','550','291','687','500'";
And comment the foreach loop, it works...? So there goes something wrong in the foreach loop, but when i echo the $sql on both methods i get the same:
INSERT INTO mesh_table (mem_id,mesh_heading_name,tree_0,tree_1,tree_2,tree_3,tree_4,qualifier_name,major,rank) VALUES ('1','Chair','C23','550','291','687','500','sitting','Y','6')
I really don't know what i am doing wrong...?
Best regards,
Thijs
change $values_string = "'$mem_id','$descript'," .$mesh_values_string. ",'$qualifier','$major','$value'";
To
$values_string = "'".$mem_id."','".$descript."'," .$mesh_values_string. ",'".$qualifier."','".$major."','".$value."'";

Categories