My website in wordpress. I want to send automatically contact form 7 value to different database table. For example one is wordpress database table & another one is php database table. how i can fixed this issue?
Follow the Below Steps and add code in functions.php:
1) Create custom table in your custom database
CREATE TABLE candidate(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(50)
);
2) Create contact form 7 fields
[text* title]
[submit "Send"]
3) Add Below code to function.php
function contactform7_before_send_mail( $form_to_DB ) {
//set your db details
global $wpdb;
$form_to_DB = WPCF7_Submission::get_instance();
if ( $form_to_DB )
$formData = $form_to_DB->get_posted_data();
$title = $formData['title'];
/************* Insert in wordpress database ***********/
$wpdb->insert( 'candidate', array( 'title' =>$title ), array( '%s' ) );
/************ For Php Mysql Database (Create connection first) ********/
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (title)
VALUES ($title)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
remove_all_filters ('wpcf7_before_send_mail');
add_action( 'wpcf7_before_send_mail', 'contactform7_before_send_mail' );
Add below code to your function.php file.
function custom_db_wpcf7_before_send_mail($form7_data) {
//set your database details
$custom_db = new wpdb('user','password','custom_db','host');
$form7_data = WPCF7_Submission::get_instance();
if ($form7_data)
$post_data = $form7_data->get_posted_data();
$title = $post_data['title'];
$custom_db->insert('custom_table', array('field' => $value), array( '%s' ));
}
remove_all_filters('wpcf7_before_send_mail');
add_action('wpcf7_before_send_mail', 'custom_db_wpcf7_before_send_mail' );
}
Related
I have my php file on a server that retrieves data from my database.
<?php
$servername = "myHosting";
$username = "myUserName";
$password = "MyPassword";
$dbname = "myDbName";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM tableName;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row_number = 0;
while($row = $result->fetch_assoc()) {
$row_number++;
echo $_GET[$row_number. ";". $row["id"]. ";". $row["name"]. ";". $row["description"]. "<br>"];
}
} else {
echo "0 results";
}
$conn->close();
?>
Unfortunately, I do not know how to receive data from a php file using javascript.
I would like the script in javascript to display the received data in the console in browser.
The script written in javascript is Userscript in my browser extension(tampermonkey) and php file is on my server.
I've tried to use ajax, unfortunately without positive results.
(the php script works as expected).
JS(not working):
$.ajax({
url: 'https://myserver.com/file.php',
type: 'POST',
success: function(response) {
console.log(response);
}
});
The code within the loop is a little screwy
$_GET[$row_number. ";". $row["id"]. ";". $row["name"]. ";". $row["description"]. "<br>"]
that suggests a very oddly named querystring parameter which is not, I think, what was intended.
Instead, perhaps try like this:
<?php
$servername = 'myHosting';
$username = 'myUserName';
$password = 'MyPassword';
$dbname = 'myDbName';
$conn = new mysqli($servername, $username, $password, $dbname);
if( $conn->connect_error ) {
die( 'Connection failed: ' . $conn->connect_error );
}
$sql = 'select `id`, `name`, `description` from `tablename`;';
$result = $conn->query($sql);
if( $result->num_rows > 0 ) {
$row_number = 0;
while( $row = $result->fetch_assoc() ) {
$row_number++;
/* print out row number and recordset details using a pre-defined format */
printf(
'%d;%d;%s;%s<br />',
$row_number,
$row['id'],
$row['name'],
$row['description']
);
}
} else {
echo '0 results';
}
$conn->close();
?>
A full example to illustrate how your ajax code can interact with the db. The php code at the top of the example is to emulate your remote script - the query is more or less the same as your own and the javascript is only slightly modified... if you were to change the sql query for your own it ought to work...
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* emulate the remote script */
$dbport = 3306;
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql= 'select `id`, `address` as `name`, `suburb` as `description` from `wishlist`';
$res=$db->query( $sql );
$row_number=0;
while( $row=$res->fetch_assoc() ){
$row_number++;
/* print out row number and recordset details using a pre-defined format */
printf(
'%d;%d;%s;%s<br />',
$row_number,
$row['id'],
$row['name'],
$row['description']
);
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='//code.jquery.com/jquery-latest.js'></script>
<title>Basic Ajax & db interaction</title>
<script>
$( document ).ready( function(){
$.ajax({
url: location.href,
type: 'POST',
success: function( response ) {
console.log( response );
document.getElementById('out').innerHTML=response;
}
});
} );
</script>
</head>
<body>
<div id='out'></div>
</body>
</html>
Hi you can do it this way:
your php script:
if (isset($_POST["action"])) {
$action = $_POST["action"];
switch ($action) {
case 'SLC':
if (isset($_POST["id"])) {
$id = $_POST["id"];
if (is_int($id)) {
$query = "select * from alumni_users where userId = '$id' ";
$update = mysqli_query($mysqli, $query);
$response = array();
while($row = mysqli_fetch_array($update)){
.......
fill your response here
}
echo json_encode($response);
}
}
break;
}
}
Where action is a command you want to do SLC, UPD, DEL etc and id is a parameter
then in your ajax:
function getdetails() {
var value = $('#userId').val();
return $.ajax({
type: "POST",
url: "getInfo.php",
data: {id: value}
})
}
call it like this:
getdetails().done(function(response){
var data=JSON.parse(response);
if (data != null) {
//fill your forms using your data
}
})
Hope it helps
i have created a site were i have 2 tables on a database. the first page has 2 links which when clicked sends the name of the link to a php session. it then takes you to a page were its meant to view ether one of the databases based on the data that has been saved In the php session.
what i am trying to achieve is to have those links open up the table inside that file that will open up when the link is clicked. i don't want to make a new .php file for every table since i want to be able to simply add and access those tables on one document but not more then one.
that is my problem. on that document were it sends me to access the table from my database i want to access in variable (code below). the code below will explain what i need to know.
this is the code which i view the data in my table
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM tablenamehere ORDER BY id DESC LIMIT 500";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<p>". $row["firstname"]. " " . $row["lastname"] . "</p>";
}
} else {
echo "0 results";
}
$conn->close();
>
the code below is were i want to have the variable that has the name of the link i clicked on the page which gets redirected to this when the link is clicked. the variable that i gather from the php session i want to appear at the tablenamehere text.
$sql = "SELECT id, firstname, lastname FROM tablenamehere ORDER BY id DESC LIMIT 500";
$result = $conn->query($sql);
the code i have so far which creates the php session but is not connected to links yet are below.
<html>
<body>
Register Now!
</body>
</html>
<?php
session_start();
?>
<?php
if(isset($_GET['a'])){
$_SESSION['link']=$_GET['a'];
}
echo "the veriable is " . $_SESSION['link'] . "<br>";
i only want multiple tables to open up in this one php file. thank you for helping, any questions please message below.
If we can assume you are passing a table name as a parameter ( bit dangerous ) then you can do this
<?php
if(isset($_GET['a'])){
$_SESSION['link']=$_GET['a'];
}
$sql = "SELECT id, firstname, lastname
FROM {$_SESSION['link']}
ORDER BY id
DESC LIMIT 500";
But a better way might be to pass an indicator to the table you want to use. This way you are not passing a real table name around in the ether for people to see
if(isset($_GET['a'])){
$_SESSION['link']=$_GET['a'];
}
switch ($_SESSION['link']) {
case : 'a'
$tbl_name = 'table1';
break;
case : 'b'
$tbl_name = 'table2';
break;
default:
$tbl_name = 'default_table';
}
$sql = "SELECT id, firstname, lastname
FROM $tbl_name
ORDER BY id
DESC LIMIT 500";
My guess: the script that accesses the database is test1.php. The link adds already the call parameter a (=newtable):
Register Now!
The script test1.php could honor this $_GET parameter like you do when setting the $_SESSION parameter. The modification of your code would then look like this:
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get and sanitize table name
$tablename = $conn->real_escape_string($_GET['a']);
$sql = "SELECT id, firstname, lastname FROM $tablename ORDER BY id DESC LIMIT 500";
$result = $conn->query($sql);
// ....
Notes:
In my example I assume that all tables are handled the same way. Of course, you could differentiate code based on the value of $tablename.
You most probably would not need a $_SESSION variable.
If, for any reason you must use a $_SESSION variable $_GET['a'] obviously should be overwritten by $_SESSION['link'] or vice-versa.
For security reasons, do not forget to sanitize the input parameter $_GET['a']!
I have a html code with javascript that loads the data from the same directory or a given folder, that's to say the url is just "folder/text.txt".
However, if I want to extract and read this file from a mySQL database named for example exampledb, how can I indicate the new url in my code in order to import the data with Javascript just as I did with a local file?
Thanks!
You will need to use a server side programming language to talk with your database, I would strongly recommend PHP or looking into some more advanced technology like Angular.js along side Node.js!
Here is a quick PHP/mysqli example on pulling data and displaying it in a table.
taken from w3
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]." ".$row["lastname"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
There is several ways to tackle this, that is just a start.
http://www.w3schools.com/php/php_mysql_select.asp
I have created this page to get data from the database, with links to print the shown data and delete it afterwards.
One of the problems is that the JavaScript print function window.print(); wont work.
Another problem is that after printing the page, I would like to update the database, so people can see that it has been printed before.
Alternatively, the function could also print the page and then immediately deletes data, so people won't need to see if it has been printed before or not.
This is the code for getting the data from the database:
<html>
<header>
<script>
function print_table(id)
{
//print your document
window.print();
//send your data
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","http://localhost/Stage/printed_table.php" + id;
xmlhttp.send();
}
</script>
</header>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query("SELECT * FROM orders");
// Count the returned rows
if($resultSet->num_rows != 0){
// Turn the results into an Array
while($rows = $resultSet->fetch_assoc())
{
$id = $rows['id'];
$naam = $rows['naam'];
$achternaam = $rows['achternaam'];
$email = $rows['email'];
$telefoon = $rows['telefoon'];
$bestelling = $rows['bestelling'];
echo "<p>Name: $naam $achternaam<br />Email: $email<br />Telefoon: $telefoon<br /> Bestelling: $bestelling<br /> <a href='delete.php?del=$id'>Delete</a> <input type='button' onclick='print_table($id)' value='Print Table' /> </p>";
}
// Display the results
}else{
echo "Geen bestellingen";
}
?>
</body>
</html>
and these are the pages for the two server-side functions:
delete.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Get ID
$id = $_GET['del'];
$sql= "DELETE FROM orders WHERE id=" . $id . "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query($sql) or die("Failed".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=http://localhost/Stage%201/bestellingen.php'>";
?>
print_table.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$id = $_GET['id'];
$resultSet = $conn->query("UPDATE `orders` SET `printed` = 1 WHERE `id` = `$id`");
?>
You should really check your browser console (F12) to see if there are any JavaScript errors.
One really glaring error I could spot is this line, where the brackets aren't closed. These type of errors could be easily fixed just by checking the console first.
Another error is the variable in the string, it should be sent as a ?key=value pair.
xmlhttp.open("GET","http://localhost/Stage/printed_table.php" + id;
should be:
xmlhttp.open("GET","http://localhost/Stage/printed_table.php?id=" + id, true);
Another problem would be the URL the above line is calling. I notice you mentioned that your PHP file name is called print_table.php instead of printed_table.php.
I have a button that when pressed will create a table in the database.
I tried this
index.html
<button id="loadButton" type="button" class="btn btn-success" style="margin-top:5px;">Carregar Base de Dados</button>
dash.js
$('#loadButton').click(function() {
$.ajax({
url: 'connectdb.php'
});
});
connectdb.php
<?php
$server = 'localhost';
$user = 'root';
$password = '*****';
$database = 'test';
$con = mysql_connect($server, $user, $password, $database);
if (!$con) {
die('error: ' . mysql_error($con));
}
// Create table
$sql="CREATE TABLE Post(
id_post int Primary Key,
titulo varchar(100) not null,
imagem longblob,
descricao varchar(1000) not null,
hashtag varchar(100) not null
)";
// Execute query
mysql_query($con,$sql))
?>
?>
but when I check my database table was not created.
I'm new in jquery, what I'm doing wrong. can someone help me?
Try this and if you want to be shure the php code is called replace all the code with an simple echo and check the response.
$server = 'localhost';
$user = 'root';
$password = '*****';
$database = 'test';
$db = new mysqli($server, $user, $password, $database);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$db->query("
CREATE TABLE Post(
id_post int Primary Key,
titulo varchar(100) not null,
imagem longblob,
descricao varchar(1000) not null,
hashtag varchar(100) not null
)");
First : Please use MySQLi* mysql_* is deprecated.
You have errors in your .php code
mysql_query($con,$sql))
one ) of )) to much
you should have a ; at the end of your command
wrong order $con,$sql
this is OK
mysql_query($sql,$con);
sometimes you should use the database here 'test' in your query
$database = 'test';
...
$sql="CREATE TABLE test.Post(
you should test your result
$result = mysql_query($sql,$con);
if (!$result) {
$message = 'invalid query: ' . mysql_error() . "\n";
$message .= 'your query: ' . $sql;
echo $message;
die($message);
}
To search for errors this is very helpful !
go to connectdb.php directly e.g. http://www.example.com/connectdb.php, fix all the errors and make sure it is working first.