I am using the below PHP file to upload XML to MySQL database, but the issue is my table name is Con-1 and cannot use it.
I have error in the below line:
array(
':name' => $data->Con-1[$i]->name,
':address' => $data->Con-1[$i]->address,
':gender' => $data->Con-1[$i]->gender,
':designation' => $data->Con-1[$i]->designation,
':age' => $data->Con-1[$i]->age
)
please help me to solve it
<?php
//import.php
sleep(3);
$output = '';
if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != '')
{
$valid_extension = array('xml');
$file_data = explode('.', $_FILES['file']['name']);
$file_extension = end($file_data);
if(in_array($file_extension, $valid_extension))
{
$data = simplexml_load_file($_FILES['file']['tmp_name']);
$connect = new PDO('mysql:host=localhost;dbname=testing','root', '');
$query = "
INSERT INTO `Con-1`
(name, address, gender, designation, age)
VALUES(:name, :address, :gender, :designation, :age);
";
$statement = $connect->prepare($query);
for($i = 0; $i < count($data); $i++)
{
$statement->execute(
array(
':name' => $data->Con-1[$i]->name,
':address' => $data->Con-1[$i]->address,
':gender' => $data->Con-1[$i]->gender,
':designation' => $data->Con-1[$i]->designation,
':age' => $data->Con-1[$i]->age
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
$output = '<div class="alert alert-success">Import Data Done</div>';
}
}
else
{
$output = '<div class="alert alert-warning">Invalid File</div>';
}
}
else
{
$output = '<div class="alert alert-warning">Please Select XML File</div>';
}
echo $output;
?>
You should be able to do it using variable variables, so first assign Con-1 to a variable and then substitute this variable for the name in the assignment...
$var = 'Con-1';
$statement->execute(
array(
':name' => $data->$var[$i]->name,
':address' => $data->$var[$i]->address,
':gender' => $data->$var[$i]->gender,
':designation' => $data->$var[$i]->designation,
':age' => $data->$var[$i]->age
)
);
Related
I currently have this code connected to a JSGrid table:
$connect = new PDO("mysql:host=localhost;dbname=localDatabase", "root", "root");
$method = $_SERVER['REQUEST_METHOD'];
$query = "SELECT COUNT(*) FROM stmr";
$link = mysqli_connect("localhost","root", "root", "localDatabase");
$result = mysqli_query($link, $query);
$form_id = mysqli_fetch_array($result)[0] + 1;
if($method == 'GET')
{
$data = array(
':item_id' => "%" . $_GET['item_id'] . "%",
':description' => "%" . $_GET['description'] . "%",
':part_number' => "%" . $_GET['part_number'] . "%",
':unit' => "%" . $_GET['unit'] . "%",
':quantity' => "%" . $_GET['quantity'] . "%"
);
$query = "SELECT * FROM stmrdesc WHERE item_id LIKE :item_id AND description LIKE :description AND part_number LIKE :part_number AND unit LIKE :unit AND quantity LIKE :quantity ORDER BY item_id DESC";
$statement = $connect->prepare($query);
$statement->execute($data);
$result = $statement->fetchAll();
foreach($result as $row)
{
$output[] = array(
'id' => $row['row_id'],
'item_id' => $row['item_id'],
'description' => $row['description'],
'part_number' => $row['part_number'],
'unit' => $row['unit'],
'quantity' => $row['quantity']
);
}
header("Content-Type: application/json");
echo json_encode($output);
}
if($method == "POST")
{
$data = array(
':item_id' => $_POST['item_id'],
':description' => $_POST['description'],
':part_number' => $_POST["part_number"],
':unit' => $_POST["unit"],
':quantity' => $_POST["quantity"]
);
$query = "INSERT INTO stmrdesc (item_id, description, part_number, unit, quantity) VALUES (:item_id, :description, :part_number, :unit, :quantity)";
$statement = $connect->prepare($query);
$statement->execute($data);
}
if($method == 'PUT')
{
parse_str(file_get_contents("php://input"), $_PUT);
$data = array(
':item_id' => $_PUT['item_id'],
':description' => $_PUT['description'],
':part_number' => $_PUT['part_number'],
':unit' => $_PUT['unit'],
':quantity' => $_PUT['quantity']
);
$query = "
UPDATE 'stmrdesc'
SET 'item_id' = ':item_id',
'description' = ':description',
'part_number' = ':part_number',
'unit' = ':unit',
'quantity' = ':quantity'
WHERE 'id' = ':id'
";
$statement = $connect->prepare($query);
$statement->execute($data);
}
if($method == "DELETE")
{
parse_str(file_get_contents("php://input"), $_DELETE);
$query = "DELETE FROM stmrdesc WHERE id = '".$_DELETE["id"]."'";
$statement = $connect->prepare($query);
$statement->execute();
}
As you can see, I have a method that is connected to each of the buttons of the JSGrid table and all work (submit the changes to the database) except the PUT Method that edits and updates the row in the database.
The put sql statement has WHERE 'id' = ':id' but ':id' does not exist in the $data array.
I want import an List in csv format, with seperator, from an Textarea to my MySQL Database.
But it always failed, also if its in the correct format.
Input Text:
Thomas|Maier|5778011152|Bahnweg|232
PHP Code:
<?php
if(isset($_POST["base_name"]) && isset($_POST["new_entry"])) {
$myList = preg_replace("/\r|\n/", "", preg_split("/$\R?^/m", $_POST["new_entry"]));
foreach($myList as $info) $csv[] = explode($_POST["separator"], $info);
$csvParams = $csv[0];
array_shift($csv);
$success = 0;
$total = 0;
foreach($csv as $info) {
$sqlInsert = array_combine($csvParams, $info);
$sqlInsert["base"] = $_POST["base_name"];
$sqlInsert["info"] = "unbenutzt";
$p = softwareInsertArray($softwareSqlLink, $sqlInsert, "person");
if($p) $success++;
$total++;
}
$q = softwareRunQuery($softwareSqlLink, false, "INSERT INTO statistics (`key`, `val`) VALUES ('".$_POST["base_name"]."|profit', '0');");
}
if(isset($total)) {
if($total == $success && $total > 0 && $q) {
$alert = array("type" => "success", "header" => "Erfolgreich!", "text" => "Success.");
softwareSqlLog($softwareSqlLink, "person", array("status" => 1, "info" => array("base" => $_POST["base_name"], "text" => $success." person added successfully")));
} else {
$alert = array("type" => "danger", "header" => "Fehler!", "text" => $success."/".$total." sucess.");
softwareSqlLog($softwareSqlLink, "person", array("status" => 0, "info" => array("base" => $_POST["base_name"], "text" => $success."/".$total." added.")));
}
}
?>
If comes always 0 added = Nothing Uploaded. Anyone an Idea?
Thanks
To put it briefly, I'm looking for a way to do a redirect after a successful PDO insert. Here is what I have so far.
Function for redirecting
<?php
function redirect_to($new_location) {
header("Location: " . $new_location);
exit;
}
?>
PDO INSERT
Please note, I've trimmed some code in my example below to make it easier to read.
try {
$sql = "INSERT INTO location_info (`department`, `participant`, `activity`, `location`, `rec_injuries`, `rec_injuries_timeframe`, `non_rec_injuries` )
VALUES (:department, :participant, :activity, :location, :rec_injuries, :rec_injuries_timeframe, :non_rec_injuries, :non_rec_injuries_timeframe, '{$id}')";
$stmt = $db->prepare($sql);
for($i = 0, $l = count($_POST["department_name"]); $i < $l; $i++) {
$loc_info = array(':department' => $_POST["department_name"][$i],
':rec_injuries_timeframe' => $_POST["injury_time_frame"][$i],
':non_rec_injuries' => $_POST["non_rec_injuries"][$i],
':non_rec_injuries_timeframe' => $_POST["non_rec_injury_timeframe"][$i],
':competitor' => $_POST["competitor"][$i],
':cost_per_pair' => $_POST["cost_per_pair"][$i],
':usage_rate' => $_POST["usage_rate"][$i],
':leakage' => $_POST["leakage"][$i],
':cost_of_productivity' => $_POST["cost_of_productivity"][$i],
':non_rec_impact' => $_POST["non_rec_impact"][$i],
':non_rec_sprain' => $_POST["non_rec_sprain"][$i],
':non_rec_puncture' => $_POST["non_rec_puncture"][$i],
':non_rec_dermatitis' => $_POST["non_rec_dermatitis"][$i],
':non_rec_infection' => $_POST["non_rec_infection"][$i],
':non_rec_burns' => $_POST["non_rec_burns"][$i],
':non_rec_cuts' => $_POST["non_rec_cuts"][$i],
':rec_impact' => $_POST["impact"][$i],
':rec_sprain' => $_POST["sprain"][$i],
':rec_puncture' => $_POST["puncture"][$i],
':rec_dermatitis' => $_POST["dermatitis"][$i],
':rec_infection' => $_POST["infection"][$i],
':rec_burns' => $_POST["burns"][$i],
':rec_cuts' => $_POST["cuts"][$i],
':condition' => $_POST["condition"][$i] );
$stmt->execute($loc_info);
}
if ($stmt->execute()) {
redirect_to($_SERVER["DOCUMENT_ROOT"]."/testing/tim/results.php");
}
}
catch (Exception $e) {
$error = $e->getMessage();
print "<b>error:</b> " . $error;
}
You'll see that I have an if statement for the redirect with if ($stmt->execute()) {
redirect_to($_SERVER["DOCUMENT_ROOT"]."/testing/tim/results.php");
Where am I going wrong?
Where am I going wrong?
When you are adding A LOT of useless code.
Here goes the FULL code you need (save for the trimmed array):
$sql = "INSERT INTO location_info (`department`, `participant`, `activity`, `location`, `rec_injuries`, `rec_injuries_timeframe`, `non_rec_injuries` )
VALUES (:department, :participant, :activity, :location, :rec_injuries, :rec_injuries_timeframe, :non_rec_injuries, :non_rec_injuries_timeframe, '{$id}')";
$stmt = $db->prepare($sql);
for($i = 0, $l = count($_POST["department_name"]); $i < $l; $i++) {
$loc_info = array(
':department' => $_POST["department_name"][$i],
':condition' => $_POST["condition"][$i]
);
$stmt->execute($loc_info);
}
redirect_to("/testing/tim/results.php");
This is all.
This code will redirect if all executes will be executed successfully.
You have a bit of a structure issue here...
If you're wanting to execute an indeterminate number of queries, then redirect after all queries have been executed successfully, then you need to track all the statement executions and errors.
If you want to throw an error the first time you have one, and stop inserting, then you just check the return result of the execute function and throw an error if it fails:
$sql = "INSERT INTO location_info (`department`, `participant`, `activity`, `location`, `rec_injuries`, `rec_injuries_timeframe`, `non_rec_injuries` )
VALUES (:department, :participant, :activity, :location, :rec_injuries, :rec_injuries_timeframe, :non_rec_injuries, :non_rec_injuries_timeframe, '{$id}')";
$stmt = $db->prepare($sql);
$errors = array();
for($i = 0, $l = count($_POST["department_name"]); $i < $l; $i++) {
$loc_info = array(':department' => $_POST["department_name"][$i],
':rec_injuries_timeframe' => $_POST["injury_time_frame"][$i],
':non_rec_injuries' => $_POST["non_rec_injuries"][$i],
':non_rec_injuries_timeframe' => $_POST["non_rec_injury_timeframe"][$i],
':competitor' => $_POST["competitor"][$i],
':cost_per_pair' => $_POST["cost_per_pair"][$i],
':usage_rate' => $_POST["usage_rate"][$i],
':leakage' => $_POST["leakage"][$i],
':cost_of_productivity' => $_POST["cost_of_productivity"][$i],
':non_rec_impact' => $_POST["non_rec_impact"][$i],
':non_rec_sprain' => $_POST["non_rec_sprain"][$i],
':non_rec_puncture' => $_POST["non_rec_puncture"][$i],
':non_rec_dermatitis' => $_POST["non_rec_dermatitis"][$i],
':non_rec_infection' => $_POST["non_rec_infection"][$i],
':non_rec_burns' => $_POST["non_rec_burns"][$i],
':non_rec_cuts' => $_POST["non_rec_cuts"][$i],
':rec_impact' => $_POST["impact"][$i],
':rec_sprain' => $_POST["sprain"][$i],
':rec_puncture' => $_POST["puncture"][$i],
':rec_dermatitis' => $_POST["dermatitis"][$i],
':rec_infection' => $_POST["infection"][$i],
':rec_burns' => $_POST["burns"][$i],
':rec_cuts' => $_POST["cuts"][$i],
':condition' => $_POST["condition"][$i] );
if(!$stmt->execute($loc_info)){
$errors[] = $e->getMessage();
// un-comment if you want to stop on error:
// print "<b>error:</b> " . $e->getMessage();
// die();
};
}
if(count($errors)){
foreach($errors as $error){
print "<b>error:</b> " . $e->getMessage()."<br/>";
}
} else {
redirect_to($_SERVER["DOCUMENT_ROOT"]."/testing/tim/results.php");
}
why images can not be performed when added
if(isset($_POST['tambah'])){
$data1 = array(
'id' => $_POST['id'],
'nama' => $_POST['nama'],
'jk' => $_POST['jk'],
'tempat' => $_POST['tempat'],
'tanggal' => date('Y-m-d',strtotime("$_POST[tanggal]")),
'pekerjaan' => $_POST['pekerjaan'],
'alamat' => $_POST['alamat'],
'foto' => move_uploaded_file($FILES['photo']['temp_name'], '..asset/img/anggota/'.str_replace(' ', '-', $_POST['id'].'.jpg'))
);
use function :
function tambahAnggota($data1){
$kunci = implode(", ",array_keys($data1));
$i = 0;
foreach ($data1 as $key => $value) {
if (!is_int($value)){
$arrayValue[$i] = "'".$value."'";
}else{
$arrayValue[$i] = $value;
}
$i++;
}
$nilai = implode(", ", $arrayValue);
print_r($nilai);
die();
$s = "insert into anggota ($kunci)";
$s .= " VALUES ";
$s .= "($nilai)";
$sql = $this->db->prepare($s); /*or die ($this->db->connect_errno);*/
$sql->execute();
}
will be added all the data except the image data file to be uploaded
will look like this :
'DA123', 'David', 'laki', 'Los Angeles', '1987-03-12', 'Web Developer', 'foof st.', ''
You have an error in your path : you write '..asset/img/anggota/' which is not correct.
Try with ../asset/img/anggota/ (notice the / after ..).
Just replace :
'foto' => move_uploaded_file($FILES['photo']['temp_name'], '..asset/img/anggota/'.str_replace(' ', '-', $_POST['id'].'.jpg'))
With :
'foto' => move_uploaded_file($FILES['photo']['temp_name'], '../asset/img/anggota/'.str_replace(' ', '-', $_POST['id'].'.jpg'))
I'm creating a multi-step form for my users. They will be allowed to update any or all the fields. So, I need to send the values, check if they are set and if so, run an UPDATE. Here is what I have so far:
public function updateUser($firstName, $lastName, $streetAddress, $city, $state, $zip, $emailAddress, $industry, $password, $public = 1,
$phone1, $phone2, $website,){
$updates = array(
'firstName' => $firstName,
'lastName' => $lastName,
'streetAddress' => $streetAddress,
'city' => $city,
'state' => $state,
'zip' => $zip,
'emailAddress' => $emailAddress,
'industry' => $industry,
'password' => $password,
'public' => $public,
'phone1' => $phone1,
'phone2' => $phone2,
'website' => $website,
);
Here is my PDO (well, the beginning attempt)
$sth = $this->dbh->prepare("UPDATE user SET firstName = "); //<---Stuck here
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
return $result;
Basically, how can I create the UPDATE statement so it only updates the items in the array that are not NULL?
I thought about running a foreach loop like this:
foreach($updates as $key => $value) {
if($value == NULL) {
unset($updates[$key]);
}
}
but how would I write the prepare statement if I'm unsure of the values?
If I'm going about this completely wrong, please point me in the right direction. Thanks.
First of all, use array_filter to remove all NULL values:
$updates = array_filter($updates, function ($value) {
return null !== $value;
});
Secondly, bind parameters, that makes your live a lot easier:
$query = 'UPDATE table SET';
$values = array();
foreach ($updates as $name => $value) {
$query .= ' '.$name.' = :'.$name.','; // the :$name part is the placeholder, e.g. :zip
$values[':'.$name] = $value; // save the placeholder
}
$query = substr($query, 0, -1).';'; // remove last , and add a ;
$sth = $this->dbh->prepare($query);
$sth->execute($values); // bind placeholder array to the query and execute everything
// ... do something nice :)
The below can be optimized:
$i = 0; $query = array();
foreach($updates as $key => $value) {
if ($value != NULL) {
$query[] = "{$key} = :param_{$i}";
$i++;
}
}
if (! empty($query)) {
$finalQuery = implode(",", $query);
$sth = $this->dbh->prepare('UPDATE user SET ' . $finalQuery);
$i = 0;
foreach($updates as $key => $value) {
if ($value != NULL) {
$sth->bindParam(':param_'.$i, $value, PDO::PARAM_STR);
$i++;
}
}
}