run insert query once only when the database is created php pdo - php

from config.php
<?php
global $dbh;
$dbname = 'memberdb';
try {
$dbh = new PDO("mysql:host=localhost", "root", "");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbname = "`".str_replace("`","``",$dbname)."`";
$dbh->query("CREATE DATABASE IF NOT EXISTS $dbname");
$dbh->query("use $dbname");
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql ="CREATE TABLE IF NOT EXISTS $member (
mem_id int(40) NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(40) NOT NULL,
password VARCHAR(40) NOT NULL);" ;
$dbh->exec($sql);
$stmt = $dbh->prepare("INSERT INTO member (username, password) VALUES (?,?)")or die($db->errorInfo());
$stmt->bindValue(1,"admin1",PDO::PARAM_STR);
$stmt->bindValue(2,"password1",PDO::PARAM_STR);
$stmt->execute();
$stmt->bindValue(1,"admin2",PDO::PARAM_STR);
$stmt->bindValue(2,"password2",PDO::PARAM_STR);
$stmt->execute();
$stmt->bindValue(1,"admin3",PDO::PARAM_STR);
$stmt->bindValue(2,"password3",PDO::PARAM_STR);
$stmt->execute();
} catch(PDOException $e) {
}
?>
This is my function of new user when the user is registered using a registered button.
How to make this kind of function run only one, when the database is created and only.
I will need to put defined value for each input but i didnt not change it yet
UPDATE
The code i used is above my prob is still the same when i reload the index.php the query runs again making double entry..what i want is that when the database is create the query will run and when loaded the database is not created again so i want the query to not run again to avoid double entry.

$stmt = $dbh->prepare("SELECT * FROM member") ;
$stmt->execute();
$count = $stmt -> rowCount();
echo $count;
if( $count == 00 ){
$stmt = $dbh->prepare("INSERT INTO member (username, password) VALUES (?,?)")or die($db->errorInfo());
$stmt->bindValue(1,"admin1",PDO::PARAM_STR);
$stmt->bindValue(2,"password1",PDO::PARAM_STR);
$stmt->execute();
$stmt->bindValue(1,"admin2",PDO::PARAM_STR);
$stmt->bindValue(2,"password2",PDO::PARAM_STR);
$stmt->execute();
$stmt->bindValue(1,"admin3",PDO::PARAM_STR);
$stmt->bindValue(2,"password3",PDO::PARAM_STR);
$stmt->execute();
}
i only have one more question why is it sometimess the echo for count is 3 and sometimes its 33 its like the query is run twice please clear this out...this worked but maybe just maybe there are incorrect logic here please feel free to edit to make it perfect.

Related

Getting the result of an SQLite query for PHP

I am trying to obtain the user id from my database, using the query bellow, to insert it somewhere else. I am new to php and sql so I can't really spot what's wrong. The result I get on var_dump() is object (SQLite3Result)#4 (0) { } - I only used this for testing. I tried using fetchArray() but it still got me nothing. The database works alright, I used it for other things.
require 'database.php';
$db = new Database();
$email = $_POST['member'];
$list = $db->prepare('SELECT userid FROM users WHERE (email = :email)');
$list->bindValue(':email', $email, SQLITE3_TEXT);
$q = $list->execute();
var_dump($q);
Thanks for any help!
Here is what you can do:
<?php
class UserDB extends SQLite3
{
function __construct()
{
$this->open('test.db');
}
}
$db = new UserDB();
$stmt = $db->prepare('SELECT * FROM users where email = :email');
$stmt->bindValue(':email', 'user1#example.com', SQLITE3_TEXT);
$result = $stmt->execute();
var_dump($result->fetchArray());
Then you can update the bindValue method call with the email variable.
For the sqlite3 db I created it using the following commands:
$ sqlite3 test.db
CREATE TABLE USERS (
ID INT PRIMARY KEY NOT NULL,
EMAIL TEXT NOT NULL
);
INSERT INTO USERS VALUES(1, 'user1#example.com');
.quit
Then you can use that with my code.

mysql_insert_id($result) not returning ID

$SQL = "INSERT INTO primarySkills (primaryName) VALUES $surveySQL";
$result = mysql_query($SQL) or die ('Cannot execute query...'.$SQL);
$surveyID = mysql_insert_id($result);
The above code will enter the table data correctly (primaryID, primaryName) but not return the id generated using mysql_insert_id(). Please let me know why the id is not returned?
What is really odd is that I use this function twice before in the same script for different tables and it works there. I double checked that primaryID is auto_increment and a primary key.
Blessings!
Stop using mysql functions
However the problem in your case could be primaryID is not a autoincrement and probably also not a primary key. For mysql_insert_id() to work, there should be a autoincrement column. Also change the query.
$SQL = "INSERT INTO primarySkills (primaryName) VALUES ($surveySQL)";
and try using mysql_insert_id() instead of mysql_insert_id($result).
Here is an example using pdo since MYSQL functions have been removed as of php 7. I did not test your sql command. replace these values:
localhost: your host
3306: your port if different
dbname: the name of your database
root: your username
'': the last parameter is your password.
<?php
$conn = new PDO('mysql:host=localhost:3306;dbname=testdb', 'root', '');
$conn->SetAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$SQL = "INSERT INTO primarySkills (primaryName) VALUES (:test)";
$insert = $conn->prepare($sql);
$insert->bindValue(":test", $surveySQL, PDO::PARAM_STR);
$insert->execute();
$last_insert_id = $conn->lastInsertId();
?>
When you have completed testing and are ready to go into production, go ahead and remove this line of code:
$conn->SetAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
Hope this helps.

Check if row exists in the database before inserting

$DBH = new PDO($dsn, $username, $password, $opt);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$STH = $DBH->prepare("INSERT INTO requests (id,imdbid,msg) VALUES ('',:imdbid,:msg)");
$STH->bindParam(':imdbid', $_POST['imdbid']);
$STH->bindParam(':msg', $_POST['msg']);
$STH->execute();
echo "<p>Successfully Requested ".$_POST['imdbid']."! Thanks!</p>";
Is there either some SQL Query that will check and insert or what?
I need it to check if whatever the user typed is already in the db so if the user typed in a imdbid that is already there then it wont continue inserting anything. How would I do this? I know I can do a fetch_all and make a foreach for it but doesnt that only work after you execute?
It's better to set a constraint on your columns to prevent duplicate data instead of checking and inserting.
Just set a UNIQUE constraint on imdbid:
ALTER TABLE `requests` ADD UNIQUE `imdbid_unique`(`imdbid`);
The reason for doing this is so that you don't run into a race condition.
There's a small window between finishing the check, and actually inserting the data, and in that small window, data could be inserted that will conflict with the to-be-inserted data.
Solution? Use constraints and check $DBH->error() for insertion errors. If there are any errors, you know that there's a duplicate and you can notify your user then.
I noticed that you are using this, $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);. In this case, you don't need to check ->error() because PDO will throw an exception. Just wrap your execute with try and catch like this:
$duplicate = false;
try {
$STH->execute();
} catch (Exception $e) {
echo "<p>Failed to Request ".$_POST['imdbid']."!</p>";
$duplicate = true;
}
if (!$duplicate)
echo "<p>Successfully Requested ".$_POST['imdbid']."! Thanks!</p>";
Simply run a query prior to inserting.
If found die the script:
$DBH = new PDO($dsn, $username, $password, $opt);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = 'SELECT COUNT(*) from requests WHERE imdbid = :imdbid';
$stmt = $DBH->prepare($sql);
$stmt->execute(array(':imdbid' => $_POST['imdbid']));
if($stmt->fetchColumn()){ die('Already exist');}
$STH = $DBH->prepare("INSERT INTO requests (id,imdbid,msg) VALUES ('',:imdbid,:msg)");
$STH->bindParam(':imdbid', $_POST['imdbid']);
$STH->bindParam(':msg', $_POST['msg']);
$STH->execute();
echo "<p>Successfully Requested ".$_POST['imdbid']."! Thanks!</p>";
or alternatively make the msg field unique.
Using a stored Procedure:
DELIMITER //
CREATE PROCEDURE insert_request_msg(IN `p_imbd`, IN `p_msg`)
IF NOT EXISTS (SELECT COUNT(*) from requests WHERE imdbid = p_imbd)
BEGIN
INSERT INTO requests (id,imdbid,msg) VALUES ('',p_imbd,p_msg)
END
END IF; //
DELIMITER ;
You call it in one query like this:
$STH = $DBH->prepare('
call insert_request_msg(:imdbid,:msg)
');
$STH->bindParam(':imdbid', $_POST['imdbid']);
$STH->bindParam(':msg', $_POST['msg']);
Try this
$DBH = new PDO($dsn, $username, $password, $opt);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$STH = $DBH->prepare("INSERT INTO requests (id,imdbid,msg) VALUES ('',:imdbid,:msg) WHERE NOT EXISTS(SELECT imdbid FROM requests WHERE imdbid =:imdbid)");
$STH->bindParam(':imdbid', $_POST['imdbid']);
$STH->bindParam(':msg', $_POST['msg']);
$STH->execute();
echo "<p>Successfully Requested ".$_POST['imdbid']."! Thanks!</p>";
Source

PDO lastInsertID is returning 0

I am having trouble with lastInsertID returning 0. It is working in another page, so I have something wrong here.
The following is in a try/catch block.
$idCount = "42";
/** set the database **/
$db = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
/** set the error reporting attribute **/
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare("SELECT image1 FROM items WHERE `id` = :id");
/** bind the parameters **/
$stmt->bindParam(':id', $idCount, PDO::PARAM_STR);
$stmt->execute();
$idCount = $db->lastInsertId();
echo $idCount;
The function name ->lastInsertId() should give you a hint that SELECT statements wouldn't normally set the last insert id.
Typically only INSERT statements on tables with an auto_increment column exhibit that behaviour.
There are exceptions though, such as when LAST_INSERT_ID(expr) is used:
SELECT LAST_INSERT_ID(`id`) AS `id`, image1 FROM items WHERE `id` = :id
lastInsertId() will only return the last insert id if you actually do an insert. You are only doing a select.

Failed To Call Member Function Query On A Non-object, MySQLI

I have a problem with producing a Register using my MySQLI Code. The tables/connection variable is matching up, and the correct variables being passed through the query is populated with expected strings, when running a query or prepare & execute when performing any type of query, I get returned with the following:
Fatal error: Call to a member function query() on a non-object in
/var/www/New/API/FormValidations.php on line 40
My code is as followed:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username='$Username'");
$Query->execute();
$Number = $Query->num_rows;
if ($Number !== 0)
{
echo "Username Already In Use";
}
else
{
$Insert_User = $STD->prepare("INSERT INTO Users ('Username', 'Password') VALUES ('$Username', '$Password)");
$Insert_User->execute();
echo "Account Created!";
}
Here is My Connection Script:
$STD = new mysqli('localhost', 'root', 'xxxxx', 'SLMS');
$AccessCon = new mysqli('localhost', 'root', 'xxxxx', 'DBAccess');
if ($AccessCon->connect_error) {
die("Access Has Been Revoked. Please Contact Administration");
}
if ($STD->connect_error) {
die("Standard Access Has Been Revoked. Please Contact Administration");
}
and my SQL Table for Users:
CREATE TABLE IF NOT EXISTS `Users` (
`ID` int(255) NOT NULL AUTO_INCREMENT,
`Username` varchar(255) NOT NULL,
`Password` text NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
I have tried commenting out all my query code, and running
$Query = $STD->query("SHOW TABLES");
$Results = $STD->fetch_array(MYSQLI_ASSOC);
this still returned an error, on my $Query variable.
I have also tried modifying my code to search for something that is already present in the database:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username='Test'");
and tried to enclose my $Username As followed:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username='{$Username}'");
This has performed No Success. I was wondering if someone could shed some light on this situation?
Edit:
Commenting out the entire script and just running:
$Query = $STD->query("SHOW TABLES");
$test = $Query->fetch_array(MYSQLI_ASSOC);
print_r($test);
Returns a result.
UPDATE:
I have modified my code to:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username=?");
$Query->bind_param("s", $Username);
$Query->execute();
Final Update:
Fatal error: Call to a member function bind_param() on a non-object
in /var/www/New/Register.php on line 45
This is the new Error.
The offending lines:
$Insert_User = $STD->prepare("INSERT INTO Users ('Username', 'Password') VALUES (?, ?)");
$Insert_User->bind_param("ss", $Username, $Password);
$Insert_User->execute();
When using prepare you have to bind the varables that hold your values.
Example:
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
here is link to prepared statements
Update
this:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username=s");
should be:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username=?");
this:
$Insert_User = $STD->prepare("INSERT INTO Users ('Username', 'Password') VALUES ('U', 'P)");
should be:
$Insert_User = $STD->prepare("INSERT INTO Users ('Username', 'Password') VALUES (?, ?)");
this :
$Insert_User->bind_param('U', $Username);
$Insert_User->bind_param('P', $Password);
should be this:
$Insert_User->bind_param('ss', $Username,$Password);

Categories