Running Multiple MySQL Queries in PHP - php

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!

Related

implode array how to make it right? [duplicate]

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,
)
);

Sqlite Call to a member function bindParam() on boolean

Hello I try with PDO to insert data to Sqlite, i have tried many ways, but I always get following errors: Call to a member function bindParam() on boolean.
I see also the bindParam() or bindValue return false if an error exist. But I don't find an error.
thx in advance
function insertCostumers(){
$costumers = 'INSERT IGNORE INTO costumers(first_name,last_name,age)
VALUES(:first_name,:last_name,:age)';
$stmt = $this->pdo->prepare($costumers);
$data = [['firstName' => 'Hans',
'lastName' => 'Meier',
'age' => 32],
['firstName' => 'Anna',
'lastName' => 'Mueller',
'age' => 35],
['firstName' => 'Steffi',
'lastName' => 'Gygax',
'age' => 67]];
$stmt->bindParam(
':first_name', $firstName,
':last_name', $lastName,
'age', $age);
foreach ($data as $d) {
// Set values to bound variables
$firstName = $d['firstName'];
$lastName = $d['lastName'];
$age = $d['age'];
// Execute statement
$stmt->execute();
}
die('hello');
}
require "SQLiteConnection.php";
require "SQLiteCreateTable.php";
$sqlite = new SQLiteCreateTable((new SQLiteConnection())->connect());
// create new tables
$sqlite->createTables();
$sqlite->insertCostumers();
$tables = $sqlite->getOrderList();
require "index.view.php";
#SebastianBrosch Thats the Create Statement.
public function createTables() {
$commands = ['CREATE TABLE IF NOT EXISTS costumers (
costumer_id integer PRIMARY KEY,
first_name text NOT NULL,
last_name text NOT NULL,
age integer NOT NULL
)',
'CREATE TABLE IF NOT EXISTS orders (
order_id integer PRIMARY KEY,
order_nr integer NOT NULL,
costumer_id integer,
FOREIGN KEY (costumer_id) REFERENCES costumers (costumer_id)
ON DELETE CASCADE ON UPDATE NO ACTION)'];
// execute the sql commands to create new tables
foreach ($commands as $command) {
$this->pdo->exec($command);
}
}
The variable $stmt is not a PDOStatement object. It is a boolean value (in this case false).
Your INSERT statement is not valid. Try the following instead (missing OR):
$costumers = 'INSERT OR IGNORE INTO costumers(first_name, last_name, age)
VALUES(:first_name, :last_name, :age)';
You can use the methods PDO::errorInfo and PDO::errorCode to get further information.
$costumers = 'INSERT OR IGNORE INTO costumers(first_name,last_name,age)
VALUES(:first_name,:last_name,:age)';
$stmt = $this->pdo->prepare($costumers);
if ($stmt === false) {
echo $this->pdo->errorCode().': '.$this->pdo->errorInfo();
}
You also use $firstName and $lastName before init:
function insertCostumers() {
$costumers = 'INSERT OR IGNORE INTO costumers(first_name, last_name, age)
VALUES(:first_name, :last_name, :age)';
$stmt = $this->pdo->prepare($costumers);
$data = [['firstName' => 'Hans',
'lastName' => 'Meier',
'age' => 32],
['firstName' => 'Anna',
'lastName' => 'Mueller',
'age' => 35],
['firstName' => 'Steffi',
'lastName' => 'Gygax',
'age' => 67]];
foreach ($data as $d) {
$firstName = $d['firstName'];
$lastName = $d['lastName'];
$age = $d['age'];
$stmt->bindParam(':first_name', $firstName, PDO::PARAM_STR);
$stmt->bindParam(':last_name', $lastName, PDO::PARAM_STR);
$stmt->bindParam(':age', $age, PDO::PARAM_INT);
$stmt->execute();
}
}
To make sure the combination of first_name and last_name is unique, you need to add a UNIQUE constraint to your table costumers. Use the following CREATE TABLE statement:
CREATE TABLE IF NOT EXISTS costumers (
costumer_id INTEGER PRIMARY KEY,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
age INTEGER NOT NULL,
UNIQUE (first_name, last_name)
);
You can see the difference with and without the UNIQUE constraint on these following demo:
http://sqlfiddle.com/#!7/79b1c/1/1

Row name based on column ID in mysql

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

adding multiple rows in mysql table based on an array

I have a form which allows people to message each other, a user can select multiple people to message, when i submit a form it gives me the name and id of people selected to message in an array. uptil here i am able to get it to work for a single recipient
I want to be able to use this array and INSERT message for each user in different rows of mysql table
this is the array that i get when i submit a form
Array (
[to_user_id] => Array
(
[0] => 54
[1] => 55
)
[subject] => aaa
[message] => bbb
[send_message] =>
this is the part of code that works for a single recipient but not multiple
$to_user_id_array = ($_POST['to_user_id']);
$params = array(
':to_user_id' => $to_user_id_array,
':subject' => $_POST['subject'],
':message' => $_POST['message'],
':sender_id' => $this->user_id,
':status' => "0",
':type' => "message",
':sender_name' => $sender_name,
':to_user_name' => $to_user_name,
':delete_received' => 'no',
':delete_sent' => 'no',
);
$sql = "INSERT INTO `messages` (`sender_id`,`subject`,`comment`,`to_user_id`,`status`,`type`,`sender_name`,`to_user_name`,`delete_received`,`delete_sent`)
VALUES (:sender_id, :subject, :message, :to_user_id, :status, :type, :sender_name,:to_user_name,:delete_received,:delete_sent);";
parent::query($sql, $params);
$this->error = "<div class='alert alert-success'>" . _('Your message has been sent.') . "</div>";
Will really appreciate any help..
This is what worked for me, i hope this helps someone else in similar position
while ($value = $stmt->fetch(PDO::FETCH_ASSOC)) {
$params = array(
':to_user_id' => $value['user_id'],
':subject' => $_POST['subject'],
':message' => $_POST['message'],
':sender_id' => $this->user_id,
':status' => "0",
':type' => "message",
':sender_name' => $sender_name,
':to_user_name' => $value['name'],
':delete_received' => 'no',
':delete_sent' => 'no',
);
$sql = "INSERT INTO `messages` (`sender_id`,`subject`,`comment`,`to_user_id`,`status`,`type`,`sender_name`,`to_user_name`,`delete_received`,`delete_sent`)
VALUES (:sender_id, :subject, :message, :to_user_id, :status, :type, :sender_name,:to_user_name,:delete_received,:delete_sent);";
parent::query($sql, $params);
}

Trouble with PDO update

I am updating a form using PDO's update function. For some reason it is not going through.
Here is code:
$data = "UPDATE insuranceverificationdisclaimer SET InsCoName =:insur, PhoneNumber = :phone, Policy = :policy, InsuredName = :insurname
, MailingAdrs = :mailingad, EffDate = :effdate, ExpDate = :expdate, Email1 = :email, YrVehicle = :yr, Make = :make
, Model = :model, VIN = :vin, TraineeUserName = :user, EmpName = :empname, EmpCoName = :empcomp, AgencyNumber = :agnum
, SignDate = :signdate, AgentName = :agname, AgentPhone = :agphone, AgentEmail = :agemail, Combinedlimit = :csl, bodyinjur = :body
, bodyinjureachacc = :acc
, propertydmg = :prop WHERE TraineeUsername = :user";
echo"1";
$insertdata = $DBH->prepare($data);
$insertdata->execute(array(':insur' => $compname, ':phone' => $phone , ':policy' => $policynum, ':insurname' => $nameofPolicyholder
, ':mailingad' => $newMailingAdrs, ':effdate' => $Policyeffdate, ':expdate' => $Policyexpdate, ':email' => $newEmployeeEmail
, ':yr' => $YearOfVehicle, ':make' => $MakeOfVehicle, ':model' => $ModelOfVehicle, ':vin' => $Vehicleid, ':user' => $username, ':empname' => $EmployeeName, ':empcomp' => $EmployeeCompanyName, ':agnum' => $Agencynum
, ':signdate' => $TodaysDate, ':agname' => $agentname, ':agphone' => $agentphone, ':agemail' => $agentemail, ':csl' => $singlelimit
, ':body' => $bodyinjur, ':acc' => $eachacc, ':prop' => $propertydmg ));
Where , ':csl' => $singlelimit, ':body' => $bodyinjur, ':acc' => $eachacc, ':prop' => $propertydmg begins this is the function that is not working, these are ints in the database and the values are ints. If I remove from the select and the array it will work but besides that it will not.
Let me know if you need anything else!
UDATED---------------------------
Wont go through once you hit execute page just stays white.
You should turn on your error reporting as suggested by Michael Berkowski. For now I can only assume that the error is cause by params datatypes not being defined. You can try the following:
$insertdata->bindParam(':insur', $compname, PDO::PARAM_STR);
$insertdata->bindParam(':csl', $singlelimit, PDO::PARAM_INT);
//...bind the other params
$insertdata->execute();

Categories