It's just a new form of PDO that I don't fully understand. I know problems similar to this one have been solved on this site. But I’ve been attracted to this new (new to me) class-based system of PDO. It's sleek & concise. I figured everything out, all dynamic user-data INSERTS into the database just fine. However, I can’t figure out how to include lastInsertId() using this particular style. The user doesn’t input the post id & I can’t use GET request, which is how I normally get the post id.
What I have below, after many failed attempts, is the best I can do. Obviously it doesn’t work. Any corrections to my code would be much appreciated.
Here is the database class:
functions.php
class DB{
private static function connect(){
$pdo = new PDO('mysql:host=localhost;dbname=poetionpics;charset=utf8', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query($query, $params = array()){
$stmt = self::connect()->prepare($query);
$stmt->execute($params);
if(explode(' ', $query)[0] == 'SELECT'){
$data = $stmt->fetchALL();
return $data;
}
}
public function lastInsertId(){
$pdo = new PDO('mysql:host=localhost;dbname=poetionpics;charset=utf8', 'root', '');
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
return $pdo->lastInsertId();
}
}
Here is my INSERT code:
action.php
for($count = 0; $count < count($_POST['hidden_post_title']); $count++){
$post_title = (isset($_POST['hidden_post_title'][$count])) ? strip_tags($_POST['hidden_post_title'][$count]) : NULL;
$post_desc = (isset($_POST['hidden_post_desc'][$count])) ? strip_tags($_POST['hidden_post_desc'][$count]) : NULL;
$newvidurl = (isset($_POST['hidden_vid_url'][$count])) ? strip_tags($_POST['hidden_vid_url'][$count]) : NULL;
$url_1 = (isset($_POST['url1_hidden_id'][$count])) ? strip_tags($_POST['url1_hidden_id'][$count]) : NULL;
$url_2 = (isset($_POST['url2_hidden_id'][$count])) ? strip_tags($_POST['url2_hidden_id'][$count]) : NULL;
DB::query('INSERT INTO cloudbook_posts VALUES (\'\', :post_title, :post_desc)',
array(':post_title'=>$post_title, ':post_desc'=>$post_desc));
//This is possibly problematic code or wrong location....
$postid = DB::lastInsertId('SELECT id FROM cloudbook_posts WHERE id=:id',
array(':id'=>$_POST['id']))[0]['id'];
//End problematic code
DB::query('INSERT INTO vid_info VALUES (\'\', :newvidurl, :postid)',
array(':newvidurl'=>$newvidurl, ':postid'=>$postid));
DB::query('INSERT INTO url_1 VALUES (\'\', :url_1, :postid)',
array(':url_1'=>$url_1, ':postid'=>$post_id));
}
echo str_replace(array('hidden_post_title', 'hidden_post_desc', 'url1_hidden_id', 'url2_hidden_id', '{', '}', '"', ',', ':'), '',
htmlspecialchars(json_encode($result), ENT_NOQUOTES));
?>
What I’m getting in the database is this:
vid_info table
id | newvidurl | postid
69 | some user data | 0
What I want is:
vid_info table
id | newvidurl | postid
69 | some user data | $postid (see action.php for variable value)