I tried this way:
$result = odbc_exec($connection, 'SELECT id FROM MyTable WHERE id = ##Identity');
but it gives me
syntax error: unexpected T_VARIABLE
edit: here's complete logic thanks to your help:
$result = odbc_exec($connection, 'INSERT data into the table;SELECT SCOPE_IDENTITY() AS id;');
$row = odbc_fetch_array($result); //this line gives the error!
$id = $row['id'];
edit2: I missed a ";" =_=
Anyway scope_identity does not work: gives
no tuples available at this index
on fetcharray call
After inserting a row, you can look up the last inserted id using scope_identity(). There's no need to look it up in the original table:
SELECT SCOPE_IDENTIY()
If the row was inserted on another connection, you can query the maximum value of id:
SELECT max(id) FROM MyTable
Why aren't you just saying:
$result = obdc_exec('INSERT dbo.MyTable(...) VALUES(...); SELECT id = SCOPE_IDENTITY();');
Or better yet, put the logic into a stored procedure and stop burying ad hoc SQL in your application code.
EDIT because PHP is weird and may treat your INSERT as a resultset, you may need to play with this (pardon me, but I am not a PHP expert):
odbc_next_result($result);
You may also be able to suppress the first result by saying:
SET NOCOUNT ON; INSERT ...; SELECT id = SCOPE_IDENTITY();
Again, I don't know, I don't do PHP. I still think you should be doing this in a stored procedure.
Related
I have two tables, Requests & Accounting_Fundscenter_Request
I'm creating a SQL query in PHP that updates
Request_ID from Accounting_Fundscenter_Request WHERE ID is max
to
the max Request_ID from Requests
So far I have gotten the max(Request_ID) rom Requests, but I don't know how to take that value in php & sql and update the other Request_ID to equal that value.
Also, I cannot use the syntax "max(id)" because the "max" function will not work in my first query and I don't know why.
Here's what I have so far:
/* GET MAX ID FROM REQUESTS */
$selectMaxID = 'SELECT Request_ID FROM Requests ORDER BY Request_ID DESC LIMIT 1';
$maxIdResult = mysqli_query($conn, $selectMaxID); //run query
if (mysqli_num_rows($maxIdResult) > 0) {
while($maxid = mysqli_fetch_assoc($maxIdResult)) {
echo "Max Request ID: " . $maxid["Request_ID"]. "<br>";
} //echo result of
}
$insertFundsCenterMaxId = "INSERT INTO `Accounting_Fundscenter_Request` (
`Request_ID`,
VALUES (
$maxid["Request_ID"],
)
WHERE MAX(`ID`);";
/* RUN THE QUERY */
$insertFundsCenterMaxId = mysqli_query($conn, $insertFundsCenterMaxId);
This does not work. Is there a way to fix this or maybe do it in one query?
EDIT: with your help I found the solution:
You have many options here:
You can fix the syntax error you have in you insert query execution like this:
$insertFundsCenterMaxIdQuery = sprintf('INSERT INTO Accounting_Fundscenter_Request (Request_ID) VALUES (%d)', $maxid["Request_ID"]);
/* RUN THE QUERY */
$insertFundsCenterMaxId = mysqli_query($conn, $insertFundsCenterMaxIdQuery);
This way you use string formatting to replace the variable instead of directly using $maxid["Request_ID"] in a string.
Please replace %d with %s in case the Request_ID is supposed to be string/varchar.
Or you can follow another approach and just use one query to do the work like this:
INSERT INTO Accounting_Fundscenter_Request (Request_ID)
SELECT MAX(Request_ID) FROM Requests
And just execute this query
You're facing a syntax error in the update query:
$insertFundsCenterMaxId = "INSERT INTO `Accounting_Fundscenter_Request` (
`Request_ID`,
VALUES (
$maxid["Request_ID"],
)
WHERE MAX(`ID`);";
Using the double quotes in that variable hiding in the VALUES part, you are ending the string contained in insertFundsCenterMaxId. Following it is a raw string containing Request_ID which cannot be parsed by PHP. That's simply invalid code.
To solve it, you could start using prepared statements. They will also help you to secure your application against SQL injection.
There is also a solution to the syntax error problem alone - but that will leave your application vulnerable. That's why I haven't included a fix for that, but by checking how to build strings you might find it on your own. But please, please do not use it for this problem. Please.
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
i have a user database and i have to assign a user id for them for example AA01
AND after insert 1 person into database i have to insert another person with user id AA02 AND i have increment it and so on.
what i have already tried is
$sql_user_id=mysql_query("SELECT MAX(user_id) FROM `users` desc LIMIT 1");
$new_array = explode('AA',$sql_user_id);
$number=$new_array[1];
$newnumber=$number+1;
and i am getting wrong with result Resource id #5
You have to fetch the query results before you can use them.
$result=mysql_query("SELECT MAX(user_id) AS maxId FROM `users` desc LIMIT 1");
$sql_user_id = mysql_fetch_assoc($result);
$new_array = explode('AA',$sql_user_id['maxId']);
$number=$new_array[1];
$newnumber=$number+1;
FYI, I added an alias to your query as it makes referencing a value returned from a function much easier to do.
mysql_query() returns a resource, not a value you can operate directly. You have to fetch the value from this resource first:
$res = mysql_query('SELECT MAX(`user_id`) FROM `users`');
$val = mysql_fetch_row($res);
$new_array = explode('AA', $val[0]);
...
Also, notice that MAX() causes an implicit grouping to happen. So there is no order, and there is only one result. Specifying any of this in your query is futile.
In addition, notice that, since user_id is aparently a text, it might not work as expected. When sorting text, 2 comes after 10. You may need to use a different reference to fetch the latest user_id. If you can help it, don't use text to index your records.
So, I had this code working earlier today--and all of a sudden it decided to only start displaying the first result from the query. I cannot figure out what i've changed since then, I actually believe that I haven't changed anything... anyway... I've gone into the DB and altered the table so that all the "upgrades" meet the requirements to be displayed, and yet still only one result is being shown.
$sql = "SELECT id, name, cost, count(*) FROM upgrades
WHERE id NOT IN (Select upgrade_id FROM thehave8_site1.user_upgrades WHERE uid = :uid)
AND nullif NOT IN(SELECT upgrade_id FROM thehave8_site1.user_upgrades WHERE uid = :uid2)
AND prereq IN (SELECT upgrade_id FROM thehave8_site1.user_upgrades WHERE uid = :uid3)
;";
$que = $this->db->prepare($sql);
#$que->bindParam(':id', $id); //note the : before id
#$que->bindParam(':id2', $id);
$que->bindParam(':uid', $this->uid);
$que->bindParam(':uid2', $this->uid);
$que->bindParam(':uid3', $this->uid);
try {
$que->execute();
while($row = $que->fetch(PDO::FETCH_BOTH))
{
echo "<div class='upgrade' id={$row[0]}><p>{$row[1]}</p><p>{$row[2]}</p></div>";
}
} catch(PDOException $e) { echo $e->getMessage();}
Problem has been solved, though I'm not sure of the exact reason why, the count(*) being at the end of the query string was preventing the entire code from running properly
Aren't you missing some line of code that advances the result in the query to the next row? When I do loops through recordsets (slightly different than what you are doing but probably not much different) there is usually a MoveNext or something like that - I see nothing like that here.
I don't know this language you are using.
......
I am not being allowed to add a comment to your response so I will add it here..
....
Cool. You really looked like you knew what you were doing, far more advanced than anything I've written! New here also and didn't catch onto the tag system, thanks for pointing that out so I don't need to embarrass myself in future. Glad you've solved it. I think Count (*) would work if you included it as a subquery
SELECT FIELD1, FIELD2, (SELECT count (*) FROM ... ) AS FIELD3
FROM (ETC)
or if you just want its value in the recordset result, compute it ahead of time via query, and then include its value as a dummy/constant field in your select statement. Depending on the query plan in your query engine this may or may not be more efficient.
Or just wait to get Recordcount from your recordset.
Hi there i am working on PHP code that is selecting columns from two tables.
Here is my code:
$result2 = mysql_query("SELECT *
FROM `videos`, `m_subedvids`
WHERE `videos.approved`='yes' AND
`videos.user_id`='$subedFOR'
ORDER BY `videos.indexer`
DESC LIMIT $newVID");
while($row2 = mysql_fetch_array($result2))
{
$indexer = addslashes($row2['videos.indexer']);
$title_seo = addslashes($row2['videos.title_seo']);
$video_id = addslashes($row2['videos.video_id']);
$title = addslashes($row2['videos.title']);
$number_of_views = addslashes($row2['videos.number_of_views']);
$video_length = addslashes($row2['videos.video_length']);
}
When i try to print $indexer with echo $indexer; it's not giving me any results.
Where is my mistake in this code?
It seems to me like the key 'indexer' isn't in your results. It's hard to tell, since you haven't listed a definition for your table and you're using SELECT * so we can't see the names.
It makes the program easier to read later, if instead of SELECT *..., you use SELECT col1, col2, .... Yes, SELECT * will save you some typing right now, but you'll lose that time later when you or anyone else who works on your code has to check the table definition every time they work with that line of code.
So, try changing your query to explicitly select the columns you use. If it's an invalid column you'll get an error right away rather than this silent failure you're getting now, and you'll thank yourself later as well.
So long as videos.indexer is a unique field name among all tables used in the query you can change
$indexer = addslashes($row2['videos.indexer']);
to
$indexer = addslashes($row2['indexer']);
You don't need to (or can not) use the table name when referring to the result.