I am having trouble to let foreign key updating itself, the constraint was set as on update cascade on delete cascade in phpmyadmin.
I am able to insert everything else, just the foreign key user_id appearing as null rather than updating to the correct id.
Where was my mistake? id the the table id, I know I don't need to put into the sql statement; user_id is the foreign key linked with tbl_user
Insert to database codes
try
{
$dbh = new PDO("mysql:host=localhost;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt =$dbh->prepare( "INSERT INTO tbl_details (user_id, name,address,postcode)
VALUES(:user_id,:name,:address,:postcode)");
$stmt->bindParam(':user_id',$user_id);
$stmt->bindparam(':name', $name);
........
$stmt->execute();
$dbh = null;
}catch (PDOException $e) {
$dbh = null;
print "Error!: " . $e->getMessage() . "<br/>";
print "PHP Line Number: " . $e->getLine() . "<br/>";
print "PHP File: " . $e->getFile() . "<br/>";
die();
}
Yes, its working now, I am missing this
$stmt = $auth_user->runQuery("SELECT * FROM tbl_details WHERE user_id=:user_id");
$stmt->execute(array(":user_id"=>$user_id));
Thank you #sean and #Darwin von Corax
Related
I have no idea why this code wouldn't work but when I run my code it goes instantly in the catch. I have been looking into and try multiple ways to insert it into my database but why can't I insert it? Is it because I only insert 1 value? My database table looks like this:
Here my code:
<?php
include "../includes/connection.php";
$ruimte_naam = $_POST['ruimte_naam'];
try{
$stmt = $conn->prepare("INSERT INTO IA_Locatie (Ruimte_naam) VALUE (?)");
$stmt->execute([$ruimte_naam]);
}catch(PDOException $e){
echo $stmt . "<br>" . $e->getMessage();
}
$conn = null;
?>
Two steps to fix the problem:
Change echo $stmt . "<br>" . $e->getMessage();to echo $e->getMessage();
Use VALUES instead of VALUE so that it reads:
$stmt = $conn->prepare("INSERT INTO IA_Locatie (Ruimte_naam) VALUES (?)");
I can't run INSERT INTO and SELECT queries in one statement.
Have problem with this php code:
$db = connect_db_marketlist();
if($db != null) {
$sql = "INSERT INTO items (user_id, market_table_id, price, info )"
." VALUES ('$id', (SELECT table_id FROM markets WHERE city='$city' AND market='$market'), $price, '$info')";
echo $sql; // !!! DEBUG !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
try {
$db->query($sql);
echo "OKAY: ".$db->lastInsertId();
} catch (Exception $e) {
echo "ERROR: ".$e->getMessage();
}
}
And I got error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'market_table_id' cannot be null
Error says SELECT query returns null but when I run $sql statement directly in phpmyadmin, it is working.
This is echo $sql output:
INSERT INTO items (user_id, market_table_id, price, info ) VALUES
('12345678', (SELECT table_id FROM markets WHERE city='ANKARA' AND market='MİGROS'), 22.33, 'TEST_INFO_MİGROS')
What's wrong with me? Maybe it's my db connection:
function connect_db_marketlist() {
$servername = "localhost";
$username = "marketuserdb";
$password = "pass1234";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=marketlist", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
return $conn;
}
Is it possible to run "INSERT INTO...SELECT..." query with PDO? If yes how, if no why?
P.S: It's working when I enter any integer instead of (SELECT....) query. So no problem with DB connection.
You should set connections charset to proper one in DSN like
"mysql:host=$servername;dbname=marketlist;charset=utf8mb4"
(This is for utf-8, you should set it for your tables encoding)
the var should be inside the select
This way
"INSERT INTO items (user_id, market_table_id, price, info )"
." SELECT '$id', table_id , $price, '$info'
FROM markets WHERE city= '$city' AND market='$market' ;";
I need to INSERT record if user_id is unique in table map, but if not then UPDATE that row where user_id=:user_id with data...
What I try:
try {
$result = $db->prepare('SELECT user_id FROM map WHERE user_id=:user_id');
$result->bindParam(':user_id', $user_id);
$result->execute();
//echo $jsonTable;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
try {
if ($result==null) {
$STH = $db->prepare("INSERT INTO map (json, user_id) VALUES (:json, :user_id)");
$STH->bindParam(':json', $_POST['mapData']);
$STH->bindParam(':user_id', $user_id);
$STH->execute();
} else {
$STH = $db->prepare("UPDATE map SET json = :json WHERE user_id= :user_id");
$STH->bindParam(':json', $_POST['mapData']);
$STH->bindParam(':user_id', $user_id);
$STH->execute();
}
} catch (PDOException $e) {
echo $e->getMessage();
}
echo "<p>Data submitted successfully</p>";
}
So here I try to check is user_id I need to add exist into table, and if there is no user_id, so if prepared user_id is new then I try to insert data, but if user_id alredy excist into table then to UPDATE that record...
But this dont work for me, also dont give me any error?
I'beginer to php, so sorry about trivial question... Thanks!
UPDATE:
I also try to insert but if user_id is duplicate then to UPDATE:
try {
$STH = $db->prepare("INSERT INTO map (user_id, json) VALUES (:user_id,:json)
on duplicate key update json=values(json)");
$STH->bindParam(':json', $_POST['mapData']);
$STH->bindParam(':user_id', $user_id);
$STH->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
echo "<p>Data submitted successfully</p>";
}
To check uniqueness you can use an unique key to have uniqueness checked by the db: http://dev.mysql.com/doc/refman/5.6/en/mysql-indexes.html
Or better, ususally ids are primary keys of the table, this means you don't need to worry about uniqueness, primary key is always unique and the db checks it for you
I have two tables which are linked with many many relationship,Normally I work with Mysqli for querying,but now for some reasons I have to use PDO,So my problem is 1st to check if a value doesn't exists, to add it in a table tag,and if not to take the id of the value and add the related data in the join data.
tag-tagmap-post a tag can belong to many posts,and a post can have many tags I try this but when a tag name already exists I can't retrieve the id of the tag.
$sql = "
INSERT INTO tag (name)
SELECT * FROM (SELECT :name) AS tmp
WHERE NOT EXISTS (
SELECT name FROM tag WHERE name =:name
) LIMIT 1";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam(":name", $post->name);
$stmt->execute();
$test=$post->id = $db->lastInsertId();
$db = null;
//echo json_encode($post);
} catch(PDOException $e) {
//error_log($e->getMessage(), 3, '/tmp/php.log');
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
$sql2="INSERT INTO tagmap (tag_id,post_id,user_id) VALUES(:id2,:post_id,:id)";//
try {
$db = getConnection();
$stmt = $db->prepare($sql2);
$stmt->bindParam("id2", $test);//tag id
$stmt->bindParam("post_id", $post->post_id);//post_id
$stmt->bindParam("id", $id);
$stmt->execute();
//$post2->id = $db->lastInsertId();
$db = null;
echo json_encode(array("result"=>$test));
} catch(PDOException $e) {
//error_log($e->getMessage(), 3, '/tmp/php.log');
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
Thank you for your help!!!
As documented under PDO::prepare():
You cannot use a named parameter marker of the same name more than once in a prepared statement, unless emulation mode is on.
That said, the insertion query itself is over-complicated (and contains syntax errors: there is no LIMIT clause in the INSERT syntax). You could instead:
define a UNIQUE key over (name) in the tag table:
ALTER TABLE tag ADD UNIQUE (name);
use INSERT ... ON DUPLICATE KEY UPDATE:
INSERT INTO tag (name) VALUES (?)
ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id);
This will ensure that $db->lastInsertId() returns the ID of the relevant record whether it has been newly inserted or it already existed.
I am using $insertedId = $pdo_conn->lastInsertId(); to get the last inserted ID after an insert query then i run another insert query:
foreach ($records as $emails_to) {
$stmt = $pdo_conn->prepare("INSERT into emails_to (email_seq, email) values (:email_seq, :email) ");
$stmt->execute(array(':email_seq' => $InsertedId, ':email' => $emails_to["email"]));
}
but it doesn't seem to recognise the last insert ID, i get this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'email_seq' cannot be null'
what have i done wrong?
$insertedId and $InsertedId are not the same. Variable names are case-sensitive.
Your $insertedID doesn't match $InsertedID - case issue
edit; darn, beaten to the post
Beware of lastInsertId() when working with transactions in mysql. The following code returns 0 instead of the insert id.
This is an example
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)");
try {
$dbh->beginTransaction();
$stmt->execute( array('user', 'user#example.com'));
$dbh->commit();
print $dbh->lastInsertId();
}
catch(PDOException $e) {
$dbh->rollback();
print "Error!: " . $e->getMessage() . "</br>";
}
}
catch( PDOException $e ) {
print "Error!: " . $e->getMessage() . "</br>";
}
?>
When no exception is thrown, lastInsertId returns 0. However, if lastInsertId is called before calling commit, the right id is returned.
for more informations visit -> PHP