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.
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
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' );
}
I have this php code that updates a row in my MySQL database, based on 3 variables sent with ajax but that returns a http 500 error:
<?php
$dbname = 'xxxxxxxxxx';
$dbuser = 'xxxxxxxxxxxx';
$dbpass = 'xxxxxxxxxxxxx';
$dbhost = 'xxxxxxxxx';
$link = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
$topparent = $_POST['name'];
$column = $_POST['column'];
$value = $_POST['value'];
$sql = "UPDATE reloaded SET" . $column . " = '" .$value . "'WHERE top_parent = '" . $name ."';
$retval = mysql_query( $sql, $link );
if(! $retval ) {
die('Could not create table: ' . mysql_error());
}
echo "success\n";
mysql_close($link);
?>
My jquery js is this. The variables get passed correctly (tried with alert):
function updatedb(a,b,c){
$.ajax({
url: "updatedb.php",
type: 'POST',
data: ({name:a,column:b,value:c}),
success: function(msg) {
alert('DB updated');
}
});
};
Any idea why it returns an error? I have spent some time going over the code, trying different variations but can't seem to figure it out.
There is a PHP syntax error in the SQL query statement.
You have missed to end the " and hence the 500 error.
The corrected code:
$sql = "UPDATE reloaded SET " . $column . " = '" .$value . "' WHERE top_parent = '" . $name ."'";
Edit
Adding to that, there is no space after the SET keyword.
Fixing this will update your db properly.
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 am creating login in angularjs, in login.phppage i am verify whether user exist or not by number of rows exist or not means using rowCount() in php pdo but it always return 0 result. here is my php file:
<?php
/*
* Collect all Details from Angular HTTP Request.
*/
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $request->email;
$pass = $request->password;
$user ="root";
$pass ="m2n1shlko";
$dbh = new PDO('mysql:host=localhost;dbname=blog_db', $user, $pass);
$query = $dbh->prepare("SELECT * FROM `signup_tbl` WHERE `email`='$email' AND `password`='$pass'");
$query->execute();
$count = $query->rowcount();
if($count>0){
echo "You have sucessfully login with this Email: ".$count; //this will go back under "data" of angular call.
}else{
echo "Error While Authentication with this Email: " .$count;
}
/*
* You can use $email and $pass for further work. Such as Database calls.
*/
?>
Data from the controller get here I didn't know where i am missing the code. Apreciate if help .. Thanks
You overwrite $pass to database (line 13) and for user (line 8). Change database password to $db_pass.
...
$email = '...';
$pass = $request->password;
...
$db_pass = '...';
...
$dbh = new PDO('mysql:host=localhost;dbname=blog_db', $user, $db_pass); // $pass to $db_pass
Its $query->rowCount(); NOT $query->rowcount();
$count = $query->rowCount();
if($count>0){
echo "You have sucessfully login with this Email: ".$count; //this will go back under "data" of angular call.
}else{
echo "Error While Authentication with this Email: " .$count;
}
Read Manual rowCount
I have done in my local system,it's working good,Try like below example,this is working fine.just follow this example and do your code right way:
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "xxx";
// Create connection
$conn = new PDO('mysql:host=localhost;dbname=xxx', $username, $password);
$query =$conn->prepare("select * from testing");
$query->execute();
$count = $query->rowCount();
echo "Counting:".$count;
?>
Output:-
Counting:3