This question already has answers here:
Is storing a delimited list in a database column really that bad?
(10 answers)
Closed 8 months ago.
I have a form in php wich has some checkboxes named skills[], I want to know how to implode and post the correct way in this code, I was used to the usual msqli or normal post syntax, but now that I made country state city dropdown I can't figure out a way to correctly post it:
<?php
$skills = array('PHP', 'JavaScript', 'jQuery', 'AngularJS');
$commasaprated = implode(',' , $skills);
?>
<?php
//insert.php
if(isset($_POST['country']))
{
include('database_connection.php');
$query = "
INSERT INTO country_state_city_form_data (country, state, city, skills)
VALUES(:country, :state, :city, :skills)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':country' => $_POST['country'],
':state' => $_POST['state'],
':city' => $_POST['hidden_city'],
':skills' => $_POST['skills'],
)
);
$result = $statement->fetchAll();
if(isset($result))
{
echo 'done';
}
}
?>
Inside you're if(isset($_POST['country']))
After you're include() do:
$checkedSkills = implode(", ", $_POST['skills']);
...
$statement->execute(
array(
':country' => $_POST['country'],
':state' => $_POST['state'],
':city' => $_POST['hidden_city'],
':skills' => $checkedSkills,
)
);
Related
I have a problem while inserting datas in MySQL database with PDO.
I have no error, it just seems to didn't have inserted datas in the table when I select them after execute the code with MySQL in terminal.
I've tried solutions in answers on stackoverflow, like wraping name and description in backticks, but it's still not working
Here is my sql columns :
Here is the code :
$query = $pdo->prepare("INSERT INTO cities (`name`, departement, province, lat, long, `description`, poi_id) VALUES(`:name`, :departement, :province, :lat, :long, `:description`, :poi_id)");
$query = $query->execute([
"name" => $name,
"departement" => $code_dpt,
"province" => (int)$provinces[$departements[$code_dpt]],
"lat" => $lat,
"long" => $long,
"description" => $description,
"poi_id" => (int)$poi_id
]);
$query = $pdo->prepare("INSERT INTO cities (`name`, departement, province, lat, long, `description`, poi_id) VALUES(:name, :departement, :province, :lat, :long, :description, :poi_id)");
$query->execute([
':name' => $name,
':departement' => $code_dpt,
':province' => (int)$provinces[$departements[$code_dpt]],
':lat' => $lat,
':long' => $long,
':description' => $description,
':poi_id' => (int)$poi_id
]);
use placeholder in execute function.
I've found the solution.
First, I've enabled errors like this :
$pdo = new PDO('mysql:host=localhost;dbname=bpfmgr', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
I was using a property named long for longitude, but it's a MySQL reserved keyword, so it mades errors. I've added backticks to wrap long and that's working.
In PHP I'm attempting to build a form that needs to check for an ID in one table and if it exists it should create a record in another table. So far, that works but the issue I'm having is when I attempt to handle the case if the ID I checked for didn't exist. If it doesn't exist I'd like to create another one. But every time I try it, I get 500 errors from the server when I fetch the results.
Essentially I made the following function
function trySQL($con, $query, $params) {
$stmt = $con->prepare($query);
$result = $stmt->execute($params);
$id = $stmt->insert_id;
return array($stmt,$result,$id);
}
I call this function multiple times through out my php code but when I call it more then once and attempt to fetch the results it breaks.
$custINSquery = "
INSERT INTO custs (
FirstName,
LastName,
EmailAddress,
PhoneNumber
) VALUES (
:FirstName,
:LastName,
:EmailAddress,
:PhoneNumber
)
";
$createJob = "
INSERT INTO jobs (
custs_id,
StAddress,
State,
ZipCode,
MoistureLocation,
status_id
) VALUES (
:custs_id,
:StAddress,
:State,
:ZipCode,
:IssueDesc,
:status_id
)
";
$custSELquery = "SELECT id, FirstName, LastName, EmailAddress FROM custs WHERE FirstName = :FirstName AND LastName = :LastName AND EmailAddress = :EmailAddress";
$custSELquery_params = array(
':FirstName' => $_POST['FirstName'],
':LastName' => $_POST['LastName'],
':EmailAddress' => $_POST['EmailAddress']
);
$checkcust = trySQL($db, $custSELquery, $custSELquery_params);
$row = $checkcust[0]->fetch();
if(!$row){
$custINSquery_params = array(
':FirstName' => $_POST['FirstName'],
':LastName' => $_POST['LastName'],
':EmailAddress' => $_POST['EmailAddress'],
':PhoneNumber' => $_POST['PhoneNumber']
);
$custins = trySQL($db, $custINSquery, $custINSquery_params);
$custsel = trySQL($db, $custSELquery, $custSELquery_params);
$custs_id = $custsel[0]->fetch();
if ($custs_id != null) {
$createJobParam = array(
':custs_id' => $custs_id,
':StAddress' => $_POST['StAddress'],
':State' => $_POST['State'],
':ZipCode' => $_POST['ZipCode'],
':IssueDesc' => $_POST['MoistureLocation'],
':status_id' => $_POST['status_id']
);
$jobins = trySQL($db, $createJob, $createJobParam);
$jobres = $jobins[0]->fetch();
die("um...");
if ($jobres) {
# code...
die("looks like I made it");
}
}
} else {
$createJobParam = array(
':custs_id' => $row['id'],
':StAddress' => $_POST['StAddress'],
':State' => $_POST['State'],
':ZipCode' => $_POST['ZipCode'],
':IssueDesc' => $_POST['MoistureLocation'],
':status_id' => $_POST['status_id']
);
$data['success'] = true;
$data['message'] = 'Success!';
}
Additional Notes: When I look through the php doc's they are saying that I could use the inserted_id thing in order to get the ID that I inserted previously but when I try that it just gives me nulls with this set up.
Any help would be appreciated.
Thanks!
I have a little problem. I'm very new to mysql and I'm creating some sort of basic database of cats. I'm adding 100 positions to database through that code:
$result_set = $pdo->prepare("INSERT INTO koty2 (name, age, breed, author, tag, image) VALUES (:name, :age, :breed, :author, :tag, :image)");
$result_set->execute(array(
':name' => $name,
':age' => $age,
':breed' => $breed,
':author' => $author,
':tag' => $tag,
':image' => $image
));
for ($i=0; $i<100; $i++) {
$result_set->execute(array(
':name' => $name,
':age' => $age,
':breed' => $breed,
':author' => $author,
':tag' => $tag,
':image' => $image
));
I tried multiple ways of adding the $name to the database with row's ID which is auto incremented - so it would be "Name+ID". So far I failed. Can somebody tell me how to do this?
Thank you.
One work around is, you can first insert the data you want to insert, get the last inserted ID, then just update the name by concatenating the name and ID. See below code:
// insert first
$result_set = $pdo->prepare("INSERT INTO koty2 (name, age, breed, author, tag, image) VALUES (:name, :age, :breed, :author, :tag, :image)");
$result_set->execute(array(
':name' => $name,
':age' => $age,
':breed' => $breed,
':author' => $author,
':tag' => $tag,
':image' => $image
));
// get the inserted ID
$last_ins_id = $pdo->lastInsertId();
// update the inserted name
$update_row = $pdo->prepare("UPDATE koty2 SET name = :name WHERE ID = :id");
$update_row->execute(array(
':name' => $name . $last_ins_id,
':id' => $last_ins_id
));
Im not sure if this is the best solution but this logic will still do the work
If you want to get the inserted auto-incremented ID everytime you insert a new Cat( xD ), you can use:
$pdo->lastInsertId();
http://php.net/manual/en/pdo.lastinsertid.php
This will echo the whole column "$Name $CatID" do what you want:
$stmt = $pdo->query("SELECT name, catID FROM koty2");
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
print "Name: <p>{$row[0] $row[1]}</p>";
}
For more, check:
http://php.net/manual/en/pdostatement.fetch.php
I am following tutorials for user registration. This is what I am trying to build query using implode:
if(isset($_POST['submit'])){
$registration_data= array(
'username' => $_POST['username'],
'password' => $_POST['password'],
'password_again' => $_POST['password_again'],
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email']
);
register_user($registration_data);
}
function register_user($registration_data){
global $connect;
$data=implode(',', $registration_data).'}';
$fields= implode(",", array_keys($registration_data));
Now I have to build query like this
$query=INSERT INTO users ($fields) VALUES($data);
// I want data to be formated like this '{$username}', '{$password}',
How can I do it in above mentioned implode functions,
Note: I am just following some basic tutorials so not worried about PDO/ injections etc
You need to put quotes around all the data values before you implode them:
$data = implode(',', array_map(function($x) {
return "'" . $x . "'";
}, $registration_data));
$fields = implode(',', array_keys($registration_data));
$query = "INSERT INTO users ($fields) VALUES ($data)";
Especially if you are just learning on how to do this, you should learn to do them right from the beginning.
You really don't need to use implode() with prepared statements. Just use PDO::prepare() and pass the array to PDOStatement::execute. Pseudo code is along the lines of:
$registration_data= array(
':username' => $_POST['username'],
':password' => $_POST['password'],
':password_agai' => $_POST['password_again'],
':first_name' => $_POST['first_name'],
':last_name' => $_POST['last_name'],
':email' => $_POST['email']
);
$sql='INSERT INTO yourtable VALUES (:username, :password, :password_agai, :first_name, :last_name, :email);';
$qry=$yourpdoconn->prepare($sql);
$qry->execute($registration_data);
Please note that you still need to handle your errors and everything else, but that's the gist of it. mysqli_* can do the same with prepared statements so you aren't necessarily stuck with PDO either.
I have search but dont see any answer or example that fits mine code. I am pretty new to MySQL/PHP, so I might not understand the answers I have looked at.
I have a web page that posts data over that I want to use just one insert. This is what I have so far for the insert:
$statement1 = $link->prepare("INSERT INTO collection_items(collection_list_id, collection_item_number, username_id, collection_item_title, collection_item_text, created_date)
VALUES(:collection_list_id, :collection_item_number, :username_id, :collection_item_title, :collection_item_text, now())");
$statement1->execute(array(
"collection_list_id" => $last_id,
"collection_item_number" => "1",
"username_id" => $user_number,
"collection_item_title" => $collection_item_title_1,
"collection_item_text" => $collection_item_text_1
),
(
"collection_list_id" => $last_id,
"collection_item_number" => "2",
"username_id" => $user_number,
"collection_item_title" => $collection_item_title_2,
"collection_item_text" => $collection_item_text_2
));
If I drop the last set of data it works just fine for one row. I have about 20 twenty rows of data from the page post.
TIA
This is what I have, but can't get it to work. I'v shown more code to help.
$form = $_POST;
$collection_item_title_1 = $form[ 'number1' ];
$collection_item_text_1 = $form[ 'comment1' ];
$collection_item_title_2 = $form[ 'number2' ];
$collection_item_text_2 = $form[ 'comment2' ];
$last_id = $link->lastInsertId();
$q= $link->query("SELECT id FROM sitelok WHERE Username='$slusername'");
$user_number = $q->fetchColumn();
$collection_item_titles = array($collection_item_title_1, $collection_item_text_1, $collection_item_title_2, $collection_item_text_2);
$statement1 = $link->prepare("INSERT INTO collection_items(collection_list_id, collection_item_number, username_id, collection_item_title, collection_item_text, created_date)
VALUES(:collection_list_id, :collection_item_number, :username_id, :collection_item_title, :collection_item_text, now())");
for ($i = 0; $i < size($collection_item_titles); $i++)
$statement1->execute(array(
"collection_list_id" => $last_id,
"collection_item_number" => "$i",
"username_id" => $user_number,
"collection_item_title" => $collection_item_title[$i],
"collection_item_text" => $collection_item_text[$i]
));
You could create an array and loop through the data and instead of having your data in separate variables ($collection_item_title_1, $collection_item_title_2) you could do something such as $collection_item_titles[] then loop through as such:
statement1 = $link->prepare("INSERT INTO collection_items(collection_list_id, collection_item_number, username_id, collection_item_title, collection_item_text, created_date)
VALUES(:collection_list_id, :collection_item_number, :username_id, :collection_item_title, :collection_item_text, now())");
for ($i = 0; $i < size($collection_item_titles); $i++)
$statement1->execute(array(
"collection_list_id" => $last_id,
"collection_item_number" => "$i",
"username_id" => $user_number,
"collection_item_title" => $collection_item_title[$i],
"collection_item_text" => $collection_item_text[$i]
);
You can't pass more then 1 argument to execute
You can either insert values in a foreach loop or create a query with hundreds of placeholders.
I think first way is better, for example:
$values = array(); // your inserted values array here
$statement1 = $link->prepare("INSERT INTO collection_items(collection_list_id, collection_item_number, username_id, collection_item_title, collection_item_text, created_date) VALUES(:collection_list_id, :collection_item_number, :username_id, :collection_item_title, :collection_item_text, now())");
foreach ($values as $v) {
$statement1->execute($v);
}