CSV upload on front end of wordpress site (PHP/SQL) - php

I've made a lot of progress on this in some areas but struggling in others. Here's the objective: Existing wordpress site is being used by client. They want the admin user to access one of the front end pages with an upload option where they can upload a CSV (several daily). Then, upon accessing other pages in the portal, respective fields from the tables will be displayed (depending on the user). The CSV files have 201 fields, same order every time. In my php, I've setup a successful connection and coded 201 variables like so:
<?php
$server = "localhost";
$user = "root";
$pw = "root";
$db = "uwsTest";
$connect = mysqli_connect($server, $user, $pw, $db);
if ($connect->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
echo'success!';
}
if(isset($_POST['submit']))
{
$coldata = array();
$coldata['orderNumber'] = $filesop[0];
$coldata['null'] = $filesop[1];
$coldata['workOrderNum'] = $filesop[2];
$coldata['lowSideMIUNum'] = $filesop[3];
$coldata['highSideMIUNum'] = $filesop[4];
$coldata['accountNum'] = $filesop[5];
$coldata['custName'] = $filesop[6];
Again, this line goes on through [200]. On the next portion, I will only paste certain variables to save space. This is where I index which tables certain variables will belong in.
$table_cols = array();
/*staging*/
$table_cols[0] ="null,orderNumber,null,workOrderNum,lowSideMIUNum,highSideMIUNum,accountNum
/*clients*/
$table_cols[1] ="orderNumber,null,workOrderNum,lowSideMIUNum,highSideMIUNum,accountNum,custName
/*meters*/
$table_cols[2] ="workOrderNum,lowSideMIUNum,highSideMIUNum,accountNum,custName,address
/*tests*/
$table_cols[3] ="workOrderNum,lowSideMIUNum,highSideMIUNum,accountNum,custName,address
/*costs*/
$table_cols[4] ="workOrderNum,onsiteSurveyTestCost,onsiteSurveyTestRepairCost,offsiteSurveyTestCost
/*workorders*/
$table_cols[5] ="workOrderNum,lowSideMIUNum,highSideMIUNum,accountNum,custName
And now the SQL query:
$tablenames = array("staging","clients","meters","tests","costs","workorders");
for($tableno = 0;$tableno < sizeof($tablenames);$tableno++){
$q = "";
$q .= "INSERT INTO ".$tablenames[$tableno]." (".$table_cols[$tableno].") VALUES (";
$cols = explode("," ,$table_cols);
$data = array();
foreach($col as $key => $fldname) {
$data[] = "'".$coldata[$fldname]."'";
}
$q .= implode(",",$data).");";
}
echo'File submitted';
When I run this, I get no PHP errors. I run it on Mamp, upload the CSV through an html submit form, it calls the php and then on my php index page I get my messages for successful connection and successful insertion. However, when I look in MySQL workbench and select from tables they are empty. My staging table was actually only created with one column for primary key but I don't know if this code will submit everything without established columns/fields in the database tables. In my table_cols array under the 'staging' option (index [0]), I actually have all 201 variables there, as the entire form will be housed in this one table just to be safe. Am I missing something here as to why it's not loading into the database?

Related

PHP login script using bind_result in subsequent query mysqli

I'm trying to build a relatively simple PHP login script to connect to MySQL database running on my home server. I know the connection works as I've gotten some data returned as I would expect. However, I am having trouble getting the full script to work.
Essentially, I'm taking in a username/password from the user, and I first do a lookup to get the user_id from the users table. I then want to use that user_id value to do a comparison from user_pswd table (i'm storing usernames and passwords in separate database tables). At one point, I was able to echo the correct user_id based on the username input. But I haven't been able to get all the issues worked out, as I'm pretty new to PHP and don't really know where to see errors since I load this onto my server from a remote desktop. Can anyone offer some advice/corrections to my code?
The end result is I want to send the user to another page, but the echo "test" is just to see if I can get this much working. Thanks so much for the help!
<?php
ob_start();
$con = new mysqli("localhost","username","password","database");
// check connection
if (mysqli_connect_errno()) {
trigger_error('Database connection failed: ' . $con->connect_error, E_USER_ERROR);
}
$users_name = $_POST['user'];
$users_pass = $_POST['pass'];
$user_esc = $con->real_escape_string($users_name);
$pass_esc = $con->real_escape_string($users_pass);
$query1 = "SELECT user_id FROM users WHERE username = ?;";
if ($result1 = $con->prepare($query1)) {
$result1->bind_param("s",$user_esc);
$result1->execute();
$result1->bind_result($userid);
$result1->fetch();
$query2 = "SELECT user_pswd_id FROM user_pswd WHERE active = 1 AND user_id = ? AND user_pswd = ?;";
if ($result2 = $con->prepare($query2)) {
$result2->bind_param("is",$userid,$pass_esc);
$result2->execute();
$result2->bind_result($userpswd);
$result2->fetch();
echo "test", $userpswd;
$result2->free_result();
$result2->close();
} else {
echo "failed password";
}
$result1->free_result();
$result1->close();
}
$con->close();
ob_end_clean();
?>

Data Management Issue - How to manage retrieved data from mysql?

I am developing a game(c#) with database(mysql) and web service(php) to retrieving the data. The issue is the data management. There is a table on database with the name of items and it has some columns like id, item_name, item_description, item_prop, update_date, ownerId. I added 70 items to this table manually. The users can also add some items to this table or they can update the items they have already added in the game. My purpose is retrieving the whole affected rows of the table when the user is first logged in and save it as a json file in the game folder. After, read that file to fill the game environment with those items.
I try a way to achieve this. Firstly, i hold an updateDate variable in the game which is past like "1990-05-10 21:15:43". Second, i send this variable to the webservice as '$lastUpdateDate'; and make a query according to that variable at the database. select * from channels where update_date >= '$lastUpdateDate'; and write these rows in a json file as items.json. after that make a second query to retrieve the time and refresh the updateDate variable in the game. select select now() as 'Result';. In this way user would not have to get the whole table and write in json file every login process. So, it would be good for the performance and the internet usage. The problem occurs when the users update an item which is already added before. I can see the updated item, too with the first query, but I wrote it in json file twice in this way.
php code part of the getItems of my loginuser.php :
<?php
include './function.php';
// CONNECTIONS =========================================================
$host = "localhost"; //put your host here
$user = "root"; //in general is root
$password = ""; //use your password here
$dbname = "yourDataBaseName"; //your database
$phpHash = "yourHashCode"; // same code in here as in your Unity game
mysql_connect($host, $user, $password) or die("Cant connect into database");
mysql_select_db($dbname)or die("Cant connect into database");
$op = anti_injection_register($_REQUEST["op"]);
$unityHash = anti_injection_register($_REQUEST["myform_hash"]);
if ($unityHash == $phpHash)
{
if($op == "getItems")
{
$lastUpdateDate = anti_injection_login($_POST["updateDate"]);
if(!$lastUpdateDate)
{
echo "Empty";
}
else
{
$q = "select * from items where update_date >= '$lastUpdateDate';";
$rs = mysql_query($q);
if (!$rs)
{
echo "Could not successfully run query ($q) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($rs) == 0)
{
echo "No rows found, nothing to print so am exiting";
exit;
}
$arr = array();
while ($row = mysql_fetch_row($rs))
{
$arr = $row;
}
echo json_encode($arr);
}
mysql_close();
}
}
?>
So, how can i solve this problem? Or do you have any better idea for this approach. Help would be much appreciated. Thank you for your time.

Write to a php file via wordpress

I've built a web page that is able to send text messages to employees at the company where I work. With new employees being added and removed on a constant basis, I want to integrate this app with wordpress where the employees can be managed without editing the code.
Each post would contain the user's name and phone number. The name would be pulled in on the webpage as an option for the user to contact. When the form is submitted, it would go to a php form that runs an if/else to find the employee and match that employee with their phone number like so:
//Who the text message is to, Establish their phone #
if($employee == 'brad'):
$text_to[] = '+15555555555';
elseif ($employee == 'mary'):
$text_to[] = '+15555555555';
elseif ($employee == 'tom'):
$text_to[] = '+15555555555';
elseif ($employee == 'bill'):
$text_to[] = '+15555555555';
elseif ($employee == 'joe'):
endif;
I want to be able to not only pull these names from wordpress via a loop to display onto my page, but also to be able to add or remove the new entries, along with their phone number, to this php contact form.
I know how to loop through the wordpress posts to display the names on the page. I want to know if it's possible to also use this data to modify this contact form, and if so, how to set this up. Each time someone edits the wordpress entry for Joe, the PHP form gets this update so that when Joe is sent a message, it finds his phone number and sends him the message.
Any help is greatly appreciated. I should also note that I'm using Twilio to send the texts messages.
The use of a DMBS works well, but is not the only solution.
include 'users.inc'; // flat file creating array $userList
which could be an array( ofArrays ) for complex structures
[assume $userList = array($user => $phone, ...); ]
then foreach( $userList as $user => $phone ) { // process($user, $phone); }
Kudos for trying to solve a simple problem yourself. It's obvious that you are new to the idea of databases, and quite frankly, you're doing this the wrong way.
Let's talk about how your initial approach can be improved:
Each post would contain the user's name and phone number.
Perhaps instead of posts, we have one database table to store employee information.
You'll find tons of information on databases and how to use them with your wordpress account with a simple google search.
I want to be able to not only pull these names from wordpress via a loop to display onto my page, but also to be able to add or remove the new entries, along with their phone number, to this php contact form.
Again, if you had a database to store employee information, this is basic.
For example, an employees database table may have the following columns:
id
name
phone
created_at
updated_at
Since PHP has built in functions for communicating with a MYSQL database (which is most likely what WordPress is already using), you can do things like:
Get all employee data
SELECT * FROM employees
Get a certain employee's data
SELECT * FROM employees WHERE name = '$name'
$name is a variable that can be set via POST request from a WordPress form
Update a certain employee's data
UPDATE employees SET phone = '+15555555555' WHERE name = '$name'
Remove a certain employee's data
DELETE FROM employees WHERE id = 5
You are also able to do things like:
SELECT * FROM employees WHERE created_at > '3/1/2015'
Which will return all employees that were added after 3/1/15.
So everything that you all suggested was helpful. I may have not been as clear as I could have that I really needed the creation/editing/deletion of entries to be done via wordpress posts. I was able to set it up like this by doing the following:
//pull variables from html form input. Employee variables are post ID's that I will then be able to use to retrieve the post_content which contains their phone numbers
$employee1 = $_POST['employeeName1'];
$employee2 = $_POST['employeeName2'];
$employee3 = $_POST['employeeName3'];
$customMsg = $_POST["textMessage"];
//Create array from above variables and exclude any that lack post data
$employees = array($employee1, $employee2, $employee3);
$setEmployeeIDs = array();
foreach ($employees as $employee) {
if (!empty($employee)) {
$setEmployeeIDs[] = $employee;
}
}
$servername = "xxxx";
$username = "xxxx";
$password = "xxxx";
$dbname = "xxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Get array of Phone Numbers connected to each ID and add to array
$sql = "SELECT * FROM wp_posts WHERE ID IN (".implode(',',$setEmployeeIDs).")";
$result = $conn->query($sql);
$phoneNumbers = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$phoneNumbers[] = $row["post_content"] ;
}
} else {
echo "0 results";
}
$conn->close();
So to sum it up, I used wordpress to publish/edit/delete that data as posts, then sent the ID's selected from the webpage to the php form, and then was able to retrieve the phone numbers from the SQL database using Raphael's direction.

Optimizing WebSQL Local Database Population

I am trying to optimize the speed that my Local database populates in a Web app that is being developed. Currently, it uses PHP to access the Database and then inserts that data into the local database using Javascript.
Problem is, anything more than a couple entries slows it down and I'm pretty sure it's because it executes an individual SQL query for EVERY row. I've been reading up on transactions (Commits and Rollbacks and what not) and it seems like an answer but I'm not entirely sure how to implement it, or even where.
Here is a sample of one of the functions that loads a particular table.
function ploadcostcodes()
{
$IPAddress = '';
$User = '';
$Password = '';
$Database = '';
$Company = '';
$No='';
$Name='';
ploadSQLConnection($IPAddress,$User,$Password,$Database,$Company);
// This Connects to the actual database where the information comes from.
$Login = 'XXXXXXX';
$conn=mssql_connect($IPAddress,$Login,$Password);
if (!$conn )
{
die( print_r('Unable to connect to server', true));
}
mssql_select_db($Database, $conn);
$indent=" ";
$sql="SELECT Cost_Code_No as No, Description as Name, Unit_of_Measure FROM v_md_allowed_user_cost_codes WHERE Company_No = " . $Company . " and User_No = '" . $User . "'";
$rs=mssql_query($sql);
if (!$rs)
{
exit("No Data Found");
}
while ($row = mssql_fetch_array($rs))
{
$No = addslashes($row['No']);
$Name = addslashes($row['Name']);
$Name = str_replace("'",'`',$Name);
$Unit = addslashes($row['Unit_of_Measure']);
//THIS IS WHERE I SEE THE PROBLEM
echo $indent."exeSQL(\"INSERT INTO Cost_Codes (Cost_Code_No,Name,Unit_of_Measure) VALUES('".$No."','".$Name."','".$Unit."')\",\"Loading Cost Codes...\"); \r\n";
}
mssql_free_result($rs);
mssql_close($conn);
return 0;
}
I don't know what needs the transaction(or even if that's what needs to be done). There is MSSQL to access the data, SQLite to insert it and Javascript that runs PHP code.
I would prepare a query with placeholders, then execute it for each row with the right arguments. Something like this (JS part only, using underscore.js for array helpers):
db.transaction(function(tx) {
var q = 'INSERT INTO Cost_Codes (Cost_Code_No, Name, Unit_Of_Measure) VALUES (?, ?, ?)';
_(rows).each(function(row) {
tx.executeSql(q, [row.code, row.name, row.unit]);
});
});
Edit: a query with placeholders has two main benefits:
It makes it a lot easier for the DB engine to cache and reuse query plans (because you are running the same query a hundred times instead of a hundred different queries once).
It makes escaping data and avoiding SQL injections a lot easier.

PHP - Dynamic SQL Query from Dynamic POSTs

First time question, long time reader :)
I am building forms dynamically from Columns in a MYSQL DB. These columns
are created/ deleted etc.. elsewhere on my App. My form runs a query against a
SQL View and pulls in the column names and count of columns. Simple! build the form,
with the HTML inputs built with a PHP for loop, and it echos out the relevant HTML for the new form fields. All very easy so far.
Now i want a user to update these dynamically added fields and have the data added to the relevant columns - same table
as existing columns. So, as the input fields are named the same as the columns, they are posted to a PHP script for processing.
Problem is, while i have the actual field names inserted in to the SQL INSERT query, i cannot figure out how to extract the POST
data from the POST dynamically and add this to the VALUEs section of the query.
Here is my attempt....
The Query works without the variables added to it.
It works like this, first section/ is to retrieve the columns names from earlier created VIEW - as these are identical to POST names from the form. Then output to array and variable for insertion to Query. It looks like the implode function works, in that the relevant column names are correct in the statement, but i fear that my attempt to inject the column names on to the POST variables is not working.
$custq = "SELECT * FROM customProperties";
$result = $database->query($custq);
$num_rows = mysql_numrows($result);
while (list($temp) = mysql_fetch_row($result)) {
$columns[] = $temp;
}
$query = '';
foreach($columns as $key=>$value)
{
if(!empty($columns[$key]))
{
$values .= "'".'$_POST'."['".$value."'], ";
}
}
$q = "INSERT INTO nodes
(deviceName,
deviceInfo,
".implode(", ", $columns).",
nodeDateAdded,
status
)
VALUES
('" . $_POST['deviceName'] . "',
'" . $_POST['deviceInfo'] . "',
".$values."
CURDATE(),
'1'
)";
$result = $database->query($q)
Any help is much appreciated. I will feed back as much as i can. Please note, relativity new to PHP, so if i am all wrong on this, i will be glad for any tips/ advice
Regards
Stephen
If you want to get the values of every POST input without knowing the input names then you can do it this way:
//get all form inputs
foreach($_POST as $name => $value)
{
echo $name . " " . $value . "<br>";
}
If you want to get the value of certain POST inputs where you know the name of the input field then you can do it this way:
if(isset( $_GET["deviceName"]))
{
$deviceName = $_POST["deviceName"];
}
if(isset( $_GET["deviceInfo"]))
{
$deviceInfo = $_POST["deviceInfo"];
}
To connect to a database and insert the info then you have to do something like this:
$host = "localhost";
$dbuser = "username";
$pass = "password";
$datab = "databasename";
//Create DB connection
$con=mysqli_connect($host, $dbuser, $pass,$datab);
if (mysqli_connect_errno($con))
{
echo "ERROR: Failed to connect to the database: " . mysqli_connect_error();
}
else
{
echo "Connected to Database!";
}
//insert into database
mysqli_query($con, "INSERT INTO nodes (deviceName, deviceInfo) VALUES ('$deviceName', '$deviceInfo')");
(Don't forget to add mysql_real_escape_string to the $_POST lines after you get it working.)

Categories