Write to a php file via wordpress - php

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.

Related

How to allow users to search my database from a WordPress web page

I have a database of some entities (to warn people from them, scan fraud, etc.) and provide a search box when some one searches.
It will tell him if this entity is included in this fraud list, and why to show for an example a source of the warning if no source it won't show it
I'm so confused I can't even start, should it be just normal listing and user can just do ctrl + f... or I have to do it more creatively
First you haven't provided a structure of the database so I added some example colums like websitename, url and added_at
You first need a Database connection
$pdo = new PDO("mysql:hostname=localhost;dbname=fraud"; "mysqlusername, "mysqlpassword");
Then you need a search form
<form action="index.php?search=1" method="GET">
Search query: <input type="text" name="query"><br>
<input type="submit"><br>
</form>
After that you need to get the entries from the MySQL Database.
if(isset($_GET["search"])) {
$stmnt = $pdo->prepare("SELECT * FROM table WHERE websitename = ? OR url = ?");
$stmnt->execute(array($_GET["query"], $_GET["query"]));
// Print values
while($row = $stmnt->fetch()) {
echo $row["websitename"];
echo $row["url"];
echo $row["added_at"];
}
}

How to make a generated code expire after a few times of entering (PHP)?

I have been trying to write a code in PHP that generates a random code, stores it in the database and asks the user to enter it. if the code is entered more than 3 times, the code needs to be expired. this is my code:
<?php
include("ProcessCode.php");
$con = mysqli_connect("localhost","root","") ;
if(mysqli_select_db($con,"login"))
{
echo 'database selected' ;
}
$rand=rand();
echo $rand ;
$sql = "INSERT INTO random (number) VALUES ('$rand') " ;
if(mysqli_query($con,$sql))
{
echo 'inserted' ;
}
?>
$CodeCheck=$_POST['code'];
//Establishing Connection with server
$conn = mysqli_connect("localhost", "root", "");
//Selecting Database
$db = mysqli_select_db($conn, "login");
//sql query to fetch information of registerd user and finds user match.
$query = mysqli_query($conn, "select * from random WHERE number='$CodeCheck'");
$rows = mysqli_num_rows($query);
if (mysqli_num_rows($query) > 0)
{
echo " Code exists already.";
}
if($rows == 1)
{
header("Location: Success.php");
}
else
{
$error = " Code is Invalid";
echo $error;
}
could you please explain how to implement the expiry part?
in your table you could have a field for count. When use login and login is wrong, add + 1 to your count. When user login successfuly, reset the count. If count meet +3, reset the code.
i understand from your question that you need the logic on how to make the random_code expired after inserting from interacted users on your website 3 times ,assuming that , as long as the code is not expired he will be able to do his inserts and you may load it on your page .
i would do that through database queries .
Please follow this instruction listed below
instructions :
while your php page generate the random code , you may store it in database table with a auto reference key , for instance ,
assuming that you have randomly generated a code as below :
"Some random code here"
the above code which was generated by your php page have load it from mysql table called Random_Generated_Code , i would go to edit this table and add new field in it and call it generated_Code_Reference_Key ( could be auto serial number ) to avoid any duplication as well make additional field called Expire_Flag which we are going to use later.
so once your page have loaded the above example code , you should retrieve the generated_Code_Reference_Key along with it and keep it in hidden variable on your page
it should be loaded on the page based on expire_Flag value as a condition
select generated_code from Random_Generated_Code where expire_flag = ""
now once the user try to insert that generated code , in each time he insert it define another table in your database lets call it ( inserted_Codes_by_users) and store in it the username of whoever is doing that on your website as well you have to store the generated_Code_Reference_Key which we are storing in hidden variable as mentioned earlier to indicate which code was used while inserting.
now during page load or any event you want you can find expired code by make select statement from the inserted_Codes_by_users table
select count(generated_Code_Reference_Key) as The_Code_Used_Qty from inserted_Codes_by_users where username = username_of_that_user
so you can get how many times this user have inserted this specific generated_random_Code
retrieve result of the query in a variable and to make sense lets call it The_Code_Used_Qty and make if condition on page load event or any event you like
if The_Code_Used_Qty = 3 then
fire update statement to first table which loaded that random generated code
and update the expire_flag field for that code (Expired) based on reference_key
update Random_Generated_Code set expire_Flag = "expired" where generated_Code_Reference_Key = "generated_Code_Reference_Key" << the one u stored in hidden variable
end if
so now that will get you directly to the point of why we are loading random_generated_code table first time with that condition expire_flag = ""
as it will only retrieve the codes which is not expired .
hopefully this will help you to achieve what you want .
good luck and let me know if you need any help or if you face any confusion while reading my answer.
Good luck .

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.

How to return data based on the email which I have in the sessions within codeigniter?

I'm trying to build a site with codeigniter and when a user logs in I am able to get the email address they logged in with from the sessions data so I therefore can pin point their record which is in the database.
At the moment I am only able to get these records by querying the database where $email = email blah blah and doing a foreach statement which isn't ideal. I would rather be able to get the users id via the email address which has been passed in the sessions. Then pass the id into the urls for each item of the navigation menu when they log in and get the content this way.
Not sure if I'm being clear but what I need help with is:
Get the correct record from the database based on the session email
Creating dynamic URLs which pass the users id into each item of the navigation menu once logged in
Display that users content based on the id which is in the url
I have this for the function in my controller at the moment:
$email = $this->session->userdata('email');
$query = $this->db->get_where('users', array('email' => $email));
foreach($query->result_array() as $result){
echo $result['id'];
}
So I'm unsure of what I need to do, getting muddled up, any help is greatly appreciated!
Since you're expecting a single row you can use $query->row_array().
$email = $this->session->userdata('email');
$query = $this->db->get_where('users', array('email' => $email));
$user = $query->row_array();
echo $user['id'];
More info on generating query results on the CodeIgniter docs.

Edit mysql database from "GET" index.php?id=XX

I'm currently learning PHP. I've code a simple bucketlist script with a admin panel, sessions etc just to see if I can do it.
The last page I am coding is the "edit.php" & "editone.php" I have a table which returns all data within the database "ID, Goal & Rating" my fourth column returns "EDIT" as a link which will link off to: editone.php?id=xx
editone.php currently is not a page. For the life of me I cannot figure out how I code the editone so I can grab the data and UPDATE mysql. I'm almost there just cannot piece together the puzzle.
Here's the core of my code for the edit page.
<?php
while ($query_row = mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>".$query_row['id']."</td><td>". $query_row['goals']."</td><td><span class='label label-inverse'>". $query_row['rating']."</span></td><td><a href='editone.php?id=".$query_row['id']."'>Edit</a></td>";
echo "<tr>";
}
?>
Any assistance would be really appreciated.
Send all the parameters through POST method to editone page. I mean in your edit page, you are getting all the variables from database. You can show them in a form having a submit button and of type "POST". So now when someone submits, it goes to editone.php page.
Get all the variables first through $_POST method. Then write a update query.
$sql = "UPDATE tablename SET goals = '$goal', rating='$rating' WHERE id = $id";
make sure to escape your post variables as said in the comment.
This is how should be your PDO Update statement.
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$goals = 'Some goals';
$rating = 'whatever rating';
$id = 3;
// query
$sql = "UPDATE tablename
SET goals=?, rating=?
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($goals,$rating,$id));
If I understood you correctly, what you want is a page that first displays a single row (so it can be edited) and then saves it once you're done. So you start out by writing the HTML form with no data in it.
Next, you read the ID from the query string:
<?php
$rowId = $_GET['id'];
and then query for the data:
// database connection example borrowed from Abhishek
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "SELECT goals, rating FROM tablename WHERE id = ?";
$query = $conn->prepare($sql);
$query->execute(array($rowId));
$row = $query->fetch();
Now, you can use the data to populate your form. This gets you about halfway there. :-)
You'll want the actual save to be in response to a POST request, not GET. There's a long and somewhat complicated explanation on why that is, but the simplified version is that you use POST whenever you're making changes for the user, and GET when you're just reading data -- there's a bunch of browser and proxy behavior and whatnot tied to these assumptions, so it's a good idea to start doing things the right way early on.
When you process the POST request -- you can do it on the same page -- you'll have the updated form values for grabs, and you can use them to update your database:
// This can be a hidden field on the form...
$rowId = $_POST['id'];
$goals = $_POST['goals'];
$rating = $_POST['rating'];
// database connection example borrowed from Abhishek
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "UPDATE tablename SET goals = ?, rating = ? WHERE id = ?";
$query = $conn->prepare($sql);
$query->execute(array($goals, $rating, $rowId));
After this, your database should be updated. To finish things off, you'll probably want to redirect back to the page to make sure the form can't be double-submitted accidentally.
I haven't covered quite everything here, a bit on purpose. It's more fun when there are some blanks to fill in. :-)
You probably want your second <tr> to be </tr>.
The most common solution is to use an html form. The input values of this form are a select with the id in query string. When a submit button is pressed to save this, make a update. But I want share with you a good and complete web 2.0 example.

Categories