Insert data to mysql doesn't work from php - php

I have the following PHP code:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$insert_query = mysql_query("INSERT INTO articles(articleTitle, articleContent, typeID)
VALUES
('$_POST[articleTitle]','$_POST[articleContent]',$_POST[articleType])");
}
typeID => is number, the other values are text.
There is no error in this code, but the insert query doesn't work (I have no idea why because I don't get any error message).
How can I fix it?

There are a number of problems with your code.
It's open to SQL injectoion
mysql_* functions have been deprecated
This code is untested but should give you an idea:
try
$dbh = new PDO('mysql:host=localhost;dbname=your_database_name', $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare('INSERT INTO Persons (articleTitle, articleContent, typeID) VALUES (:articleTitle, :articleContent, :articleType)');
$sth->execute($_POST);
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
}
Have a look at this article on Why you Should be using PHP’s PDO for Database Access

Try this
if(isset($_POST[articleTitle])) {
$insert_query = mysqli_query("INSERT INTO Persons (articleTitle, articleContent,typeID)
VALUES
('$_POST[articleTitle]','$_POST[articleContent]',$_POST[articleType])");
}

Related

BeginTransaction can not work in PHP mysql

I want to insert data into CLOUD and IDC tables.
Cloudid is the foreign key of IDC table, so i want to use transaction.
Before $conn->beginTransaction(); and $conn->commit(); are added ,it works fine, but without them, it works fine.
Here is my code:
<?php
if($_GET["act"]=="add")
{
try
{
$conn=new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'root' , 'xxxx');
//$conn->beginTransaction();
$query="
insert into CLOUD (name,date) VALUES('".$_POST['customerName']."','".$_POST['firstDay']."');
insert into IDC (name,id,phone,cloudid) VALUES('".$_POST['engName3']."','".$_POST['engID3']."','".$_POST['engPhone3']."',LAST_INSERT_ID());
insert into IDC (name,id,phone,cloudid) VALUES('".$_POST['engName4']."','".$_POST['engID4']."','".$_POST['engPhone4']."',LAST_INSERT_ID());
";
$stmt=$conn->query($query);
//$conn->commit();
echo "success";
}
catch(PDOException $e)
{
$conn->rollBack();
echo "connect failed!".$e->getMesage();
exit;
}
}
?>
Transactions are only available when the database uses InnoDB as the storage engine. You are probably using MyISAM
Have a look here for more details on the difference between the storage engines https://dev.mysql.com/doc/refman/5.7/en/storage-engines.html
As a side note, your code is vulnerable to SQL injections because you use raw post data in non prepared queries. you should have a look there : How can I prevent SQL injection in PHP?
Try to initiate your connection and get last inserted id like below, also i would recommend you to use prepared statements (see http://php.net/manual/ru/pdo.prepare.php):
if($_GET["act"]=="add")
{
try {
$dbh = new PDO('mysql:host=localhost;port=3306;dbname=xxx', 'root', 'xxx',
array(PDO::ATTR_PERSISTENT => true));
echo "Connected\n";
} catch (Exception $e) {
die("Unable to connect: " . $e->getMessage());
}
try {
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->beginTransaction();
$stmt = $dbh->prepare('insert into CLOUD (name,date) VALUES(:customerName,:firstDay)');
$stmt->execute([
'customerName' => $_POST['customerName'],
'firstDay' => $_POST['firstDay']
]);
$cloud_id = $dbh->lastInsertId();
$stmt = $dbh->prepare('insert into IDC (name,id,phone,cloudid) VALUES(:name,:id,:phone,:cloudid)');
$stmt->bindParam(':name', $name);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':phone', $phone);
$stmt->bindParam(':cloudid', $cloud_id);
$name = $_POST['engName3'];
$id = $_POST['engID3'];
$phone = $_POST['engPhone3'];
$stmt->execute();
$name = $_POST['engName4'];
$id = $_POST['engID4'];
$phone = $_POST['engPhone4'];
$stmt->execute();
$dbh->commit();
} catch (PDOException $e) {
$dbh->rollBack();
echo "Failed: " . $e->getMessage();
}
}

PDO : Need to escape string or not ?

I use this code to insert some data into my database.
I adapt my previous code based on mysqli to use PDO now.
For the 2 parameters name and id, do i need to escape them using a function like mysqli_real_escape_string with PDO ? or is it OK to pass these params direclty in the query ?
<?php
try
{
$pdo = new PDO('mysql:host='.$servername.';port='.$dbport.';dbname='.$dbname.'', $username, $decodedPwd);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$json = $_POST['jsonData'];
$id = $json["id"]
$name = $json["name"]
$pdo->beginTransaction();
// do request
$pdo->query('INSERT INTO test(id, name) VALUES ('$id', '$name')');
$pdo->commit();
echo 'Everything is OK';
}
catch(Exception $e)
{
$pdo->rollback();
echo 'An error occurred :<br />';
echo 'Error : '.$e->getMessage().'<br />';
echo 'N° : '.$e->getCode();
exit();
}
You need to prepare your statement, try this:
$query = $pdo->prepare('INSERT INTO test(id, name) VALUES (:theid, :thename)');
$query->execute(array(
'theid' => $id,
'thename' => $name
));
You don't have to escape strings but you have to use preared statements.
Here is what your code should be.
<?php
$pdo = new PDO('mysql:host='.$servername.';port='.$dbport.';dbname='.$dbname.'', $username, $decodedPwd);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$json = $_POST['jsonData'];
$pdo->prepare('INSERT INTO test(id, name) VALUES (:id,:name)')->execute($json);
echo 'Everything is OK';
note that a transaction is useless for just a single query and the way you are reporting errors is wrong.
also, if $json already contains the all the data for thequery, no need to store its contents in separate variables.
It's not okay. You need to use prepared statements or PDO::quote().

insert postgis geometry with GET values

I'm trying to make an insert using ST_Makepoint with get values, but I run into 500 Error.
This is my php code:
<?php
try {
$user = 'user';
$dbh = new PDO('pgsql:host=localhost;dbname=userdb', $user);
$stmt = $dbh->prepare("INSERT INTO table(id_a, id_b, geom) VALUES (?,?,?);");
if ($stmt->execute(array($_GET['id_a'], $_GET['id_b'], ST_SetSRID(ST_MakePoint($_GET['lat'], $_GET['long']),4326)))) {
print_r("OK");
} else {
print_r("Error");
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
If I run this query with pgAdmin, it runs well:
INSERT INTO table(id_a, id_b, geom) VALUES (1,1,ST_SetSRID(ST_MakePoint(2, 2),4326));
Do you know how to fix the problem in php code?
I solved in this way:
$stmt = $dbh->prepare("INSERT INTO table(id_a, id_b, geom) VALUES (?,?,ST_SetSRID(ST_MakePoint(?, ?),4326));");
if ($stmt->execute(array($_GET['id_a'], $_GET['id_b'], $_GET['lat'], $_GET['long']))) {
print_r("OK");
} else {
print_r("Errore");
}

More efficient way of inserting using PDO?

Hi I am inserting image data into a database each time an image is uploaded to my server. The code I am using looks a bit 'chunky' especially the binds. Can it be done differently to reduce the amount of text and execute more quickly or should I not worry about it?
Here is the code I am using:
function($file_name, $cat, $year, $desc, $title, $image_size, $image_width, $image_height){
//test the connection
try {
//connect to the database
$dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
$stmt = $dbh->prepare("INSERT INTO mjbox_images(img_file_name,img_cat,
img_year,img_desc,img_title,img_size,img_width,img_height)
VALUES(?,?,?,?,?,?,?,?)");
$stmt->bindParam(1,$file_name);
$stmt->bindParam(2,$cat);
$stmt->bindParam(3,$year);
$stmt->bindParam(4,$desc);
$stmt->bindParam(5,$title);
$stmt->bindParam(6,$image_size);
$stmt->bindParam(7,$image_width);
$stmt->bindParam(8,$image_height);
$stmt->execute();
}
Depending on how much code you want to rewrite, you could always swap from using pure PDO to something like RedBean (which is actually quite nice, being a zero-config ORM).
http://www.redbeanphp.com/
Worth a look, even if you won't use it now; it's definitely a great tool.
Inserts would then take just modifying bean properties, reducing the overall amount of code you'd use.
You could do it like this, passing an array of values and use the keys as place holders, that way you can use the same function to insert into different tables:
<?php
$insert = array('img_file_name'=>'',
'img_cat'=>'',
'img_year'=>'',
'img_desc'=>'',
'img_title'=>'',
'img_size'=>'',
'img_width'=>'',
'img_height'=>'');
insert('mjbox_images',$insert);
function insert($table,$values=array()){
//test the connection
try{
//connect to the database
$dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
$fieldnames = array_keys($values);
$sql = "INSERT INTO $table";
$fields = '( ' . implode(' ,', $fieldnames) . ' )';
$bound = '(:' . implode(', :', $fieldnames) . ' )';
$sql .= $fields.' VALUES '.$bound;
$stmt = $dbh->prepare($sql);
$stmt->execute($values);// whoops
}
//INSERT INTO mjbox_images( img_file_name ,img_cat ,img_year ,img_desc ,img_title ,img_size ,img_width ,img_height ) VALUES (:img_file_name, :img_cat, :img_year, :img_desc, :img_title, :img_size, :img_width, :img_height )
?>

How to handle PDO exceptions [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 7 years ago.
I'm trying to work with PDO class on php but I have some trouble to find the right way to handle errors, I've wrote this code:
<?php
// $connection alreay created on a class which works with similar UPDATE statements
// I've simply added here trim() and PDO::PARAM... data type
$id = 33;
$name = "Mario Bros.";
$url = "http://nintendo.com";
$country = "jp";
try {
$sql = "UPDATE table_users SET name = :name, url = :url, country = :country WHERE user_id = :user_id";
$statement = $connection->prepare ($sql);
$statement->bindParam (':user_id', trim($id), PDO::PARAM_INT);
$statement->bindParam (':name', trim($name), PDO::PARAM_STR);
$statement->bindParam (':url', trim($url), PDO::PARAM_STR);
$statement->bindParam (':country', trim($country), PDO::PARAM_STR, 2);
$status = $statement->execute ();
} catch (PDOException $e) {
print $e->getMessage ();
}
print $status; // it returns a null value, and no errors are reported
?>
this portion of code doesn't report errors, but it simply doesn't work, the var $status at the bottom, return a null value.
can someone help me to find where I'm wrong?
PDO won't throw exceptions unless you tell it to. Have you run:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
on the PDO object?
You can add the attribute one time while you connect you mysql.
function connect($dsn, $user, $password){
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
}
Thanks

Categories