PDO Connection issue cannot Insert data into mysql DB - php

I just wanted to create PDO connection rather than old connection but I can't get form fields to be inserted into MYSQL DB. I am sure I am making a stupid mistake however I can't figure it out what exactly.
Here is my database.php file
<?php
$server = 'localhost';
$username = 'root';
$password = '';
$database = 'dbaname';
try{
$conn = new PDO("mysql:host=$server;dbname=$database;", $username, $password);
} catch(PDOException $e){
die( "Connection failed: " . $e->getMessage());
}
and after submit action is taking place at my process.php
<?php
if (!isset($_SESSION)) session_start();
if(!$_POST) exit;
require 'database.php';
include dirname(__FILE__).'/settings/settings.php';
include dirname(__FILE__).'/functions/emailValidation.php';
$TechName = strip_tags(trim($_POST["TechName"]));
$Date = strip_tags(trim($_POST["Date"]));
$ToolSerial = strip_tags(trim($_POST["ToolSerial"]));
$CartridgeSerial = strip_tags(trim($_POST["CartridgeSerial"]));
$TorqueSerial = strip_tags(trim($_POST["TorqueSerial"]));
$LastCalibration = strip_tags(trim($_POST["LastCalibration"]));
$ThreadCond = strip_tags(trim($_POST["ThreadCond"]));
$HardfacingCond = strip_tags(trim($_POST["HardfacingCond"]));
$PocketCond = strip_tags(trim($_POST["PocketCond"]));
//$emailaddress = strip_tags(trim($_POST["emailaddress"]));
/*------------------ STEP 2 ------------------*/
$TorquedOEM = strip_tags(trim($_POST["TorquedOEM"]));
$FullAssembly = strip_tags(trim($_POST["FullAssembly"]));
//$file_url = strip_tags(trim($_POST["file_url"]));
$Notes = strip_tags(trim($_POST["Notes"]));
/*------------------ STEP 3 ------------------*/
//$Signature = strip_tags(trim($_POST["Signature"]));
$SignedDate = strip_tags(trim($_POST["SignedDate"]));
try {
$q = "INSERT INTO tportal (TechName, Date, ToolSerial, CartridgeSerial, TorqueSerial, LastCalibration, ThreadCond, HardfacingCond, PocketCond, TorquedOEM, FullAssembly, Notes, SignedDate)
VALUES (:TechName, :Date, :ToolSerial, :CartridgeSerial, :TorqueSerial, :LastCalibration, :ThreadCond, :HardfacingCond, :PocketCond, :TorquedOEM, :FullAssembly, :Notes, :SignedDate)";
$query = $conn -> prepare($q);
$results = $query -> execute(array(
":TechName" => $TechName,
":Date" => $Date,
":ToolSerial" => $ToolSerial,
":CartridgeSerial" => $CartridgeSerial,
":TorqueSerial" => $TorqueSerial,
":LastCalibration" => $LastCalibration,
":ThreadCond" => $ThreadCond,
":HardfacingCond" => $HardfacingCond,
":PocketCond" => $PocketCond,
":TorquedOEM" => $TorquedOEM,
":TorqueSerial" => $TorqueSerial,
":FullAssembly" => $FullAssembly,
":Notes" => $Notes,
":SignedDate" => $SignedDate,
));
if ($conn->query($q)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted. $PocketCond');</script>";
}
$conn = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
After I click on submit button I get a "Data not successfully inserted pass" pass: is variable result from $PocketCondvariable I placed to test the data.
Thank you for your time.

Apparently after refreshing the database I realized my entries were added to the database however my error scripts were creating problem.
if ($conn->query($q)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted. $PocketCond');</script>";
}

Related

Not able to insert the data from url to database in php

final.php
Here I am trying to get the data from the url using GET method and trying to insert into the database. I was able to insert the data for first few rows after that the data is not inserted. Can anyone help me regarding this?
when I try to run the url: www.myii.com/app/final.php?name=123&glucose=3232...
the data is not inserting.
<?php
include("query_connect.php");
$name = $_GET['name'];
$glucose = $_GET['glucose'];
$temp = $_GET['temp'];
$battery = $_GET['battery'];
$tgs_a = $_GET['tgs_a'];
$tgs_g = $_GET['tgs_g'];
$heartrate = $_GET['heartrate'];
$spo2 = $_GET['spo2'];
$rr = $_GET['rr'];
$hb = $_GET['hb'];
$ina22 = $_GET['ina22'];
$accucheck = $_GET['accucheck'];
$isactive = $_GET['isactive'];
$address = $_GET['address'];
$deviceno = $_GET['deviceno'];
$sql_insert = "insert into query (name,glucose,temp,battery,tgs_a,tgs_g,heartrate,spo2,rr,hb,ina22,accucheck,isactive,address,deviceno) values ('$name','$glucose','$temp',$battery','$tgs_a','$tgs_g','$heartrate','$spo2','$rr','$hb','$ina22','$accucheck','$isactive','$address','$deviceno')";
mysqli_query($sql_insert);
if($sql_insert)
{
echo "Saving succeed";
//echo $date_time;
}
else{
echo "Error occured";
}
?>
Query_connect.php
This is my database config php file.
<?php
$user = "m33root";
$password = "me3i434";
$host = "localhost";
$connection = mysqli_connect($host,$user,$password);
$select = mysqli_select_db('miiyy',$connection);
if($connection)
{
echo "connection succesfull<br>";
}
else {
echo "Error";
}
?>
Make sure that all columns can contain NULL so that not filled fields will stay NULL instead of throwing an error.
Try below to see mysql error:
mysql_query($sql_insert);
echo mysql_error()
Try these
In SQL
Change the table name of query to some other name. Because "query" is reserved in SQL
In code
if (!mysqli_query($con,$sql_insert ))
{
echo("Error description: " . mysqli_error($con));
}
else
{
echo "Success";
}
Use mysqli_error() function

php include not working on host server but works on local (xampp) server

I cannot resolve why what works locally fails at the host server. It connects to the database, retrieves and displays data, but it fails to retrieve the data and include the form. Hopefully, I have included enough code.
First the data is retrieved and displayed:
/*------------------- DISPLAY ACCESSORIES ------------------*/
if(isset($_GET['table']) && $_GET['table'] === "accessories")
{
$table = 'accessories';
include '../includes/dbconnect.php';
try {
$result = $db->query("SELECT * FROM $table");
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$accessories[] = array(
'id' => $row['id'],
'buy_link' => $row['buy_link'],
'img' => $row['img'],
'item_number' => $row['item_number'],
'name' => $row['name'],
'description' => $row['description'],
'laser_series' => $row['laser_series'],
'laser_model' => $row['laser_model'],
'quantity' => $row['quantity'],
'price' => $row['price'],
);
}
}
catch (PDOException $e)
{
$error = 'Error fetching data.' . $e->getMessage();
include 'error.html.php';
exit();
}
try {
$sql2 = 'DESCRIBE accessories';
$s2= $db->prepare($sql2);
$s2->execute();
$table_fields = $s2->fetchAll(PDO::FETCH_COLUMN);
}
catch (PDOException $e)
{
$error = 'Error fetching data from database.';
include 'error.html.php';
exit();
}
// Close database connection
$db = null;
// Display data on included page
include 'display-accessories.html.php';
exit();
}
Then, in the row the user wishes to edit, he clicks the edit button. Here's that html:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<input type="hidden" name="id" value="<?php htmlout($accessory['id']); ?>">
<button class="btn btn-default btn-sm" type="submit" name="action" value="edit_accessories">Edit</button>
</form>
Clicking the edit button triggers this php, which fails (not locally). It does not include the file (the path is correct; in the same folder).
/*------------------- EDIT ACCESSORIES ------------------*/
if(isset($_POST['action']) && $_POST['action'] === "edit_accessories")
{
// Assign name of table being queried to variable
$table = 'accessories';
// Sanitize posted data
$id = sanitize($_POST['id']);
// Connect to database
include '../includes/dbconnect.php';
try {
$sql = "SELECT * FROM $table WHERE id = :id";
$s = $db->prepare($sql);
$s->bindValue(':id', $id);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error fetching data.' . $e->getMessage();
include 'error.html.php';
exit();
}
// Store single row result in $item associative array
$item = $s->fetch(PDO::FETCH_ASSOC);
// Close database connection
$db = null;
// Display row content in form
include 'edit-accessories-form.html.php';
exit();
}
If anyone has any ideas why this does not work, I welcome your insight!
Just change the sentence:
FROM: '../includes/dbconnect.php';
TO: $_SERVER['DOCUMENT_ROOT'].'/includes/dbconnect.php';
In the server the path can't be write as '../' because there is a whole different server path configuration.

How to UPDATE only filled input with a submit button?

PROBLEM: I got a problem updating my input into sql using PHP, the PHP updates all empty values into sql which I don't want to.
ACHIEVEMENT: So I hope to achieve when user submit their data either empty or filled then PHP might be able to pickup and update only filled data into my sql. I tried using input with value=">php echo here<" but it won't work with textarea, so I couldn't find any solution since I'm new to PHP and SQL. Tried to find similar posts but I couldn't make them work like I wanted to :(
<?php include 'config/sqlconnect.php'; ?>
<form method="post" action"config/sqlconnect.php">
</p>MainPage info</p>
<input type="text" name="mainPageInfo"/>
<br>
</p>MiddlePage info</p>
<textarea name="middlePageInfo"></textarea>
<br>
</p>Container info</p>
<input type="text" name="containerInfo"/>
<br>
</p>Content</p>
<input type="text" name="content"/>
<br>
</p>Second content</p>
<input type="text" name="secondContent"/>
<input type="submit" name="submit" class="btn-block"/>
<br>
</form>
in PHP script
<?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "pagesDb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn,"utf8");
$sql = "SELECT * FROM myPages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$mainPageInfo = $row['mainPageInfo'];
$middlePageInfo = $row['middlePageInfo'];
$containerInfo = $row['containerInfo'];
$content = $row['content'];
$secondContent = $row['secondContent'];
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
$mainPageInfo = $_POST['mainPageInfo'];
$middlePageInfo = $_POST['middlePageInfo'];
$containerInfo = $_POST['containerInfo'];
$content = $_POST['content'];
$secondContent = $_POST['secondContent'];
$sql = "UPDATE myPages SET mainPageInfo='$mainPageInfo',
middlePageInfo='$middlePageInfo',
containerInfo='$containerInfo',
content='$content',
secondContent='$secondContent'
WHERE id=0";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
Second Attempts: It doesn't update my data somehow... please help I tried more than 8 hours with no results :(
if (isset($_POST['submit'])) {
foreach($_POST as $name => $value) {
$sql = "UPDATE myPages SET $name = '$value' WHERE id=1";
}
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
Help would be appreciated, thanks everyone!
Using your Second Attempt as a starting point.
The problem with just using the POST array without being specific is that, in this example you are going to try an update a column on the database called submit i.e. your submit button. Later there may be data on the page that belongs in 2 or more tables.
So create an controlling array containing all the field names from the form that you want to process onto your table.
$db_fields = array('mainPageInfo', 'middlePageInfo', 'containerInfo',
'content', 'secondContent');
$sql = ''; // will hold the query we build dynamically
// was this a user sending data
if ( $_SERVER['REQUEST_METHOD' == 'POST' ) {
foreach($db_fields as $fieldname) {
if ( ! empty($_POST[$fieldname] ) {
$sql .= "$fieldname = '{$_POST[$fieldname]}', ";
}
}
}
$sql = rtrim($sql, ','); // remove the trailing comma
$sql = "UPDATE myPages SET $sql WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

PHP get data from jquery

Im trying to write a simple prgram that the server can get data from client.
I write a simple code in my script
var str = "testString";
$.post("http://anonymous.comze.com/test1.php", { string: str });
in the server,
$var = $_POST['string']; // this fetches your post action
$sql2 = "INSERT INTO afb_comments VALUES ('3',$var)";
$result2= mysql_query($sql2,$conn);
The question is var is always null. The sql2 can be executed if I change $var into "1111" for example,
but if I put $var, it doesn't work. Can anyone give some advice?
your are passing string to the query so it should be
$var = $_POST['string']; // this fetches your post action
$sql2 = "INSERT INTO afb_comments VALUES ('3','".$var."')";
$result2= mysql_query($sql2,$conn);
please also check datatype of the that column.
Use this example and learn from this code how to get data
Or
use can also use this link:
http://api.jquery.com/jQuery.get/
$user and $pass should be set to your MySql User's username and password.
I'd use something like this:
JS
success: function(data){
if(data.status === 1){
sr = data.rows;
}else{
// db query failed, use data.message to get error message
}
}
PHP:
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$databaseName = "movedb";
$tableName = "part parameters";
$con = mysql_pconnect($host, $user, $pass);
$dbs = mysql_select_db($databaseName, $con);
//get the parameter from URL
$pid = $_GET["pid"];
if(empty($pid)){
echo json_encode(array('status' => 0, 'message' => 'PID invalid.'));
} else{
if (!$dbs){
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t connect to the db'));
}
else{
//connection successful
$sql = "SELECT `Processing Rate (ppm)` FROM `part parameters` WHERE `Part Number` LIKE `" . mysqli_real_escape_string($pid) . "`"; //sql string command
$result = mysql_query($sql) or die(mysql_error());//execute SQL string command
if(mysql_num_rows($result) > 0){
$rows = mysql_fetch_row($result);
echo json_encode(array('status' => 1, 'rows' => $rows["Processing Rate (ppm)"]);
}else{
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t find processing rate for the give PID.'));
}
}
}
?>
As another user said, you should try renaming your database fields without spaces so part parameters => part_parameters, Part Number => part_number.

PHP certain part of code is not executing

Hi I am facing a unique issue with my PHP script.Here is my code. After writeToDB() is executed I dont see the echo ("<script> top.location.href=www.facebook.com</script>");
Can someone let me know why my script stops executing after writing to db?
<?php
function writeToDB($access_token,$uid,$username,$birthday,$gender,$age)
{
/* Database Connection */
$user = "xxxx";
$password = "xxxx";
$host = "xxxxxxxxxxxxxxxxxx";
//connect to database, where tsnames.ora is setup
$connect_obj = oci_connect($user, $password, $host);
if ($connect_obj) {
error_log("connected okay");
} else {
$err = OCIError();
echo "Oracle connection error " . $err[text];
return;
}
$select_query = "SELECT USER_ID FROM FBTABLE WHERE USER_ID= '$uid'";
$select_sql_stmt = oci_parse($connect_obj, $select_query);
//execute statement
try {
$r = oci_execute($select_sql_stmt, OCI_DEFAULT);
if (!$r) {
$p = oci_error($select_sql_stmt);
echo "Oci Execute error";
}
} catch (Exception $e) {
echo "<br>Failed to get database info" . $e->getMessage();
}
$user_id_in_db = null;
while (oci_fetch($select_sql_stmt)) {
$user_id_in_db = oci_result($select_sql_stmt, 'USER_ID');
}
// User already exists in db so update instead of insert
if ($user_id_in_db != null) {
$query ="UPDATE FBTABLE SET ACCESS_TOKEN='$access_token' WHERE USER_ID='$uid'";
} else {
$query = "INSERT INTO FBTABLE(ACCESS_TOKEN, USER_ID,USER_NAME,BIRTHDAY,GENDER,AGE)
VALUES
('$access_token','$uid','$username','$birthday','$gender','$age')";
}
//create sql statement
$sql_statement = oci_parse($connect_obj, $query);
//execute statement
try {
$r = oci_execute($sql_statement, OCI_DEFAULT);
if (!$r) {
$p = oci_error($sql_statement);
echo "Oci Execute error";
}
} catch (Exception $e) {
echo "<br>Failed to get database info" . $e->getMessage();
}
//Commit transaction
$committed = oci_commit($connect_obj);
//Test whether commit was successful. If error occurred, return error message
if (!$committed) {
$error = oci_error($conn);
echo 'Commit failed. Oracle reports: ' . $error['message'];
}
//close the connection
$oci_free_statement($sql_statement);
if (oci_close($connect_obj)) {
echo " oci connection not closed!!!";
}
//close the connection
$oci_free_statement($sql_statement);
}
?>
<html>
<body>
<?php
$access_token = $_GET['access_token'];
$uid = $_GET['uid'];
$username = $_GET['username'];
$birthday = $_GET['birthday'];
$gender = $_GET['gender'];
$age = $_GET['age'];
echo $username;
writeToDB($access_token,$uid,$username,$birthday,$gender,$age);
echo ("<script> top.location.href=www.facebook.com</script>");
?>
</body>
</html>
i think error is in $oci_free_statement($sql_statement); must be oci_free_statement($sql_statement); extra $ before oci_free_statement
http://php.net/manual/en/function.oci-free-statement.php
no any error show because of error_display is off
Your JavaScript code should be
echo ("<script> top.location.href='http://www.facebook.com';</script>");
It's happen because writeToDB() causes error. You don't see this error because error_display is off or error_reporting = 0
Also maybe you didn't install OCI8. So when you call oci_connect it will cause error.
Thanks.
you are not using quotes around the string:
www.facebook.com should be 'www.facebook.com'

Categories