Connect to a second database from wordpress - mysql

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;

Related

PHP Phantomjs: How to handle Page Transition? (Web Scraping)

Everyone.
This question maybe duplicated with Using PhantomJs, how to get and handle the new page?.
But there was not exact answer.
My question is as follows.
The pages what I want to scrape 3 pages.
1st Page : input unique id , click next.
if valid id => go to 2nd page.
2nd Page : click link(contains id)
3rd Page : download Pdf File.
So my aim is to download pdf file from unique id automatically.
Then the main point is how to handle page transition in Phantom PHP?
My test Code is as:
// Use the composer autoloader.
require_once 'vendor/autoload.php';
// Setup mink drivers.
$goutteDriver = new \Behat\Mink\Driver\GoutteDriver();
$phantomjsDriver = new \Behat\Mink\Driver\Selenium2Driver('phantomJS');
// Setup mink sessions.
$goutteSession = new \Behat\Mink\Session($goutteDriver);
$phantomjsSession = new \Behat\Mink\Session($phantomjsDriver);
// Setup mink session manager.
$mink = new \Behat\Mink\Mink();
// Register sessions.
$mink->registerSession('goutte', $goutteSession);
$mink->registerSession('phantomjs', $phantomjsSession);
// Set Goutte as the default session.
$mink->setDefaultSessionName('phantomjs');
// Visit mink website with phantomjs driver.
$mink->getSession('phantomjs')->visit('https://testurl.com');
// Get the default goutte session.
$session = $mink->getSession('phantomjs');
// Get the page document.
$page = $session->getPage();
echo $session->getCurrentUrl(), PHP_EOL;
// $page->find('css', '#guides')->clickLink("Drivers");
// echo $session->getCurrentUrl(), PHP_EOL;
// Output the installation instructions from the page.
$input = $page->find('css', '#id');
$input->setValue("1234567890");
echo $input->getValue(), PHP_EOL;
$page->find('css', '#validar')->Click();
echo $page->find('css', '#validar')->getValue(), PHP_EOL;
$session->executeScript('document.getElementById("validar").click()');
//$session->reload();
sleep(5);
// $mink->getSession('phantomjs')->visit('https://testurl.com/next');
$page = $session->getPage();
echo $session->getCurrentUrl(), PHP_EOL;
sleep(5);
$mink->getSession('phantomjs')->visit('https://testurl.com/next2?id=1234567890');
$page = $session->getPage();
echo $session->getCurrentUrl(), PHP_EOL;
// Stop browser sessions.
$mink->stopSessions();
So
How to handle page transition?
How to download pdf file properly?

unexpected 'if' (T_IF)

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.

How to display a users post on home page

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];
}

web page keep content after refresh server side

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.

AS3 ALIVEPDF saving via method.remote (PHP) no longer working

The SWF is located on a web server. I am calling the function using this code in AS3...
myPDF.save(Method.REMOTE, "http://www.example.com/generator/createpdf.php",
Download.ATTACHMENT, "line.pdf");
Here is my PHP script located on the server...
$method = $_GET['method'];
$name = $_GET['name'];
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
// get bytearray
$pdf = $GLOBALS["HTTP_RAW_POST_DATA"];
// add headers for download dialog-box
header('Content-Type: application/pdf');
header('Content-Length: '.strlen($pdf));
header('Content-disposition:'.$method.'; filename="'.$name.'"');
echo $pdf;
} else echo 'An error occured.';
It used to work, but stopped a while back. Any help would be greatly appreciated.
1) This stopped working for me as well, until I added the following -
if(!$HTTP_RAW_POST_DATA){
$HTTP_RAW_POST_DATA = file_get_contents(‘php://input’);
}
2) I also patched /src/org/alivepdf/pdf/PDF.as::save() per this post enter link description here