Why isn't anything being inserted into my MySQL table? - php

I have some PDO that I'm trying to use to insert data into a MySQL table.
private function addResource() {
include('./dbconnect.php');
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stmt = $pdo->prepare('INSERT INTO Resources VALUES (?, $title, $url, $_SESSION[\'tblUserID\'');
$stmt->bindParam(1, $title);
$stmt->bindParam(2, $url);
$stmt->bindParam(3, $_SESSION['tblUserID']);
$stmt->execute();
if ($stmt->rowCount() != 1)
throw new Exception('Could not add resource');
$status = true;
}
Thing is, whenever I check the table, nothing is being inserted. How come?
EDIT: I have session_start() at the top of the page.

Because you're using PDO completely wrong. Placeholders do not use PHP variable syntax. The query string should be:
$stmt = $pdo->prepare('INSERT INTO .... VALUES (:id, :title, :url, :userid')
^^^^^^
$stmt->bindParam(':title', $title);
^^^^^^
Note the use of the :whatever format for placeholders.
As it is written now, your query is a flat-out syntax error, and vulnerable to SQL injection attacks

Try this:
private function addResource() {
include('./dbconnect.php');
try{
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stmt = $pdo->prepare('INSERT INTO Resources VALUES (:title, :url, :userid)';
$stmt->bindParam(':title', $title);
$stmt->bindParam(':url', $url);
$stmt->bindParam(':userid', $_SESSION['tblUserID']);
$stmt->execute();
if ($stmt->rowCount() != 1)
throw new Exception('Could not add resource');
$status = true;
}
}catch (Exception $e){
echo $e->getMessage();
exit;
}
}
Ref: http://php.net/manual/en/pdo.prepared-statements.php

Related

How to use PHP prepared statements in OOP

I am saving my data using this code (pasting my code)
Connection.php:
<?php
namespace Database;
use Mysqli;
class Connection {
public $con;
function __construct() {
$this->con = new mysqli(connection strings here);
}
function save($sql) {
$this->con->query($sql);
}
}
?>
then my Save.php is like this:
<?php
require 'config.php';
class Save {
function __construct($username, $password) {
$connect = new Database\Connection;
$sql = "INSERT INTO sample(string1, string2) VALUES ('$test1', '$test2')";
$connect->save($sql);
}
}
$save = new Save("last", "last");
?>
my question is how do I implement bind params here and prepared statement for PHP?
and also I would like to ask what are the best way to do this and best practices that I should implement for my code
thanks guys
Your classes are structured in a weird way, I am guessing you want some sort of ORM like class?
If so, you may want to rename your Save class to User (that's a guess since you are trying to save a username and password) and move your constructor logic, e.g.
class User {
function save($username, $password) {
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
}
}
This example explain how you can do it .
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* Clean up table CountryLanguage */
$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", $mysqli->affected_rows);
/* close connection */
$mysqli->close();
?>
And you can find more info in this link : http://php.net/manual/tr/mysqli-stmt.bind-param.php
And i suggest you to use PDO its better way to connect with the
database .
Use like this.
public function insert_new_user($username, $email, $password){
$mysqli = $this->link;
$sql = "INSERT INTO users"
. " (user_name, user_email, user_pass)"
. " VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sss", $username, $email, $password);
if ($stmt->execute()) {
return "success";
} else {
return "failed: " . $mysqli->error;
}
}

bindValue is not working

Using PDO with MariaDB server. I am having trouble understanding why this code does not work. Whenever I have :value for the values it gives me an error " Invalid parameter number: parameter was not defined"
$sql = "INSERT INTO table (USER, DOMAIN,FLG) VALUES (:username,:domain,:flag)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':domain', $domain);
$stmt->bindValue(':flag', $flag);
$stmt->execute();
But then the code below does work.
$sql = "INSERT INTO table (USER, DOMAIN,FLG) VALUES (?,?,?)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(1, $username);
$stmt->bindValue(2, $domain);
$stmt->bindValue(3, $flag);
$stmt->execute();
Below is the rest of the section for this code.
if(isset($_POST['addEditor'])){
$username = $_POST['formUsername'];
$domain = $_POST['formDomain'];
$flag = $_POST['formflg'];
$sql = "INSERT INTO table (USER, DOMAIN,FLG) VALUES (:username,:domain,:flag)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':domain', $domain);
$stmt->bindValue(':flag', $flag);
$stmt->execute();
try{
$stmt->execute();
}
catch (Exception $e) {
die ('ERROR: ' . $e->getMessage());
}
That code worked for me have read something about PDO here
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$username='a';
$domain ='b';
$flag ='c';
$sql = "INSERT INTO `table` (`USER`, `DOMAIN`, `FLG`) VALUES (:username,:domain,:flag)";
$stmt = $dbh->prepare($sql);
$stmt->execute(
array(':username'=> $username,
':domain'=> $domain,
':flag'=> $flag)
);
I am having trouble understanding why this code does not work.
No wonder, as you're using wrong way to understand.
Get rid of all try and catch operators in your code, run it again and then read the full error message, that will make you understand which code does not work.
if($_POST)
{
$role ="student";
try{
$stmt = $db_con->prepare("INSERT INTO userinfo (role)
VALUES(:qrole)");
$stmt->bindParam(":qrole", $role);
if($stmt->execute())
{
echo "Successfully Added";
}
else{
echo "Query Problem";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
try this , if some errors occurred it will post it using catch

PDO not being able to return the last_insert_id

<?php
session_start();
$userid = $_SESSION['userid'];
$categorynumber=0;
$categorynumber = create_category($userid);
//keep the category number for future reference
if($categorynumber > 0){
$_SESSION['categorynumber'] = $categorynumber;
}
echo $categorynumber;
?>
echo $categorynumber prints 0
function create_category($userid)
{
// connect to database with PDO
$dsn = 'mysql:host='.DB_HOST.';dbname='.DB_DATABASE;
$dbh = new PDO($dsn, DB_USER, DB_PASSWORD);
// insert category and get the category_id
$categorynumber = 0;
$stmt = $dbh->prepare("INSERT INTO categories (userid, name) VALUES (:userid, :name);SELECT LAST_INSERT_ID();");
$stmt->bindValue(':userid', $userid, PDO::PARAM_STR);
$stmt->bindValue(':name', 'test7', PDO::PARAM_STR);
if ($stmt->execute())
{
$result = array();
while ($row = $stmt->fetch()) {
array_push($result, $row);
}
if (isset($result[0][0]))
$categorynumber = $result[0][0];
}
// close database and return null
$dbh = null;
return $categorynumber;
}
What am I doing wrong here, so that I cannot retrieve the last id of the created entry? How can I return the last_insert_id(); and assign it to the $_SESSION['categorynumber']??
I have managed to achieve what I wanted with the following line:
$categorynumber = $dbh->lastInsertId();
full example:
function create_category($userid)
{
// connect to database with PDO
$dsn = 'mysql:host='.DB_HOST.';dbname='.DB_DATABASE;
$dbh = new PDO($dsn, DB_USER, DB_PASSWORD);
// insert category and get the category_id
$categorynumber = 0;
$stmt = $dbh->prepare("INSERT INTO categories (userid, name) VALUES (:userid, :name);");
$stmt->bindValue(':userid', $userid, PDO::PARAM_STR);
$stmt->bindValue(':name', 'test7', PDO::PARAM_STR);
$stmt->execute();
$categorynumber = $dbh->lastInsertId();
// close database and return null
$dbh = null;
return $categorynumber;
}

php PDO prepare(" INSERT ..(variables ) VALUES(?,?,) produces an error need assistance

$query = $this->link->prepare("INSERT INTO surveys (`username`,`inspected`,
`comments`,`ip_address`,`date`,`time`)
VALUES '(?,?,?,?,?,?)';);
$values = array ($username,$inspected,$comments,$ip_address,$date,$time);
var_dump($query);$rowCount = $query->rowCount();
$return $rowCount;
You can base yourself on the following which I've prepared for you.
Sidenote: I'm not entirely sure as to why you want to use rowCount() for, so I left it out for now.
If you're looking to check if a record exists using rowCount(), let me know.
The following method works to insert data into a database, which is based on a method I use.
<?php
$dbname = 'xxx';
$username = 'xxx';
$password = 'xxx';
try {
$pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
exit( $e->getMessage() );
}
$sql = "INSERT INTO surveys (
username,
inspected,
comments,
ip_address,
date,
time
) VALUES (
:username,
:inspected,
:comments,
:ip_address,
:date,
:time)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
$stmt->bindParam(':inspected', $_POST['inspected'], PDO::PARAM_STR);
$stmt->bindParam(':comments', $_POST['comments'], PDO::PARAM_STR);
$stmt->bindParam(':ip_address', $_POST['ip_address'], PDO::PARAM_STR);
$stmt->bindParam(':date', $_POST['date'], PDO::PARAM_STR);
$stmt->bindParam(':time', $_POST['time'], PDO::PARAM_STR);
// $stmt->execute();
$stmt->execute(array(':username' => $_POST['username'],':inspected' => $_POST['inspected'],':comments' => $_POST['comments'],
':ip_address' => $_POST['ip_address'],':date' => $_POST['date'],':time' => $_POST['time']));
if($stmt != false) {
echo "success!";
} else {
echo "an error occured saving your data!";
}

PHP PDO Simple insert does not work

I am converting all of my query's to PDO, and i'm new to it.
It's properly a very stupid question but why does the following code not work?
try {
$conn = new PDO('mysql:host=localhost;dbname=ddd', $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$id = $_SESSION['id'];
$name = $_POST['name'];
$stmt = $pdo->prepare('INSERT INTO projects
(group_id, project_name)
VALUES (:id, :name)');
$stmt->execute(array(
':id'=>$id,
':name'=>$name
));
Thanks.
Your connection variable is $conn and you are preparing your PDO Statement using $pdo->prepare.
Change to $conn->prepare()
$stmt = $conn->prepare('INSERT INTO projects
(group_id, project_name)
VALUES (:id, :name)');
You're initializing a variable for your database connection called $conn yet later call $pdo that's not mentioned anywhere. That's the first thing I'd start with.

Categories