I made a fairly simple script to take records from a development database, and for each selected record insert it into production and get the newly created ID.
This "Works" but only for one record. WHen I run this script, it successfully connects, selects, inserts, and prints the newly inserted record's ID but then the script just stops and when I check the database only one new record is there, even though there are over 500 records in the source table
Is it just becuase I'm using While instead of foreach? I think I've done something similar before with a while loop but this isjust dying on me after one successful attempt.
if($DB2connDEV && $DB2connPROD){
$getDevelopment = "
SELECT * FROM TEST_TABLE; // there are over 500 records in here
";
$stmt = odbc_exec($DB2connDEV, $getDevelopment);
while($gettingDevelopment = odbc_fetch_array($stmt)){
$originalID = $gettingDevelopment['identity'];
$insertTable = "INSERT INTO testing_insert_php (name) VALUES ($originalID)";
$getIdentity = "SELECT IDENTITY_VAL_LOCAL() AS LASTID FROM SYSIBM.SYSDUMMY1";
$stmt = odbc_exec($DB2connPROD, $insertTable);
$stmt = odbc_exec($DB2connPROD, $getIdentity);
$row = odbc_fetch_array($stmt);
$ret = $row['LASTID'];
if($ret) {
echo "Last Insert ID is : " . $ret . "\n";
} else {
echo "No Last insert ID.\n";
}
}
odbc_close($DB2connPROD);
}
Related
I have created a program in which a user will enter what device they are using and will then perform a task to test their performance based on the device they are using. The user will be taken to a start page in which they will type what device they are using, select from a drop down what hand they are using and the screen width and height will be collected via Javascript along with a primary key called DeviceID. So far all this data is stored in my first table. The second table contains data relating to the user performance such as time etc.
The first table has a one-to-many relationship with the second table as for every 1 device there will be approximately be 100 results.
The part which I am struggling with however is being able to recognise which device entered has gotten which results (i.e. DeviceID 1 got these results, DeviceID 2 got those results etc) and how I can view this relationship.
Edit:
First PHP Page
<?php
include 'db.php';
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$HandUsed = $_POST['HandUsed'];
if(isset($_POST['submit']))
{
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$phoneType = $_POST['phoneName'];
$HandUsed = $_POST['HandUsed'];
echo 'hello';
$sql = "INSERT INTO deviceInfo (screenWidth, phoneType, screenHeight, HandUsed)
VALUES ('$screenWidth','$phoneType', '$screenHeight', '$HandUsed')";
if (sqlsrv_query($conn, $sql)) {
// echo "New record has been added successfully !";
} else {
echo "Error: " . $sql . ":-" . sqlsrv_errors($conn);
}
sqlsrv_close($conn);
}
Second PHP Page
<?php
include 'db.php';
$Xpos = $_POST['Xpos'];
$Ypos = $_POST['Ypos'];
$StartID = $_POST['StartID'];
$Random = $_POST['RandomID'];
$Time = $_POST['timeTaken'];
$sql = "INSERT INTO UserResults6(Xpos, Ypos, StartID, RandomID, TimeTaken, DeviceID)
VALUES ('$Xpos', '$Ypos', '$StartID', '$Random', '$Time', SELECT DeviceID from deviceInfo)";
if (sqlsrv_query($conn, $sql)) {
echo "New record has been added successfully !";
} else {
echo "Error: " . $sql . ":-" . sqlsrv_errors($conn);
}
sqlsrv_close($conn);
?>
In the first page everything works as intended and I am given the information that I want along with an auto-incremented DeviceID. In the first page everything works up until the select statement to get the DeviceID. The outcome that I would be hoping for would be for the DeviceID to match with DeviceID from the prior table but I am currently unsure of how to go about achieving this.
My Insert query is :
function CreateResult($init_quizz_id,$result_title,$result_image,$result_description) {
$sql = "INSERT INTO result_quizz(init_quizz_id,result_title
,result_image,result_description)
VALUES('$init_quizz_id','$result_title','$result_image','$result_description')";
if ( $GLOBALS['conn']->query($sql) === TRUE) {
echo "Result Added";
$sql2 = "UPDATE 'init_quizz' SET 'results_count' = 'results_count' +1 WHERE 'quizz_id' = '$init_quizz_id'";
$GLOBALS['conn']->query($sql2);
if (!$GLOBALS['conn']->query($sql2)) {
echo ' NO UPDATE';
}
}
}
Lets say i have init_quizz table with the questions, and another table quizz_results. I want to increase the results_count on every quizz when result is added. My result table is hoilding also an init_quizz_id which is the actual ID of the quizz.
Im beginner so im looking for any solution to that.
Thanks
edit: fixed the error on the second query( sql2 ) and getting "not updated" msg. Seems like my second query is completely wrong. Any ideas?
#barmar was right, i found a better solution for my counter instead of UPDATE, i just returning the affected rows which have quizz_id from my results table.
function GetResultsCountByID($quizz_id) {
global $conn;
$sql = "SELECT * FROM result_quizz WHERE init_quizz_id = '$quizz_id'";
$result = $conn->query($sql);
return mysqli_affected_rows($conn);
}
I'm working with a file and I'm attempting to do multiple select statements one after another and insert some values. So far the insert and the select I've got working together but when attempting to get the last SELECT to work I get no value. Checking the SQL query in workbench and everything works fine. Here's the code:
$id = "SELECT idaccount FROM `animator`.`account` WHERE email = '$Email'";
$result = mysqli_query($dbc, $id) or die("Error: ".mysqli_error($dbc));
while($row = mysqli_fetch_array($result))
{
echo $row[0];
$insert_into_user = "INSERT INTO `animator`.`user` (idaccount) VALUES ('$row[0]')";
}
$select_userid = "SELECT iduser FROM `animator`.`user` WHERE iduser = '$row[0]'";
$results = mysqli_query($dbc, $select_userid) or die("Error: ".mysqli_error($dbc));
while($rows = mysqli_fetch_array($results))
{
echo $rows[0];
}
I do not want to use $mysqli->multi_query because of previous problems I ran into. Any suggestions? And yes I know the naming conventions are close naming... They will be changed shortly.
Your code makes no sense. You repeatedly build/re-build the $insert_int-User query, and then NEVER actually execute the query. The $select_userid query will use only the LAST retrieved $row[0] value from the first query. Since that last "row" will be a boolean FALSE to signify that no more data is available $row[0] will actually be trying to de-reference that boolean FALSE as an array.
Since you're effectively only doing 2 select queries (or at least trying to), why not re-write as a single two-value joined query?
SELECT iduser, idaccount
FROM account
LEFT JOIN user ON user.iduser=account.idaccount
WHERE email='$Email';
I'm not sure what you're trying to do in your code exactly but that a look at this...
// create select statement to get all accounts where email=$Email from animator.account
$id_query = "SELECT idaccount FROM animator.account WHERE email = '$Email'";
echo $id_query."\n";
// run select statement for email=$mail
$select_results = mysqli_query($dbc, $id_query) or die("Error: ".mysqli_error($dbc));
// if we got some rows back from the database...
if ($select_results!==false)
{
$row_count = 0;
// loop through all results
while($row = mysqli_fetch_array($result))
{
$idaccount = $row[0];
echo "\n\n-- Row #$row_count --------------------------------------------\n";
echo $idaccount."\n";
// create insert statement for this idaccount
$insert_into_user = "INSERT INTO animator.user (idaccount) VALUES ('$idaccount')";
echo $insert_into_user."\n";
// run insert statement for this idaccount
$insert_results = mysqli_query($dbc, $insert_into_user) or die("Error: ".mysqli_error($dbc));
// if our insert statement worked...
if ($insert_results!==false)
{
// Returns the auto generated id used in the last query
$last_inisert_id = mysqli_insert_id($dbc);
echo $last_inisert_id."\n";
}
else
{
echo "insert statement did not work.\n";
}
$row_count++;
}
}
// we didn't get any rows back from the DB for email=$Email
else
{
echo "select query returned no results...? \n";
}
I am having a really odd problem here, in that I can replace a record but cant create new ones for some reason. If I create an album with id = 2hdfhh4 and then submit an album with the same id the details get updated. If I try posting a new album nothing happens, I don't even get any errors either ?.
include("connect.php");
$photostring = implode(',',$photos);
$albumname = htmlspecialchars($albumname);
$sqlA = <<<SQL
SELECT *
FROM `albumorders`
WHERE albumid = '$albumid'
LIMIT 1
SQL;
if(!$resultA = $db->query($sqlA)){
die('There was an error running the query [' . $db->error . ']');
}
while($rowA = $resultA->fetch_assoc()){
if ($albumid = $rowA['albumid']){
mysqli_query($db,"UPDATE albumorders SET `albumid`='$albumid',`albumname`='$albumname',`imagesordered`='$photostring' WHERE `albumid`='$albumid'");
}
else {
mysqli_query($db,"INSERT INTO albumorders (`albumid`,`albumname`,`imagesordered`) VALUES ('$albumid','$albumname','$photostring')");
}
}
My table looks like this :
if ($albumid = $rowA['albumid']){
is an assignment, so it always evaluates to true and you won't get to the else part.
It should be:
if ($albumid == $rowA['albumid']) {
Here you are double checking the value.
The SQL Query will check whether the row with $albumid is available or not.
So, what you can do is you can directly check the sql result. If sql result is avaiable you update the row else you insert into data into the table...
A company I am working for has a Progress DB that store much of their information. They asked me to make a PHP script that can pull data from it and merge it with data inside of a MySQL database.
At first I figured I would just fetch the data, but after a while I found that the Progress DB was incredibly slow. I decided to have the page fetch from either MySQL or Progress depending on which had it (MySQL trumping Progress)
I ran into a problem though in that for some reason ODBC and MySQL don't seem to be able to function when both open. How can I solve this? Is it possible to do what I am needing it to do?
Note: I threw catches for errors all over the place and MySQL never returned an error. The ODBC always goes and returns the content, but it never INSERTs it into the MySQL DB
Here is my code:
$job_num = "59505";
$fields = 'JobNum, Name, City, State, StartDate, ReqDueDate';
$field_queries = 'j.JobNum AS JobNum, Name, City, State, jh.StartDate AS StartDate, ReqDueDate';
//Determine if there is a record in the MySQL DB that has the job
$mysqlr = mysql_query("SELECT * FROM jobsinfo WHERE JobNum='$job_num'");
if(!$mysqlr){
die(mysql_error());
}
//If there is a record, display it from there: faster
if(mysql_num_rows($mysqlr) > 0){
//Take the fields and explode them into an array so that it can be looped through.
$field_array = explode(', ', $fields);
//Return each row from the database
while($row = mysql_fetch_array($mysqlr)){
//Return all fields in the array
foreach($field_array as $key=>$field){
echo $field .": ".$row[$field]."<br>";
}
//Because the Description comes from a different part of the Progress include it here.
echo "Description:<br>".$row['Description'];
}
}else{
//If there is no record in the MySQL display it from the Progress AND copy it over.
//Begin by inserting a record to later be modified
mysql_query("INSERT INTO jobsinfo (JobNum) VALUES ('$job_num')") or die(mysql_error());
$id = mysql_insert_id();
//Connect to the Progress DB
$conodbc = odbc_connect($dsn, $username, $password, SQL_CUR_USE_ODBC);
//Explode the fields so that they can be looped through.
$field_array = explode(', ', $fields);
//Make the query to the Progress DB. Merge many tables into one query using JOINs
$sql = "SELECT TOP 1 ".$field_queries." FROM PUB.JobProd j LEFT JOIN PUB.BookOrd b ON j.OrderNum=b.OrderNum LEFT JOIN PUB.Customer c ON b.CustNum=c.CustNum LEFT JOIN PUB.JobHead jh ON j.JobNum=jh.JobNum WHERE j.JobNum = '$job_num' ORDER BY ReqDueDate DESC";
//Execute the query
$rs = odbc_exec($conodbc,$sql) or die('Select failed!');
//For each record loop through
while(odbc_fetch_row($rs)){
//For each field display
foreach($field_array as $key=>$field){
$value = odbc_result($rs, $field);
echo $field.": ".$value."<br>";
//Update the previously inserted row with the correct information
mysql_query("UPDATE jobsinfo SET ".$field."='$value' WHERE id = '$id'");
}
}
//Because there are multiple job parts it is easiest to just loop through it seperately and not JOIN it
$sql_asmbl = "SELECT * FROM PUB.JobAsmbl AS ja WHERE JobNum = '$job_num'";
//Execture
$rs_asmbl = odbc_exec($conodbc,$sql_asmbl) or die('Select failed!');
echo 'Description:<br>';
$ptdesc ='';
//Loop through all the rows that match the job number
while(odbc_fetch_row($rs_asmbl)){
$ptdesc .= odbc_result($rs_asmbl, 'PartNum') ." - ";
$ptdesc .= odbc_result($rs_asmbl, 'Description') ."<br>";
}
$ptdesc = mysql_real_escape_string($ptdesc);
//Update the MySQL
mysql_query("UPDATE jobsinfo SET Description = '$ptdesc' WHERE id = '$id'");
//Display it
echo $ptdesc;
//Close DB's
odbc_close($conodbc);
mysql_close($conn);
}
You are assuming that MySQL queries always run successfully:
$mysql = mysql_query("SELECT * FROM jobsinfo WHERE JobNum='$job_num'");
if(mysql_num_rows($mysql) > 0){
}
You should always test it explicitly:
$mysql = mysql_query("SELECT * FROM jobsinfo WHERE JobNum='$job_num'")
if( !$mysql ){
die(mysql_error());
}
I see that you make an ODBC connection, but I do not see mysql_connect() or something similar using mysqli or PDO. Are you actually opening a socket connection to mysql and you just left that out of this code example or did you forget to make the connection in your code?
I moved the INSERT up a bit and removed the ' from ('JobNum') and now it works fine.
Found the cause of the error. Both the MySQL and ODBC were using $conn as their connecting variable. This was causing errors.