Changing mysql to PDO

Hey all,

I need to switch from mysqli to PDO lib, and what I managed to to is to connect to database and list existing entries, but when I’m trying to insert I’m having a problems.
Here’s what I previously had in mysqli:

$firstName = $db-> real_escape_string($_POST['first_name']); $lastName = $db->real_escape_string($_POST['last_name']); $licnakarta = $db->real_escape_string($_POST['licnakarta']); $sql = "INSERT INTO subjects (first_name,last_name,licnakarta,kompanija,regbr,kategorija,brdokumenta,domacin,comment,potpis) VALUES('".$firstName."', '".$lastName."', '".$licnakarta ."', '".$kompanija ."', '".$regbr."', '".$dep."', '".$brdokumenta."', '".$dom."', '".$comment."', '".$potpis."')";

This is processing when form input is sent, and I’m not sure if how to change real_escape_string, from what I understand I won’t need that at all as I’m using the prepare when running queries?
In that case, how should I handle this variables and pass it to query? I tried to just leave $firstName = $_POST[‘first_name’] but it won’t insert anything to db.
as for $sql, i changed it to:

$sql = 'INSERT INTO subjects (first_name,last_name,licnakarta,kompanija,regbr,kategorija,brdokumenta,domacin,comment,potpis) VALUES(:firstname, :lastname, :licnakarta, :kompanija, :regbr, :dep, :brdokumenta, :dom, :comment, :potpis)'; $success = $db->prepare($sql); $stmt->execute(['firstname' => $firstName, 'lastname' => $lastName, 'licnakarta' => $licnakarta, 'kompanija' => $kompanija, 'regbr' => $regbr, 'kategorija' => $dep, 'brdokumenta' => $brdokumenta, 'domacin' => $dom, 'comment' => $comment, 'potpis' => $potpis]);
<?php

$sql = 'INSERT INTO subjects (
			first_name,
			last_name,
			licnakarta,
			kompanija,
			regbr,
			kategorija,
			brdokumenta,
			domacin,
			comment,
			potpis) 
        VALUES(
        	:firstname, 
        	:lastname, 
        	:licnakarta, 
        	:kompanija, 
        	:regbr, 
        	:dep, 
        	:brdokumenta, 
        	:dom, 
        	:comment, 
        	:potpis)'; 

$success = $db->prepare($sql); 
$stmt->execute([
	'firstname' => $firstName, 
	'lastname' => $lastName, 
	'licnakarta' => $licnakarta, 
	'kompanija' => $kompanija, 
	'regbr' => $regbr, 
	'kategorija' => $dep, 
	'brdokumenta' => $brdokumenta, 
	'domacin' => $dom, 
	'comment' => $comment, 
	'potpis' => $potpis
	]);

So, after reformatting due to the sites inability to keep things nice…
Drop the extra variables, they aren’t needed. Use the $_POST values that they came in on.

I can’t read most of what you are doing, but if possible, I would consider redesigning your database, it looks like it’s not normalized as well.

Sponsor our Newsletter | Privacy Policy | Terms of Service