I am quite new to JavaScript and PHP.
I have started lately on my free time to develop a chrme extension to grab some data from db on a hosting server.
I have created a php file and upload it to the server, this file will be called from my extension js file and will connect to the DB to execute a query and return the result back.
everything goes fine except I dnt see the data, it keeps sending me null info.
Connection is ok, credentials are good but somiething is missing.
PHP code:
<?php
header("Access-Control-Allow-Origin: *");
$name = $_POST['name'];
$servername = "139.162.132.71";
$username = "evhoodco_EVhdAdm";
$password = "******";
$dbname = "evhoodco_EVhd623Vehicles";
// Create connection
$dbhandle = new mysqli($servername, $username, $password, $dbname);
if (!$dbhandle)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
echo "Success to connect to MySQL";
}
$result = $dbhandle->query("SELECT 1");
if ( false===$result ) {
printf("error: %s\n", mysqli_error($con));
}
else {
echo ' ... done...';
}
echo json_encode($result);
mysqli_close($dbhandle);
?>
JavaScript code:
$(document).ready(function(){
$.post('http://evhood.com/connDB.php','name=bob').done(function(data){
chrome.bookmarks.create({'parentId': "1",'title': '','url': "http://www.sapo.pt"});
console.log(data);
});
});
And this is the debug window result:
Related
I am using PHP 5.6 to use a database.
$connect = new mysqli($serverName, $username, $password);
if ($connect->connect_error){
$connectError = mysqli_connect_error();
echo('<script> alert("Connection Failed :/'.$connectError.'")</script>');
}else{
echo(('<script> alert("Connection success :)")</script>'));
}
the issue is that $connectError stops the code outputing the javaScript alert how can i inclued the error message and output the alert?
You need to escape your $connectError:
$connect = new mysqli($serverName, $username, $password);
if ($connect->connect_error){
$connectError = addslashes(mysqli_connect_error());
echo('<script> alert("Connection Failed :/'.$connectError.'")</script>');
}else{
echo(('<script> alert("Connection success :)")</script>'));
}
I think the issue is in escaping quote marks. In my PHP code this works perfectly:
$message = "Connection Failed :/" .$connectError;
echo "<script>";
echo "alert(\"" .$message. "\");";
echo "</script>";
I am creating a database to make my 'PHP' website but I couldn't do this. My website is cruzapp that is related to rideshare companies and changing it in to php to get details about our users. But I can't connect MYSQL by using the following PHP code:
?php
$username = "name";
$password = "password";
$hostname = "host";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Not connected to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT id, model,year FROM cars");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:"$row{'id'}." Name:".$row{'model'}."Year: ". //display the results
$row{'year'}.<br>";
}
//close the connection
mysql_close($dbhandle)
?>
Can anyone help me to debug this code?
I will be very thankful to you.
Try this one out. It uses MySQLi with error echoing.
<?php
$username = "name";
$password = "password";
$hostname = "host";
$database = "examples";
$con = mysqli_connect($hostname, $username, $password, $database);
if (!$con) {
exit("Connection failed: " . mysqli_connect_error());
}
$result = mysqli_query($con, "SELECT id, model,year FROM cars");
if (mysqli_error($con)) {
exit("Error: " . mysqli_error($con));
}
while ($row = mysqli_fetch_array($result)) {
echo "ID:" . $row['id'] . " Name:" . $row['model'] . "Year: " . $row['year'] . "<br>";
}
mysqli_close($con);
First of all you should not use mysql because with PHP 7 mysql extension does not work anymore. so you must consider to change it to mysqli or PDO. PDO is recommended. Any how for a quick fix $selected = mysql_select_db($dbhandle,"examples") do this and also check all your values like hostname database name table name and make sure there are no mistakes.
When I click on "subcribeButton" I want it to save the value and pass that value to my PHP file. I want that PHP file to then make a post to the SQL database.
This is my js:
$(".subscribeButton").on( "click", function() {
var email = $(".subscribeInput").val();
var isValid = isEmailValid(email);
if(isValid){
$(".errorMsg").css( "display", "none" );
modal.style.display = "block";
$.post( "save.php", { email: email });
$(".subscribeInput").val("");
} else {
$(".errorMsg").css( "display", "initial" );
};
});
$(".subscribeInput").on( "click", function() {
$(".subscribeInput").val("");
});
This is my php code, I would like my php code to accept data from my js file and then post the data to my sql database:
<?php
$servername = "localhost";
$username = "user";
$password = "pw";
$dbname = "db_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$text = $_POST['email'];
echo $text
$sql = "INSERT INTO MyGuests (email)
VALUES ($text)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The result is I'm getting the following error:
POST http://flockto.it/home/save.php 500 (Internal Server Error)
send # jquery.js:4
ajax # jquery.js:4
m.(anonymous function) # jquery.js:4
(anonymous function) # email.js:13
dispatch # jquery.js:3
r.handle # jquery.js:3
so why not adding a callback in your ajax request so you can debug it in console or with an alert see this it may help you
$.post( "save.php", { "email" : email } , function(result){
console.log(result);//here the result will display what you will echo after getting the post in your php file
});
so in your php file you can add this
if (isset($_POST['email'])){
$text = $_POST['email'];
echo $text;
}
//so if you check the console you will get the email
//value from your php file so then you can insert it at the DB as you want
You have a syntax error.
Your code is missing the ; at the end of this line:
echo $text
It should be:
echo $text;
The solution:
In the js file url was wrong and quotation marks around email were missing
$(".subscribeButton").on( "click", function() {
var email = $(".subscribeInput").val();
var isValid = isEmailValid(email);
if(isValid){
$(".errorMsg").css( "display", "none" );
modal.style.display = "block";
$.post( "data/save.php", { "email": email });
$(".subscribeInput").val("");
} else {
$(".errorMsg").css( "display", "initial" );
};
});
$(".subscribeInput").on( "click", function() {
$(".subscribeInput").val("");
});
In the php file used the wrong variable
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$text = $_POST['email'];
if (isset($_POST['email'])){
$text = $_POST['email'];
echo $text;
}
$sql = "INSERT INTO MyGuests (email)
VALUES ('$text')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
A million thanks to everyone who replied to this thread and helped me solve the issue.
Well For Start I Want To Tank You All For The Help
The Script now it create a table but send empty info
so i have try to do like this:
http://mediaads.eu/villageop/back/savepoints.php?user_id=abcdefghijklm
Now The script wen i call it give me this error:
So I Have Edit The Script code to clean it
so now my code is:
<?php
header('Access-Control-Allow-Origin: *');
error_reporting(E_ALL);
ini_set('display_errors',1);
$servername = "localhost";
$username = "publiadd_publix";
$password = "1a3g7893fsh";
try {
$conn = new PDO("mysql:host=$servername;dbname=publiadd_registervillageop", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
if(isset($_GET['user_id'])){
//$user_id = intval($_GET['user_id']);
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
try {
$dbh = new PDO("mysql:host=$servername;dbname=publiadd_registervillageop", $username, $password);
$user_id = #$_GET['user_id'];
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO users (user_id) VALUES ('".$_POST["user_id"]."')";
if ($dbh->query($sql)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
$dbh = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
$sql->execute(array($user_Id));
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your ID was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'There was a problem saving your points. Please try again later.';
}
}else{
echo 'Your id wasnt passed in the request.';
}
// close MySQL connection
$conn = null;
?>
<html>
<head>
</head>
<body>
<body bgcolor="#ffffff">
</body>
</html>
The method you are using in your forms is GET so use $_GET not $_POST as it goes in your if condition. So replace $_POST with $_GET and second error is your table name it is users table not publiadd_registervillageop so your sql query looks like,
$sql = "INSERT INTO users (user_id) VALUES ('".$_GET["user_id"]."')";
I need some help with MySQL and D3 with a php file.
I am trying to get access to my database using D3. I have created a php file where I make the connection to MySQL.
My problem is however that I get an empty array when printing out my output to the console from D3. I can't seem to find what I am doing wrong. Below is my code for both the D3 call and the php file: (I have appropriate names from username, password and database name.)
<?php
$host = "localhost";
$port = 8889;
$username = "********";
$password = "********";
$database="***datebasename***";
if (!$server) {
die('Not connected : ' .mysql_error());
}
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
if (isset($_GET['type'])) {
$type = $_GET['type'];
} else {
$type = "null";
echo "Type not passed";
}
if($type=='load'){
$string = '';
$gene = $_GET["gene"];
$data = $_GET["data"];
$myquery = "select gene_data.gene_data from genes inner join gene_data on genes.id=gene_data.g_id where genes.name ='$gene' and genes.type='$data'";
$query = mysql_query($myquery);
if ( !$myquery || !$query) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
}
?>
My file are all running from a server. The MySQL server is also on the same server, so I jut call localhost to get access. Also since I need several different parameters for my SQL calls I send the values from D3 ("gene" and "human").
The following the call I make from D3:
d3.json("getdata.php?type=load&gene=CLL5&data=human", function(error, data) {
console.log(data);
});
Also it is worth mentioning that my query is tested and works.
Some help would be greatly appreciated! Any ideas on how to debug with and prints or write.outs would be appretiated as well!