this is table schema:
CREATE TABLE `USERS` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(30) DEFAULT '',
`first_name` varchar(15) DEFAULT '',
`last_name` varchar(15) DEFAULT '',
`password` varchar(15) DEFAULT '',
`gender` int(1) DEFAULT '-1',
PRIMARY KEY (`id`)
)
in php:
$sql = 'INSERT INTO Users (email, first_Name, last_Name, password, gender ) VALUES ("'.$email.'", "'.$first_name.'", "'.$last_name.'", "'.$password.'", '.$gender.')';
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->execute();
//$user = $stmt->fetchObject();
echo 'last id was '.mysql_insert_id();
$db = null;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
I can't figure out why mysql_insert_id() returns 0. there are no other processes running. id is set to auto increment. Insert is done and seen in db.
You are using PDO to interface with the database. Use PDO::lastInsertId() to get the last inserted id.
$stmt->execute();
echo 'last id was ' . $db->lastInsertId();
mysql_insert_id() is part of the ext/mysql extension. You cannot mix-match functions from both extensions to interface with the same connection.
Related
I am using the following awesome, easy & lightweight database class: https://codeshack.io/super-fast-php-mysql-database-class/
My problem is I do not know how I can figure out if a table in the database exists or not. I have the following PHP Code:
function addSts($database, $brow, $vers, $pag, $lang) {
$tablename = "sts" . $pag;
$stsinsert = $database->query('INSERT INTO ' . $tablename . '(id, browser, version, language, date) VALUES (NULL, ?, ?, ?, current_timestamp())', $brow, $vers, $lang);
if ($stsinsert->affectedRows()) {
echo "TABLE EXISTS";
$database->close();
}
else {
echo "TABLE DOES NOT EXISTS -> CREATE TABLE";
$pagecreation = $database->query('CREATE TABLE ' . $tablename . ' (`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, `browser` VARCHAR(20) NOT NULL, `version` VARCHAR(10) NOT NULL, `language` VARCHAR(5) NOT NULL, `date` TIMESTAMP NOT NULL DEFAULT CURRENT_DATE(), PRIMARY KEY (`id`))');
if ($pagecreation) {
addSts($brow, $vers, $pag, $lang);
}
}
}
It always throws the following error: Unable to prepare MySQL statement (check your syntax) - Table 'testdb.ststest' doesn't exist
So and here we have the salad. It throws the error and does not go further to the if-else part. SO every time the table does not exist the program stops working.
Hope somebody can help me out.
Thanks in advance.
If you can, use the information_schema DB and query TABLES tables
select * from tables where TABLE_SCHEMA like '<database name>'
e.g. select * from tables where TABLE_SCHEMA like 'mydbdev'
the simply iterate through the results OR
select * from tables where TABLE_SCHEMA like '<database name>' AND TABLE_NAME like '<table name>';
and count the rows (should be 0 if not present or 1 if it is).
As #Barmar mentioned in the comments, you can use try/catch statements to do this.
function addSts($database, $brow, $vers, $pag, $lang) {
$tablename = "sts" . $pag;
try {
// try to insert first
$stsinsert = $database->query('INSERT INTO ' . $tablename . '(id, browser, version, language, date) VALUES (NULL, ?, ?, ?, current_timestamp())', $brow, $vers, $lang);
if ($stsinsert->affectedRows()) {
echo "TABLE EXISTS";
$database->close();
}
}
catch (\Exception $e){
echo "TABLE DOES NOT EXISTS -> CREATE TABLE";
$pagecreation = $database->query('CREATE TABLE ' . $tablename . ' (`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, `browser` VARCHAR(20) NOT NULL, `version` VARCHAR(10) NOT NULL, `language` VARCHAR(5) NOT NULL, `date` TIMESTAMP NOT NULL DEFAULT CURRENT_DATE(), PRIMARY KEY (`id`))');
if ($pagecreation) {
// call the function to insert data
addSts($brow, $vers, $pag, $lang);
}
}
}
The UserId field does not get updated with the value passed by the application, whereas all the other fields get updated.
This is my insert query and other related code from my app:
$sql = "INSERT INTO usermaster (UserId, UserName, Password,OwnerOrEmp, DBName, DeleteFlag, CreateDate, UpdateDate) values(:id, :userName, :password, :ownerOrEmp, :dBName, :deleteFlag, :createDate, :updateDate)";
$q = $pdo->prepare($sql);
//echo $uid;
$q->bindParam(':id', $uid);
$q->bindParam(':userName', $name);
$q->bindParam(':password', $pass);
$q->bindParam(':ownerOrEmp', $ownEmp);
$q->bindParam(':dBName', $dbName);
$q->bindParam(':deleteFlag', $delFlag);
$q->bindParam(':createDate', $curr_date);
$q->bindParam(':updateDate', $curr_date);
$q->execute();
This is how I create my table:
CREATE TABLE `USER_MASTER` (`UserID` varchar(8) NOT NULL,
`Password` varchar(10) NOT NULL,
`UserName` varchar(100) CHARACTER SET utf8 NOT NULL,
`OwnerOrEmp` char(1) NOT NULL,
`DBName` varchar(100) NOT NULL,
`DeleteFlag` char(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
And the result is
I am trying to create a "setup script" for my website. I would like to create the database, adding tables and some content at the same time. So far this is how I did it, but it seems kind off messy using multiple queries:
<?php
$servername = "localhost";
$username = "root";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE MYDB";
if ($conn->query($sql) === TRUE) {
echo "1. Database created successfully <br/>";
$conn->select_db("MYDB");
$sql_members = "CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
)";
if ($conn->query($sql_members) === TRUE) {
echo "2. Table MEMBERS created successfully <br/>";
} else {
echo "Error creating table: " . $conn->error;
}
$sql_content = "CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
)";
if ($conn->query($sql_content) === TRUE) {
echo "3. Table CONTENT created successfully <br/>";
} else {
echo "Error creating table: " . $conn->error;
}
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
Is there a better way?
Thanks!
== UPDATE ==
I have tried to export the database and use the resulted .sql file as my setup query, but something is wrong, I get:
Error creating tables: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'INSERT INTO CONTACTS (ID, NAME, PHONE,
EMAIL, ADDRESS, CITY, `COUN' at line 12
CREATE TABLE IF NOT EXISTS `CONTACTS` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(25) COLLATE utf8_romanian_ci NOT NULL,
`PHONE` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
`EMAIL` varchar(35) COLLATE utf8_romanian_ci NOT NULL,
`ADDRESS` text COLLATE utf8_romanian_ci NOT NULL,
`CITY` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
`COUNTRY` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_romanian_ci AUTO_INCREMENT=2 ;
INSERT INTO `CONTACTS` (`ID`, `NAME`, `PHONE`, `EMAIL`, `ADDRESS`, `CITY`, `COUNTRY`) VALUES
(1, 'Peter Brown', '0742062307', 'office#shop.com', 'Avenue 13.', 'Santaclaus', 'Austria');
== SOLUTUION ==
I needed "multi_query()" for executing my multiple queries.
You can try this too :p
$errors = [];
$table1 = "CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
)";
$table2 = "CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
)";
$tables = [$table1, $table2];
foreach($tables as $k => $sql){
$query = #$conn->query($sql);
if(!$query)
$errors[] = "Table $k : Creation failed ($conn->error)";
else
$errors[] = "Table $k : Creation done";
}
foreach($errors as $msg) {
echo "$msg <br>";
}
You could export the whole database including all tables using the command line or using PhPMyAdmin. Then query the content of the file in php to create the database.
you can create a file and put all your sql queries in it..
CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
);
CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
);
then in your php code:
$query = file_get_contents ('queries.sql');
if ($conn->query($query) === TRUE) {
echo "all tables created successfully <br/>";
} else {
echo "Error creating tables: " . $conn->error;
}
<?php
include_once 'db.php';
session_start();
if(!$_SESSION['logged_in']) {
die('You are unauthorized to be here. 1');
}
$old_password = md5($_POST['old_password']);
$new_password = md5($_POST['new_password']);
$sql = "UPDATE users SET pass='?' WHERE user='?' AND pass='?'";
$q = $db->prepare($sql);
$q->bindParam(1, $new_password);
$q->bindParam(2, $_SESSION['username']);
$q->bindParam(3, $old_password);
$q->execute();
header('location: ../?page=account');
?>
Here's my 'users' table scheme:
`users` (`active` int(1) NOT NULL DEFAULT '1',
`user` varchar(200) NOT NULL,
`pass` varchar(200) NOT NULL,
`admin` int(1) NOT NULL,
`date` varchar(150) NOT NULL DEFAULT 'error',
`Paid` varchar(200) NOT NULL DEFAULT 'None',
KEY `user` (`user`) )
ENGINE=MyISAM DEFAULT CHARSET=latin1;
Its simply not updating the values at all... Any ideas?
Remove quotes from your placeholders.
$sql = "UPDATE users SET pass='?' WHERE user='?' AND pass='?'";
change it to
$sql = "UPDATE users SET pass=? WHERE user=? AND pass=?";
Assuming that your code does not have a typo or other bug (not tested), logically the only explanation is that either the username or old password are not matching
i have a mysql database...
CREATE TABLE `applications` (
`id` int(11) NOT NULL auto_increment,
`jobref` int(11) NOT NULL,
`userid` int(11) NOT NULL,
`q1` text NOT NULL,
`q2` text NOT NULL,
`q3` text NOT NULL,
`sub_q1` text,
`sub_q2` text,
`sub_q3` text,
`timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
`printed` int(11) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `jobref` (`jobref`),
KEY `applications_ibfk_2` (`userid`),
CONSTRAINT `applications_ibfk_1` FOREIGN KEY (`jobref`) REFERENCES `jobs` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `applications_ibfk_2` FOREIGN KEY (`userid`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='InnoDB free: 9216 kB; (`jobref`) REFER `iwcjobs/jobs`(`id`) '
and this php file, using mysqli for data operations.
<?php
require_once '../includes/constants.php';
if(isset($_POST['submit'])) {
$q1 = $_POST['question1'];
$q1a = $_POST['ifNoQuestion1'];
$q2 = $_POST['question2'];
$q2a = $_POST['ifNoQuestion2'];
$q3 = $_POST['question3'];
$q3a = $_POST['ifNoQuestion3'];
$JobRef = $_POST['jobref'];
$UserRef = $_POST['id'];
$mysql = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was a problem connecting to the database');
if($stmt = $mysql->prepare('INSERT INTO `applications` VALUES (NULL,?,?,?,?,?,?,?,?,NULL,NULL)')) {
$stmt->bind_param('iissssss',$JobRef,$UserRef,$q1,$q2,$q3,$q1a,$q2a,$q3a);
$stmt->execute();
$stmt->close();
header('location: ../myApps.php?apr=y');
//echo ("<h2>success</h2> - $q1 . $q2 . $q3 . $q1a . $q2a . $q3a . $JobRef . $UserRef");
} else {
echo 'error: ' . $mysql->error;
}
} else {
echo 'errorStage2: ' . $mysql->error;
}
?>
The script is grabbing the correct values from the previous form, but not inserting them into the database. Any ideas people?
Thx in advance,
Aaron.
the way your insert query is currently written, you are trying to set id to NULL, which is a NOT NULL field.
it'd be better to structure the insert would be like this:
INSERT INTO 'applications' (jobref,userid,etc..) VALUES (?,?etc..)
this way, you not try to change id, and just let auto_increment do it's thing.