Is this code with PDO good (PHP)? [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm new to PHP and I've followed a few tutorials on PDO after learning the basics of the language and I was just wondering if my code here is correct and what you guys'd suggest I can change to make it more secure, faster, more efficient, you name it...
I've followed numerous tutorials to achieve this result and therefore I thought I'd ask you guys as not every tutorial on the web on PHP (there are so many) are reliable sources to learn best practices and writing good code.
Here's the code I have. It only inserts the string 'Bill Gates' to the database, called 'pdotest', table 'tableOne' and row 'rowOne'. I've used persistent db connection because that's supposed to make the web application faster. I'm sure you guys can enlighten me on how to use this persistent connection thing correctly, I may have not fully understood how to use this in my code.
<?php
// DB connect configuration
$user = 'user';
$pass = 'password';
// Database connection
try {
$conn = new PDO('mysql:host=localhost;dbname=pdotest', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
}
catch(PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
$conn = null;
die();
}
// Data to insert (Bill Gates = Hero #1)
$data = 'Bill Gates';
try {
// The insert query
$sql = "INSERT INTO tableone (rowOne) VALUES (:rowOne)";
$q = $conn->prepare($sql);
$q->execute(array(':rowOne'=>$data));
// Example INSERT query with multiple VALUES
// $q->execute(array(':rowOne'=>$data, ':rowTwo'=>$dataTwo));
}
catch(PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
$conn = null;
die();
}
?>

this is apparently inefficient as your PHP have to run twice more code than needed.
the below code is enough
<?php
// DB connect configuration
$user = 'user';
$pass = 'password';
// Database connection
$dsn = "mysql:host=localhost;dbname=pdotest;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$conn = new PDO($dsn, $user, $pass, $opt);
$data = 'Bill Gates';
$sql = "INSERT INTO tableone (rowOne) VALUES (?)";
$q = $conn->prepare($sql);
$q->execute(array($data));
some highlights
use persistent connection only if you certainly know what are you doing
set exception mode if you are expecting exceptions
DO NOT catch them only to die. PHP can die all right by itself.

Related

Simple PDO write not working

I'm trying to get a simple PDO insert to work. I have successfully created a tabled named mydb10 using PDO, and the next part I want to do is insert data into that table. Running the script does not return any errors (PDO error mode exception is enabled), but the table still contains null values.
I'm using a local server to run the PHP file, and am connecting to an Amazon RDS database. Currently all inbound traffic through SSH, HTTP, HTTPS, and MYSQL is allowed through the database's security group
$link = new PDO("mysql:host=$dbhost;dbname=$dbname",$username,$password);
$statement = $link->prepare("INSERT INTO mydb10 (selectedMain, selectedSide)
VALUES(:selectedMain, :selectedSide)");
$statement->execute(array(
"selectedMain" => "test",
"selectedSide" => "test2"
));
This might be silly, but I've been stuck for a while now and any help is appreciated. If you'd like any more information, let me know. I'm trying to utilize PHP in my app, but can't even get this simple test to work, so it's a bit discouraging.
EDIT # 1
This snippet is part of a larger file. I am able to successfully
connect to the database with my credentials and create new tables on the server. I do have PDO error reporting enabled in exception mode, and it has helped me work past syntax errors, but I am no longer getting any errors when I run the code. There are also no errors on the MYSQL server log.
I can provide any additional information that may be useful in debugging if desired.
First you need to properly set connection to MySQL database. You can write this code to sql.php:
<?php
$ServerName = "******";
$Username = "******";
$Password = "******";
$DataBase = "******";
try {
$CONN = new PDO("mysql:host=$ServerName; dbname=$DataBase", $Username, $Password);
$CONN->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$CONN->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Now, when you properly set connection, you need to execute sql, but before this you need to include sql.php:
try {
$SQL = 'INSERT INTO MyDB10 (SelectedMain, SelectedSide) VALUES(:SelectedMain, :SelectedSide)'; // Write SQL Query to variable
$SQL = $CONN->prepare($SQL); // Prepare SQL Query
$SQL->execute(array('SelectedMain' => 'Test', 'SelectedSide' => 'Test2')); // Execute data to Insert in MySQL Databse
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
When you finish all queries you must close connection with:
$CONN = null;

SQLite3 multithread at same server

How can I perform a SQLite3 exec at the same time in PHP?
I have this code (by example):
$bd = new SQLite3("database.db");
$bd->busyTimeout(5000);
$bd->exec("INSERT into 'foo' ('data') values ('bar')");
$bd->close();
unset($bd);
And it works, but the real problem is when I connect another computer to my server and I made the insert at the same time (really, I press the key that trigger the code at the same time in both computers) and it show an error "database is locked".
I know that with the pragma WAL the database works in multithread, but it even show the error. Thank you a lot! and sorry for my bad english.
The problem is sqlite3 employs database locking, as opposed to row or column locking like mysql or postgresql. If you want to do two things at the same time try using mysql, or postgresql. In mysql you would have to create the database. Your code would then look something like this:
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $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();
}
$count = $conn->exec("INSERT into 'foo' ('data') values ('bar')");
$conn = null // close connection

SQLSTATE[3D000]:1046 - No database selected [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I was trying to execute a SQL CREATE command with php but I have this problem:
SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected
I REALLY can't know where is the problem, please could you help me?
This is the script:
<?php
include 'connessione.php';
try {
$sql = 'CREATE TABLE joke (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
joketext TEXT,
jokedate DATE NOT NULL
) DEFAULT CHARACTER SET uft8 ENGINE=InnoDB';
$pdo->exec($sql);
} catch (PDOException $e){
$output = 'Errore nella creazione della tabella joke: ' . $e->getMessage();
include 'output.html.php';
exit();
}
$output = 'Tabella creata con successo.';
include 'output.html.php';
?>
And here the "connessione.php" file:
<?php
$host = 'host=localhost';
$mysql_user = 'root';
$mysql_password = '';
$database = 'php';
try {
$pdo = new PDO('mysql:$host;dbname=$database', $mysql_user, $mysql_password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
$output = 'Impossibile connettersi al database: ' . $e->getmessage();
include 'output.html.php';
exit();
}
?>
I checked the "connessione.php" file and the connection to database is right. Also, I checked user privileges and root has all privileges to "php" database... What's the problem?!
The problematic line is the connection itself:
$pdo = new PDO('mysql:$host;dbname=$database'
Remember that this is a string literal since they are wrapped with single quotes.
Change them you double quotes if you want the variables interpolated.
$pdo = new PDO("mysql:$host;dbname=$database", $mysql_user, $mysql_password);
It LOOKS like you're missing "host=" when you create the db handle. I'd also recommend searching SO or Google before asking questions - tons of hits for this issue: PHP PDO: Unable to connect, Invalid catalog name

mysqli_query() expects parameter 1 to be mysqli [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have new to PHP programming and looking to create access a database I created. I have been able to get a successful connection going between PHP and my database, but the problem arises when I try to run a simple query.
I get the dreaded message mysqli_query() expects parameter 1 to be mysqli. I have seen numerous issues on this throughout the internet. I still am unable to resolve my situation. Can someone please address my code here:
$mysqli= mysql_connect($hostname,$username,$password,'japanesewords')
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
mysqli_query($mysqli, 'SELECT * FROM japanesedefinition') or die(mysql_error($mysqli));
Why don't you use PDO?
<?php
try {
// config
$dsn = 'mysql:dbname=japanesewords;host=127.0.0.1;charset=utf8';
$username = 'root';
$password = '';
$options = array(
// necessary for rowCount() on SELECT
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
// for catching SQL errors as PDOException
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// default fetch mode is used for iterating PDOStatement by foreach()
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
);
// connect
$pdo = new PDO($dsn, $username, $password, $options);
// execute SQL
$stmt = $pdo->query('SELECT * FROM japanesedefinition');
// check row count
if (!$stmt->rowCount()) {
throw new Exception('no data');
}
// fetch results and display
echo "<p>\n";
foreach ($stmt as $row) {
printf("foo: %s; bar: %s;<br />\n", $row->foo, $row->bar);
}
echo "</p>\n";
} catch (Exception $e) {
printf("<p>%s</p>\n", $e->getMessage());
}
I don't know whether you're japanese or not, remark the summary in Japanese for connectiong to MySQL with PHP.
http://qiita.com/mpyw/items/b00b72c5c95aac573b71

Parsing variables through PHP with Flash

I'm making chat in flash as3 with php and mysql database.
However I don't know php at all, and got problem with updating messages.
for now my php file looks like this:
$caster = $_POST['caster'];
$msgText = $_POST['msgText'];
$sendTime = $_POST['sendTime'];
$query = "INSERT INTO chat VALUES ('','$sendTime','$caster','$msgText')"
mysql_query($query);
$query="SELECT * FROM chat";
$result=mysql_query($query);
$cast=mysql_result($result,1,"caster");
mysql_close();
$returnVars = array();
$returnVars['success'] = $success;
$returnVars['caster'] = $cast;
$returnString = http_build_query($returnVars);
echo $returnString;
And my question is how to loop for all already sent chat messages to send them to flash.
I can only do it with one, but I need whole bunch of them to be loaded.
Thanks
What you are looking for is "fetchAll". Note that your code is open to SQL injection, it is very easy to drop your database by passing evil values to the PHP script. I have changed the code therefore from the deprecated Mysql extension to PDO. PDO will to the escaping of the values for you.
Read more on PDO in the PHP manual (Lots of examples over there).
Also note that you have to adapt the following code snipped as I could not guess how the field names of the chat table in your database are named. So you have to adapt the insert statement below.
// database config parameters
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "";
try {
// try to set up a db connection
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
// insert the data using PDO's prepared statements
// you have to adapt this line to the field names of your chat table!!
$sql = "INSERT INTO chat (sendtime,caster,msg) VALUES (:sendtime,:caster,:msg)";
$sth = $db->prepare($sql);
$sth->execute(array(
':caster' => $_POST['caster'],
':sendtime' => $_POST['sendTime'],
':msg' => $_POST['msgText']
));
// Get everything
$sth = $db->prepare("SELECT * FROM chat");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
// your code to format and return the data goes here
print json_encode($result);
}
catch (PDOException $e) {
// if anything related to the database goes wrong, catch the exceptions
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$db = null;
The Actionscript will receive a JSON object looking similar to this:
[
{
"sendtime":"2013-04-14",
"caster":"person1",
"msg":"Message 1"
},
{
"sendtime":"2013-04-15",
"caster":"person2",
"msg":"Message 2"
}
]
As you can see the JSON has no specific variable name like in the version with GET used in the question (the method used in the question does not work for large result lists).
So how do you work with the JSON document in Actionscript? I am not an actionscript programmer, but this Stackoverflow post looks like a reasonable answer to this problem:
Get and parse JSON in Actionscript

Categories