Execute 2 mysql Queries with the second being based on the first - php

Hi I have two tables that I need to insert into.
the issue is that the first table has an ID field that is automatically generated and I need this field in the second query
members (table1):
|id|name|eyeColour|
assignedMembers (table 2):
|id|memberID|groupID|
I am currently using the below:
$addMember = $dbHandle->prepare("INSERT INTO members(name,date) VALUES(?,?)");
$addMember->bind_param("ss",$name,$eyeColour);
$addMember->execute();
$getID = $dbHandle->("SELECT id from members where name = ? LIMIT 1");
$getID->bind_param("s",$name);
$getID->execute();
$getID->bind_param($MID);
$assignMember= $dbHandle->prepare("INSERT INTO assignedMembers memberID,groupID) VALUES(?,4)");
$assignMember->bind_param("i",$MID);
$assignMember->execute();
This fails at the $assignMember->bind_param(); after troubleshooting I noticed that the $MID variable is empty.
it seems as though the row from the first INSERT is not added before the execution of the next statement is there a way to force this?
Thank you for taking the time to read this post, any help would be greatly appreciated

mysqli:$insert_id is what you are looking for.
$addMember = $dbHandle->prepare("INSERT INTO members(name,date) VALUES(?,?)");
$addMember->bind_param("ss",$name,$eyeColour);
$addMember->execute();
$id = $dbHandle->insert_id;

I think you should use
$getID->bind_result($MID);
$getID->fetch();
instead of
$getID->bind_param($MID);

Due to usage of '...->bind_param' I assume, you use MySQLi.
Check out: mysqli_insert_id — Get the ID generated in the last query

Related

php pdo code for for loop to insert values in sequence order /increment order

plz suggest me
what i need is ..when i entered 5 in book_no txtbox then insert 5 rows in
database and values goes in book_no column like 1,2,3,4,5,,,,like wise...
plz suggest me what to change in my for loop....
below code works perfect but values not going in sequential order...
$book_no = $_POST['book_no'];
for($row=1;$row<=$book_no;$row++)
{
$insertrow = $database->insertRow("INSERT INTO scheme_master (book_no,created) VALUES (:book_no,:created)",
array(':book_no'=>$book_no,':created'=>$created));
}
Replace this
':book_no'=>$book_no
with this:
':book_no'=>$row
Ok understood, I think you need to set auto increment in mysql to desired value. This would solve your problem?
If not, you can use lastInsertId method from PDO
link

Using a SELECT Query to look up a UPDATE Query on MySQL

I'm using a SELECT query to obtain a variable using mysql_fetch_assoc. This then puts the variable into an UPDATE variable to put the returned value back into the database.
If I hard code the value, or use a traditional variable and it goes in just fine, but it doesn't work when using a value previously retrieved from the database. I've tried resetting the array variable to my own text and that works.
$arrgateRetrivalQuery = mysql_query(**Select Query**);
$arrGate = mysql_fetch_assoc($arrgateRetrivalQuery);
$arrivalGateTest = $arrGate['gatetype'];
$setGateAirportSQL = "UPDATE pilots SET currentgate = '".$arrivalGateTest."' WHERE pilotid = '".$pilotid."'";
$setGateAirportQuery = mysql_query($setGateAirportSQL);
// Close MySQL Connection
mysql_close($link);
This will just make the field to update have nothing in it, however whenever I remove the variable from the SELECT to one I define, array or not, it will work.
Hope this is clear enough. Thanks in advance.
Is arrivalGateTest a number or a string? How did you try to put another value in the query? If you are sure the previous query returns a value, try to write: $setGateAirportSQL = "UPDATE pilots SET currentgate = '$arrivalGateTest' WHERE pilotid = '$pilotid'";.
Just change your sql to inlcude a subquery.
You could use the following general syntax:
UPDATE pilots SET currentgate = (SELECT gate FROM airport WHERE flight='NZ1') WHERE pilotid='2';
which is demonstrated on this fiddle
This saves the extra query and more accurately describes what you are trying to achieve.
WARNING - test it carefully first!

PHP, PDO binding dynamic number of values into the statement

I need effective some solution for the following issue:
For some reason that would be too much time-consuming to explain properly, I need a PDO prepare statemnt sorta looking this way:
'SELECT field, another field, blabla FROM table WHERE some_foreign_id = first_val AND the_same_foreign_id = second_val AND again_the_same_id = third val ......'
and Id wish to fill the values with an array of unknown size, that depends on how many fields in that foreign table fits to a certain category in yet another table.
So the querstion is: is it even possible or should I give it up and find some naive walkaround?
Thanks in advance!
Mac
You can pass an array of values into stmt ->execute($array); The only tricky part would be getting the number of question marks to enter.
$foreign_ids = array(foreign_id_1, foreign_id_2, foreign_id_3); //etc
$input_list = substr(str_repeat(',?', count($foreign_ids)), 1); //this gets you the correct number of ? to use for your query
// if you need add another value to the parameters you can use array_push($foreign_ids,$your_other_param);
$stmt= $dbh->prepare("
SELECT field, another_field
WHERE some_foreign_id = ($input_list)");
$stmt->execute($foreign_ids);
It should be possible. You'll need to generate your query dynamically with question marks for parameters, and then bind with an array at the point of execution.
See example 3 on the PDO::execute page of the PHP docs.

mysql query does not work on different files -php

i might be doing some idiot mistake, but i could not figure that out. i have some values coming from html and wanna insert into mysql db. problem is, the very same query does not work in regular php file (that includes other queries), but when i try on an independent php file, it does. here is a sample of the code:
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '".$_POST['Article_Title']."') ";
mysql_query($sql15);
as i mentioned, the very same code works when i just copy this snippet to a new php file, and it works smoothly.. as you see, there are 20+ insert with the same php, because there are 25+ tables, but data is not much. first 14 query and following 7 queries do work by the way.
do you have any ideas?
There are some things to check and do.
Sanitize user input:
"('$article_id', '".mysql_real_escape_string($_POST['Article_Title'])."')";
You might also want to check if the value is what you expect.
Is your $article_id correct for column Article_ID?
Are your table and column names correct?
Check for errors:
$res = mysql_query($sql15);
if (!$res)
echo mysql_errno($link) . ": " . mysql_error($link);
Show us you complete query:
echo $sql15;
First of all i would suggest you to write your insert query like below
$sql15="insert into body SET Article_ID = '$article_id', Article_Title = '".$_POST['Article_Title']."'";
echo $sql15;
mysql_query($sql15);
so that each time when you add new column to database it would be easy for u to change insert query. echo your query and see it in browser. in it seems to o.k then copy it and paste it in SQL section under your phpmyadmin (see you are choosing proper database) and run it. if one row inserted successfully then your query is alright.
I hope this would help you a little.
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '".$_POST['Article_Title']."') ";
mysql_query($sql15) or die(mysql_error());
use like this u will be get the error. then u will be find the issue
I think using mysql_real_escape_string may solve your problem.I also recommend you to store your form data in a string.
$article_title= mysql_real_escape_string($_POST['Article_Title']);
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '$article_title') ";
mysql_query($sql15) or die(mysql_error());

only retrieving 1 row of data from MYSQL database

I am trying to input multiple pieces of data through a form and all the data will be separated by (,). I plan to use this data to find the corresponding id for further processing through an sql query.
Below is the code I use.
$key_code = explode(",", $keyword);
//$key_count = count($key_code);
$list = "'". implode("','", $key_code) ."'";
//$row_count = '';
$sql4= "SELECT key_id FROM keyword WHERE key_code IN (".$list.")";
if(!$result4 = mysql_query($sql4, $connect)) {
mysql_close($connect);
$error = true;
}else{
//$i = 0;
while($row = mysql_fetch_array($result4)) {
$keyword_id[] = $row['key_id'];
//$i++;
}
//return $keyword_id;
}
The problem i see is that keyword_id[0] is the only element that contains any data (the data is accurate). Even if I input multiple values through the aforementioned form.
I thought it might be an error in the sql but I echo'ed it and it looks like:
SELECT key_id FROM keyword WHERE key_code IN ('WED','WATER','WASTE')
The values in the brackets are exactly what I inputted.
I even tried to figure out how many rows are being returned by the query and it shows only 1. I assume something is wrong with my query but I cannot figure where.
Any help will be greatly appreciated.
Edit: Alright Solved the problem. Thanks to suggestions made I copied and pasted the $sql_query I had echo'ed on the website into mysql console; which resulted in only 1 row being retrieved. After taking a closer look I realized that there was a whitespace between ' and the second word. I believe the problem starts when I input the key_code as:
WED, WATER, WASTE
Instead inputting it as
WED,WATER,WASTE
fixes the problem. I think I should make it so that it works both ways though.
Anyway, thank you for the help.
I am pretty sure that the query is ok. How many rows do you get with just
SELECT key_id FROM keyword
I think that there is just one line that matches your WHERE.
Check the query directly in the database(with phpmyadmin, or in the mysql console), however this query seems to be working as you may assumed. If it returns only 1 row when you use it directly in the db, then maybe there is only one row in your table wich matches this query.

Categories