So at the top of the page there is an area for users to create a post with a title and body.
<div class="write_post" id="write_post">
<label for="post_title"><b>Title</b></label>
<input type="text" placeholder="What are you calling this?" name="post_title" required>
<label for="post_body">Body</label>
<textarea name="post_body" id="post_body" rows="5" cols="80" placeholder="Write post here..." required></textarea>
<button action="post.php" class="post_submit" type="submit">Post</button>
</div>
The goal is when they click the post button it will create a post below.
I've tried using javascript to help, but I'm not 100% sure what to do. A push in the right direction would help.
There is no need to use JavaScript in this case – you can use PHP and save the form data in a database.
1. Create an HTML form within a PHP file
First, wrap your input elements in a form (I've only kept the elements that are important in this case):
index.php
<form action="comment.php" method="get">
<input type="text" name="post_title">
<textarea name="post_body"></textarea>
<button type="submit">Post</button>
</form>
2. Create a PHP file to process the submitted form data
As you can see, the form has an action attribute which leads to a file named comment.php. This is just a suitable name I picked, you can name the PHP-file however you like.
In this newly created PHP-file you have to process the submitted form data. Please notice that PHP-files can only run on a server and not locally on your PC like an HTML-file. I would recommend to directly upload and test within a sub-folder on your web server.
A possible folder structure would be:
test-folder
|
+-- index.php
|
+-- comment.php
2. Editing the PHP file and saving data to the database
Open the PHP-File and add the following:
comment.php
2.1 Getting the form data
?php
/*
* Receive the submitted form data and assign it to variables
*/
$comment_title = $_GET["post_title"]; // same as the name attribute in HTML
$comment_body = $_GET["post_body"];
2.2 Creating a new database
We now have the data, but we also want to save it. Data like this is usually saved within a database. Most hosting providers allow you to create one pretty easily.
Your database should have a structure like this:
comments
|
+-- ID (auto increment)
|
+-- comment_title
|
+-- comment_body
2.3 Connecting to the database
We now have to connect to our database to save the data.
/*
* Connect to your database to save the form data
*/
$servername = "localhost"; // get this data from your hosting provider
$username = "username";
$password = "password";
// create a new connection
$conn = new mysqli($servername, $username, $password);
// check if the connection succeeds
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
2.4 Inserting data in to the database
/*
* Insert the form data in to the database
*/
$sql = "INSERT INTO comments (comment_title, comment_body)
VALUES ('".$comment_title."','".$comment_body."',)";
$conn->close();
3. Displaying the saved data
Now we only have to display the saved data on the index.php
We can to this by looping through the rows in our database.
index.php
/*
* Connect to your database and display the saved comments
*/
$servername = "localhost"; // get this data from your hosting provider
$username = "username";
$password = "password";
// create a new connection
$conn = new mysqli($servername, $username, $password);
// check if the connection succeeds
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysql_query("SELECT comment_title, comment_body FROM comments");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo $row[0] . $row[1];
}
Related
I have been getting this T_IF error, but I can't locate any syntax errors. Originally I had the ";" inside of the "" for the sql, but after fixing this the errors continued. I have tried clearing my cache just to be sure that isn't the problem, but no luck.
<?php
require_once 'requires-requires.php';
require 'requires-vars.php';
$mainUser = $row[user];
$coinUser = $mainUser;
$coinExperience = 0;
$coinCoins = 0;
$coinLevels = 0;
$coinUser = mysql_real_escape_string($coinUser);
$coinExperience = mysql_real_escape_string($coinExperience);
$coinCoins = mysql_real_escape_string($coinCoins);
$coinLevels = mysql_real_escape_string($coinLevels);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$servername = "localhost";
$user = "username";
$pass = "password";
$dbname = "databasename";
$conn = new mysqli($servername, $user, $pass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$usercheck = $conn->query("SELECT user FROM coinchaser WHERE user = '$coinUser'");
$rows_count_value = mysqli_num_rows($usercheck);
if($rows_count_value != 0){
$usernameMatchErr = "You Have Already Joined This Game";
} else {
$sql = "INSERT INTO coinchaser (user, experience, levels, coins) VALUES ('$coinUser', '$coinExperience', '$coinLevels', '$coinCoins')";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
}
?>
<div class="wrapper">
<h2>GAMES</h2>
<p> Game: Description </p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Coin Chaser">
</div>
</form>
</div>
</body>
</html>
EDIT: Added full code from the page. The $row[user] comes from one of the included files. This was working prior to me attempting to add the code the below it so I know it is fine. The issue remains with the following portion of the code:
$sql = "INSERT INTO coinchaser (user, experience, levels, coins) VALUES ('$coinUser', '$coinExperience', '$coinLevels', '$coinCoins')";
if ($conn->query($sql) === TRUE) {
As far as debugging the php, I was having issues attempting to do so on this laptop. I have been mainly doing javascript/html/css on this laptop and had forgotten that php needed to be installed on it for the debugging to work properly. I am dusting off my older laptop to see if I can get it to boot up to do a quick php debug on it.
I do plan to put the actual backend operations on their own page. For some reason, I find it simpler to see it working all together on a single page atm as I am still learning sql and trying to become more familiar and comfortable with it rather than bouncing between two pages back and forth trying to find any syntax errors I might have made.
EDIT (SOLVED): I solved the issue. I have no idea why, but for some reason it didn't like the database column named "user" being named "user". My spelling was correct, no syntax issue. I simply went into the database, changed the column name to "username", returned to the file and change "user" to "username" and it worked perfectly.
I solved the issue. I have no idea why, but for some reason it didn't like the database column named "user" being named "user". My spelling was correct, no syntax issue. I simply went into the database, changed the column name to "username", returned to the file and change "user" to "username" and it worked perfectly.
I am trying to connect to my own self created second database using wordpress.
What i am trying to achieve is to extract data from my own database(not wordpress database) on my static wordpress front page.
I use php_everywhere plug in in order for me to write php code in blog post and pages.
I use the following code:
<?php
$servername = "localhost";
$username = "thomas";
$password = "password";
$dbname = "thomas";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from number";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
However i got an error unexpected '"localhost"' (T_CONSTANT_ENCAPSED_STRING).
Not sure why.
See https://stackoverflow.com/search?q=T_CONSTANT_ENCAPSED_STRING
1) When using that plugin, be sure you've used straight quotes and backspace around the php to remove invisible control characters. And be sure the plugin doesn't have limitations on what it can do and ignores paragraph returns in the editor.
2) You're much better off using a page template in your theme and running PHP in a .php file and not in the post/page editor with a plugin. See Page Templates | Theme Developer Handbook | WordPress Developer Resources. Make a page template, add the calls to header, etc., and then work with your PHP in the file itself. Select the page template in the page editor of the page you're publishing in WordPress.
You can create new object for new database connection and use that object to do any operation for external database
$mydb = new wpdb('thomas','password','thomas','localhost');
$rows = $mydb->get_results("select Name from my_table");
You must have to use $mydb in place of $wpdb
Wordpres provide a way to connect the other db.
$mydb = new wpdb('thomas','password','thomas','localhost');
$rows = $mydb->get_results("select Name from number");
foreach ($rows as $row) :
echo "id: " . $row->id. " - Name: " . $row->firstname. " " . $row->lastname. "<br>";
endforeach;
I have a site with user profiles. I've delete a slew of profiles within phpmyadmin, but those profiles that I've deleted still have their picture files in a folder on the website.
I'm looking for a script that I could run that would select/delete all the pictures in the folder that are not associated with any existing profile in the database.
A typical image name is like this: 0ae71e1bc25cae7e243464adb.jpg
I'm sure there's a way to do this, but I'm not a major expert at using mysql operations for something of this nature.
So in an attempt to be more clear:
I have let's say 100 existing users with their info in the database, including their profile picture name.
Their profile picture is in a folder on the server called images
In that same folder are images of users that do not exist
I'd like to run a script that will check to see if that image is referenced in the "users" table by any user, and if not, delete it.
Your help us appreciated.
I think this script should do the trick.
// Query the images paths as array using mysqli
$db = new mysqli("localhost", "user", "pass", "foo_db");
$result = $db->query("SELECT image_path FROM users");
$images_db = $result->fetch_all(MYSQLI_ASSOC);
// Use glob to retrieve all the existing img in dir
$directory = "/home/user/public_html/images/";
$images_dir = glob($directory . "*.*");
// if image_dir is not in images_db delete it using unlink fn
foreach($images_dir as $image_dir) {
if (!in_array($image_dir, $images_db)) {
unlink($directory . $image_dir);
}
}
You have to tweak the script for your need.
Be carefull with unlink ! First test the script in local !
Lighter on memory solution:
$files = scandir(DIR_TO_IMAGES_FOLDER);
$db_conn = create_db_connection(); //assume this creates the connection to your db and return false if it cant;
if (!$db_conn) exit(); //no connection
foreach ($files as $file){
if (is_file($file)){
$query = "SELECT COUNT(*)
FROM TABLE_NAME
WHERE image_name=:image_name";
$result = $db_conn->prepare($query);
$result->bindParam(":image_name", $file);
$in_use = true; //assume it is in use just incase sql execute fails;
try{
$result->execute();
$in_use = $result->fetchColumn();
}catch (Exception $e){
}
if (!$in_use) unlink(DIR_TO_IMAGES_FOLDER . '/' . $file);
}
}
But I would just create a new TABLE image_delete_pending and a trigger BEFORE DELETE on your 'users' table. The trigger would insert the image_name to the image_delete_pending TABLE. Then the script will for sure know that every image in the image_delete_pending needs to be deleted.
The script would then be:
$db_conn = create_db_connection(); //assume this creates the connection to your db and return false if it cant;
if (!$db_conn) exit(); //end script; no connection
$query = "SELECT image_name
FROM image_delete_pending;";
try{
$result = $db_conn->prepare($query);
$result->execute();
while ($row = $result->fetch()){
if(unlink(DIR_TO_IMAGES_FOLDER . '/' . $row['image_name'])){
$db_conn->query("DELETE FROM image_delete_pending WHERE image_name='". $row['image_name'] ."';";
}
}
}catch (Exception $e){
}
I would like to create a simple text web page that keeps the content. I want to keep the content saved on the server by what ever means (php or sql is fine).
sessionStorage and localStorage isn't what i'm looking for. Those keep the data on the users computer and doesn't allow other computers to see the same thing.
Thanks
So im kind of confused by your question I assume you mean pull string from mysql and display it on the webpage so here is an example.
<?php
//Connect
$user = 'example';
$password = 'example';
$host = 'example';
$link = mysql_connect($host, $user, $password);
mysql_select_db('example_db');
$handle = mysql_query('SELECT * FROM Example_db');
$row = mysql_fetch_row($handle);
$text = $row[0]; // Retrieve text in database
//Variable name above can be what ever you want it to be.
?>
//Example html
<h1><?php echo $text;></h1>
pard me if i'm wrong if so just tell me and I can see if I can further help you.
I just downloaded PHP-EWS, installed following the README instructions, and spun up a script to test out its functionalities. When I try running the script in my browser, I get the following message:
I get the same message when I supply a login I know is invalid. It seems I am connecting to my Exchange server, but it's not recognizing the credentials I provide.
Here is the script I am using
<?php
function __autoload($className)
{
$className = str_replace('_','/', $className);
$sFileName = $className . '.php';
if (file_exists($sFileName) && !class_exists($className))
{
require_once $sFileName;
}
// If the above if fails, you're program will terminate, there is no way to catch this.
}
include("ExchangeWebServices.php");
$host = "https://myexchange/EWS/Services.wsdl";
$username = "myusername#mydomain.com";
$password = "mypassword";
$ews = new ExchangeWebServices($host, $username, $password);
$request = new EWSType_FindItemType();
$request->ItemShape = new EWSType_ItemResponseShapeType();
$request->ItemShape->BaseShape = EWSType_DefaultShapeNamesType::DEFAULT_PROPERTIES;
$request->Traversal = EWSType_ItemQueryTraversalType::SHALLOW;
$request->ParentFolderIds = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
$request->ParentFolderIds->DistinguishedFolderId = new EWSType_DistinguishedFolderIdType();
$request->ParentFolderIds->DistinguishedFolderId->Id = EWSType_DistinguishedFolderIdNameType::INBOX;
// sort order
$request->SortOrder = new EWSType_NonEmptyArrayOfFieldOrdersType();
$request->SortOrder->FieldOrder = array();
$order = new EWSType_FieldOrderType();
// sorts mails so that oldest appear first
// more field uri definitions can be found from types.xsd (look for UnindexedFieldURIType)
$order->FieldURI->FieldURI = 'item:DateTimeReceived';
$order->Order = 'Ascending';
$request->SortOrder->FieldOrder[] = $order;
$response = $ews->FindItem($request);
echo '<pre>'.print_r($response, true).'</pre>';
?>
Try testing your access by:
Hitting the server url directly: https://YOUREXCHANGESERVER/EWS/Services.wsdl
You should be prompted for credentials. After you enter your credentials you will be presented with the WSDL definition. If it does not present you a WSDL definition that looks like the example below then check with your administrator on credentials or if there are any firewall blocks put in place.
Example (Partial response):
<wsdl:definitions targetNamespace="http://schemas.microsoft.com/exchange/services /2006/messages"><wsdl:types><xs:schema><xs:import namespace="http://schemas.microsoft.com/exchange/services/2006/messages" schemaLocation="messages.xsd"/></xs:schema></wsdl:types>
A great tool I use in analyzing web services is: SOAP-UI by SmartBear