How do I insert data from a php file using PDO? - javascript

I'm trying to log some data for my website using PDO from a PHP file. I have the following code which is called by by a javascript library, D3. The call works fine, but when I run this code I get an "internal server error".
What am I doing wrong? I have been following a guide on a website and I am basically using the same principles as them. If anyone can help I'd appreciate it. Thanks a lot in advance, my code is pasted below. (Of course the database information is something valid)
$hostname="xxxx";
$username="xxxxxx";
$pw="xxxxxxxx";
$dbname="xxxx";
try {
$pdo = new PDO ("mysql:host=$hostname;dbname=$dbname","$username","$pw");
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
//Gets IP for client.
$ip = get_client_ip();
//An email, format of string.
$email = "test#test.dk";
//An int, in this case 19.
$prgm_name = $_GET["prgm"];
//Piece of text, format of string of course.
$prgm_options.=$prgm_name;
$prgm_options.= " - ";
$prgm_options.=$_GET["gene"];
$prgm_options.=" - ";
$prgm_options.=$_GET["data"];
//Datasize, int.
$data_size = 0;
//Timestamp.
$now = "NOW()";
//Table name.
$STAT_TABLE = "stat";
$query = $pdo->prepare("INSERT INTO $STAT_TABLE (ip, email, prgm, options, datasize, date) VALUES (:ip, :email, :prgm_name, :prgm_options, :data_size, :now);");
$query->execute(array( ':ip'=>'$ip',
':email'=>'$email',
':prgm_name'=>$prgm_name,
':prgm_options'=>'$prgm_options',
':datasize'=>'$datasize',
':now'=>$now));

Try the following Code to Insert
$count = $pdo->exec("INSERT INTO $STAT_TABLE(ip, email, prgm, options, datasize, date) VALUES ('$ip','$email',$prgm_name,'$prgm_options','$datasize',$now)))");
/*** echo the number of affected rows ***/
echo $count;

I like to bind each parameter individually. I think it gives you more control over data types and sizes.
try {
$sth = $pdo->prepare("INSERT INTO...");
$sth->bindParam(":ip", $ip, PDO::PARAM_STR, 16);
$sth->bindParam(":email", $email, PDO::PARAM_STR, 30);
// etc...
$sth->execute();
} catch (Exception $e) {
print_r($e);
}

Related

JAVA SCRIPT var with Double Quotes to PHP and back for Auto fill

I have an HTML/PHP form that uses JAVA SCRIPT function to send (POST) an input content to a PHP code which performs a query and gets back to the JAVA SCRIPT function with data to Auto fill additional inputs in the form.
It all works great when the input content i send is plain text, even if there is a single quote in the content it works.
BUT, as soon as double quotes are included in the input content it fails to return the Auto fill results.
Appreciate your help with indicating where do i fail with passing the quotes.
Thanks
Just to make it clearer, the code works if customer name is "Intel" or "Int'el" , but it fails when customer name is "Int"el"
Here is the JAVA SCRIPT function that sends and receive the data from the PHP:
!--Script Auto fill ltd by customer -->
<script type="text/javascript">
function updatefrm() {
setTimeout(function(){
var customer = $('#customer').val();
if ($.trim(customer) !='') {
$.post('customerfill.php', {customer: customer}, function(data) {
$('#customerupdate').val(data['customer']);
$('#ltdupdate').val(data['ltd']);
});
}
}, 10);
}
</script>
Here is the PHP code that gets the POST data , performs the query, and sends back the array for the JAVA SCRIPT auto fill:
<?php
if (!empty($_POST['customer'])) {
$DB_Server = "localhost"; // MySQL Server
$DB_Username = "XXXX"; // MySQL Username
$DB_Password = "XXXX"; // MySQL Password
$DB_DBName = "XXXXXXXX"; // MySQL Database Name
$Connect = #mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Failed to connect to MySQL:<br />" . mysql_error() . "<br />" . mysql_errno());
// Select database
$Db = #mysql_select_db($DB_DBName, $Connect) or die("Failed to select database:<br />" . mysql_error(). "<br />" . mysql_errno());
mysql_query('SET NAMES utf8');
mysql_query('SET CHARACTER SET utf8');
$safe_name = mysql_real_escape_string(trim($_POST['customer']));
$query = mysql_query(" SELECT * FROM customers WHERE customer = '". $safe_name ."' LIMIT 1 ");
if (mysql_num_rows($query) > 0) {
$row = mysql_fetch_assoc($query);
json($row);
} else {
json(null);
}
}
function json ($array) {
header("Content-Type: application/json");
echo json_encode($array);
}
i think your js code is fine and i think error in your php code and in that line
$query = mysql_query(" SELECT * FROM customers WHERE customer = '". $safe_name ."' LIMIT 1 ");
so you should use PDO Prepared Statements for security and not face problem with double quote
$dsn = "mysql:host=localhost;dbname=your_database;charset=utf8mb4";
try {
$pdo = new PDO($dsn, "database_username", "database_password");
} catch (Exception $e) {
echo "no connection";
exit();
}
$stmt = $pdo->prepare("SELECT * FROM customers WHERE customer = :customer LIMIT 1");
$stmt->execute(array(":customer"=>$safe_name));
$row = $stmt->fetch();

Upgrading my PHP chat system? (Making it only update new messages?)

JS:
"use strict";
$(document).ready(function () {
var chatInterval = 250; //refresh interval in ms
var $userName = $("#userName");
var $chatOutput = $("#chatOutput");
var $chatInput = $("#chatInput");
var $chatSend = $("#chatSend");
function sendMessage() {
var userNameString = $userName.val();
var chatInputString = $chatInput.val();
$.get("./write.php", {
username: userNameString,
text: chatInputString
});
$userName.val("");
retrieveMessages();
}
function retrieveMessages() {
$.get("./read.php", function (data) {
$chatOutput.html(data); //Paste content into chat output
});
}
$chatSend.click(function () {
sendMessage();
});
setInterval(function () {
retrieveMessages();
}, chatInterval);
});
Write.php:
<?php
require("connect.php");
//connect to db
$db = new mysqli($db_host,$db_user, $db_password, $db_name);
if ($db->connect_errno) {
//if the connection to the db failed
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
//get userinput from url
$username=substr($_GET["username"], 0, 32);
$text=substr($_GET["text"], 0, 128);
//escaping is extremely important to avoid injections!
$nameEscaped = htmlentities(mysqli_real_escape_string($db,$username)); //escape username and limit it to 32 chars
$textEscaped = htmlentities(mysqli_real_escape_string($db, $text)); //escape text and limit it to 128 chars
//create query
$query="INSERT INTO chat (username, text) VALUES ('$nameEscaped', '$textEscaped')";
//execute query
if ($db->real_query($query)) {
//If the query was successful
echo "Wrote message to db";
}else{
//If the query was NOT successful
echo "An error occured";
echo $db->errno;
}
$db->close();
?>
Read.php
<?php
require("connect.php");
//connect to db
$db = new mysqli($db_host,$db_user, $db_password, $db_name);
if ($db->connect_errno) {
//if the connection to the db failed
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
$query="SELECT * FROM chat ORDER BY id ASC";
//execute query
if ($db->real_query($query)) {
//If the query was successful
$res = $db->use_result();
while ($row = $res->fetch_assoc()) {
$username=$row["username"];
$text=$row["text"];
$time=date('G:i', strtotime($row["time"])); //outputs date as # #Hour#:#Minute#
echo "<p>$time | $username: $text</p>\n";
}
}else{
//If the query was NOT successful
echo "An error occured";
echo $db->errno;
}
$db->close();
?>
Basically everything works perfectly, except I want to allow people to copy and paste, but what the script is doing at the moment is updating every message at the chatinterval which is 250MS.
How can I make it so I can highlight a message and copy it?
So my question is, can I do this:
Can I make it only update the new messages that appear every 250-500MS instead of updating every last bit of HTML as that is a waste of resources (Especially if there was a lot of messages)
I hope you can help!
p.s. I don't want to use web sockets
To make it update just starting from the last message, get the ID of the last message, and then in your next $.get include the id of that message and get only messages that came after that.
And then use .append() in your javascript so you're not overwriting the whole thing.
It looks like you're already using jQuery. You can create a PHP script that only queries the database for entries newer than the newest one displayed, then use $.append to append the message to the <div> (or whatever other element) that holds it.
Also, as the commenter pointed out, you're still probably susceptible to SQL injection. Considering using PDO with prepared SQL statements.

i can't put the input data into the database

this is my code. i've done this before in other computer and it's okay, but now when try it in my laptop,it can't be done. idk what is the problem, it will show blank in phpmyadmin. i'm using xampp v3.2.2, is that will be the problem?
<html><head><title>Your Data</title></head>
<body>
<?php
$n = $_POST["n"];
$c = $_POST["contact"];
$e = $_POST["email"];
$cm = $_POST["campus"];
$m1 = $_POST["member1"];
$m2 = $_POST["member2"];
$m3 = $_POST["member3"];
$connect = mysqli_connect("localhost","root","") or die("Unable to connect MySQL".mysqli_error());
$db = mysqli_select_db($connect,"multimedia_db") or die("Unable to select database");
$query1 = "INSERT INTO teams(advisor_name,advisor_contact,advisor_email,advisor_campus,member1,member2,member3) VALUES ('$n','$c','$e','$cm','$m1','$m2','$m3')";
$data1 = mysqli_query($connect,$query1) or die("SQL statement failed"); //records are assigned to variable data
echo "You've succesfully register";
?>
</body>
</html>
I don't use MySQLi very often. So I'll explain how to use PDO. Just so you know PDO means PHP Data Objects. The reason I'm explaining, PDO is because, if done properly, it makes SQL injection almost impossible.
Connection
connecting to your database is generally done in a separate file. Here is an example:
con.php
<?php
$hostname = '';
$username = '';
$password = '';
$dbname = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
This is just connecting to the database, so we don't have to keep connecting to other pages, we just refer to this page with an include, like this:
<?php include 'con.php'; ?>
We can put this on any page and it'll include the connection to the database. For example, if you want to select from a database:
<?php
include 'con.php';
$load_data = $dbh->prepare("SELECT * FROM user_table");
if ($load_data->execute()) {
$load_data->setFetchMode(PDO::FETCH_ASSOC);
}
while ($row = $load_data->fetch()) {
$name = $row['name'];
echo $name;
}
?>
This would simply SELECT everything from the user_table from the column name and would display all the matching records.
If you're trying to do an INSERT instead:
<?php
include 'con.php';
$post_name = $_POST['post_name'];
$stmt = $dbh->prepare("INSERT INTO user_table (name) VALUES (:user_name)");
$stmt->bindParam(':user_name', $post_name, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "Success";
} else {
echo "Failed";
}
?>
So the $post_name would be the name you give your input on a form in this case name="post_name" that would be inserted into the user_table.
Hope this helps and FYI here is a very good tutorial on how to do INSERT, UPDATE and DELETE using PDO.
i've found the solution for my question. It's just that i forgot to put localhost in front of the 'url'. no wonder it showed blank.
like 'localhost/sem5/saveRegistration.php'.
i'm sorry for the inconvenience. still a beginner using this hehe

mysql query from php isnt working but it works in a different php file

I'm trying to make a query from my MySQL database here is the code
<?php
$link = new MySQLi('localhost','root','Rrtynt','copy');
if(isset($_POST['id'])){
$name = $_POST['id'];
$profile = 'profile';
$thestring = $name.$profile;
//echo $thestring;
$result = $link->query("SELECT Email,Name,idauth FROM user WHERE Email = '$name'");
echo $result;
}
?>
the code for the query
$result = $link->query("SELECT Email,Name,idauth FROM user WHERE Email = '$name'");
works in a different php script the same exact code but it keeps giving me http 500 error, I'm using this to post from a javascript file
$.post("/getfirstfolder.php", { id: value1 }, function (data) {
cop = data;
console.log("Data: " + data);
});
if I take out
$result = $link->query("SELECT Email,Name,idauth FROM user WHERE Email = '$name'");
and just echo $thestring it works fine, I cant figure out the problem so thank you for your time and your help is greatly appreciated
The fact that you mentioned $thestring, makes me think that perhaps you should be using $thestring as the parameter to the query like this:
$result = $link->query("SELECT Email,Name,idauth FROM user WHERE Email = '$thestring'");

"CLI has stopped working" when trying to select all from an Oracle Database using JQuery?

I am attempting to use JavaScript and Jquery to search a database. I have set up a generic query.php file so that I can pass in the database and query and have it return an array. For some reason, when I try to select all using the *, my PHP server crashes with:
I am using the built in server with PHP 7.0.2. I am attempting to retrieve information from a Oracle database.
Here is the post statement:
$.post(DB1.filename,
{sid: DB1.sid,
username: DB1.username,
password: DB1.password,
host: DB1.host,
port: DB1.port,
sql: query},
function(res){
if(res == -1){
res = errorCode(DATABASE_CONNECTION_ERROR);
} else {
var a = parseObject(res);
var t = parseTable(a);
elements[TABLE].element.innerHTML = t;
}
log(FILE_NAME, "RETRIEVED query ");
}
);
Here is the query.php:
<?php
/* This script will connect to a database and search the given SQL string.
If the connection cannot be established, it will return -1. Otherwise, it will return a JSON array.
*/
//Parameters
$sql = $_POST["sql"];
//Database Information
$user = $_POST["username"];
$pass = $_POST["password"];
$host = $_POST["host"];
$port = $_POST["port"];
$sid = $_POST["sid"];
$connection = "(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = " . $host .")(PORT = " . $port . ")) (CONNECT_DATA = (SID = " . $sid . ")))";
//Establish connection
$conn = oci_connect($user, $pass, $connection);
//Check connection
if(!$conn){
echo -1;
} else {
//Query for the given SQL statement
$stRows = oci_parse($conn, $sql);
oci_execute($stRows);
oci_fetch_all($stRows, $res); //This is where the everything actually crashes
echo json_encode($res);
//Close the connection
oci_close($conn);
}
?>
So if I set the query as:
query = "select TABLE_NAME from ALL_TABLES";
everything works just fine. A table with a single column will be printed to the screen.
However, if I run:
query = "select * from ALL_TABLES";
I get the error above.
This happens regardless of which table I am attempting to connect to. My credentials are correct and I have tried different credentials as well. Any ideas why this is happening?
--UPDATE--
I tried hard coding the column names. I can select up to 8 columns before it crashes.There are 152 rows.
I circumvented the error by swapping the oci_fetch_all for oci_fetch_array as follows:
<?php
...
} else {
//Query for the given SQL statement
$stRows = oci_parse($conn, $sql);
oci_execute($stRows);
$res = array();
while($row = oci_fetch_array($stRows, OCI_NUM)){
$res[] = $row;
}
echo json_encode($res);
//Close the connection
oci_close($conn);
}
?>
This meant drastic changes to the function used to decode the JSON object array, but it does work. I will not mark this answer as correct though because I would very much like to know why my original code wasn't working...

Categories

Resources