I've successfully refactored the below script to select records from a table on server 1, and then connect to server 2 and insert/ignore the missing records into the cloned table there.
This works but takes about 1.5 minutes to run. I'm hoping someone can help with a slightly faster and more efficient way of doing this, since it's successful but expensive.
I don't have the option to do federated storage or replication, so this has to be done with a script. I previously did this by using the max ID of the source table but after the insert I was missing up to 15 records a day.
Here's the script:
$source_data = mysqli_query($conn,
"select * from `cdrdb`.`session` where ts >= now() - INTERVAL 1 DAY");
while($source = $source_data->fetch_assoc()) {
//Insert new rows into ambition.session
$stmt = $conn2->prepare(
"INSERT IGNORE INTO ambition.session (SESSIONID,
SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO,
DIALPLANNAME,TERMINATIONREASONCODE,ISCLEARINGLEGORIGINATING,
CREATIONTIMESTAMP,ALERTINGTIMESTAMP,CONNECTTIMESTAMP,DISCONNECTTIMESTAMP,
HOLDTIMESECS,LEGTYPE1,LEGTYPE2,INTERNALPARTYTYPE1,INTERNALPARTYTYPE2
,SERVICETYPEID1,SERVICETYPEID2,EXTENSIONID1,EXTENSIONID2,
LOCATION1,LOCATION2,TRUNKGROUPNAME1,TRUNKGROUPNAME2,SESSIONIDTRANSFEREDFROM
,SESSIONIDTRANSFEREDTO,ISTRANSFERINITIATEDBYLEG1,
SERVICEEXTENSION1,SERVICEEXTENSION2,SERVICENAME1,
SERVICENAME2,MISSEDUSERID2,ISEMERGENCYCALL,NOTABLECALLID,
RESPONSIBLEUSEREXTENSIONID,
ORIGINALLYCALLEDPARTYNO,ACCOUNTCODE,ACCOUNTCLIENT,ORIGINATINGLEGID
,SYSTEMRESTARTNO,PATTERN,HOLDCOUNT,AUXSESSIONTYPE,
DEVICEID1,DEVICEID2,ISLEG1ORIGINATING,ISLEG2ORIGINATING,
GLOBALCALLID,CADTEMPLATEID,CADTEMPLATEID2,ts,INITIATOR,
ACCOUNTNAME,APPNAME,CALLID,CHRTYPE,CALLERNAME,serviceid1,serviceid2)
VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
or die(mysqli_error($conn2)) ;
mysqli_stmt_bind_param($stmt,
"iisssiissssiiiiiiiiissssiiissssiiiisssiisiiiiiiiiisisssisii"
,$source['SESSIONID']
,$source['SESSIONTYPE']
,$source['CALLINGPARTYNO']
//omitting other columns for sake of space
);
$stmt->execute() or die(mysqli_error($conn2));
}
A simple improvement would be to move the call to prepare() to before the loop. Since the prepared statement is the same each time through the loop, there's no need to contact the DB server each time.
You can also move the call to bind_param() outside the loop, since the variables are the same each time. bind_param binds to a reference, so updating the variable will change what gets inserted when you call execute().
However, these are likely to make only a small difference. One of the most effective ways to improve speed of INSERT queries is to insert multiple rows at a time. This is much easier to do with PDO than mysqli, because you can provide an array of parameters in the call to $stmt->execute(). The code would look like:
$params = array();
$count = 0;
$batch_size = 100;
$placeholders = implode(", ", array_fill(0, $batch_size, "(SESSIONID,
SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO,
DIALPLANNAME,TERMINATIONREASONCODE,ISCLEARINGLEGORIGINATING,
CREATIONTIMESTAMP,ALERTINGTIMESTAMP,CONNECTTIMESTAMP,DISCONNECTTIMESTAMP,
HOLDTIMESECS,LEGTYPE1,LEGTYPE2,INTERNALPARTYTYPE1,INTERNALPARTYTYPE2
,SERVICETYPEID1,SERVICETYPEID2,EXTENSIONID1,EXTENSIONID2,
LOCATION1,LOCATION2,TRUNKGROUPNAME1,TRUNKGROUPNAME2,SESSIONIDTRANSFEREDFROM
,SESSIONIDTRANSFEREDTO,ISTRANSFERINITIATEDBYLEG1,
SERVICEEXTENSION1,SERVICEEXTENSION2,SERVICENAME1,
SERVICENAME2,MISSEDUSERID2,ISEMERGENCYCALL,NOTABLECALLID,
RESPONSIBLEUSEREXTENSIONID,
ORIGINALLYCALLEDPARTYNO,ACCOUNTCODE,ACCOUNTCLIENT,ORIGINATINGLEGID
,SYSTEMRESTARTNO,PATTERN,HOLDCOUNT,AUXSESSIONTYPE,
DEVICEID1,DEVICEID2,ISLEG1ORIGINATING,ISLEG2ORIGINATING,
GLOBALCALLID,CADTEMPLATEID,CADTEMPLATEID2,ts,INITIATOR,
ACCOUNTNAME,APPNAME,CALLID,CHRTYPE,CALLERNAME,serviceid1,serviceid2)"));
$stmt = $pdo->prepare("INSERT INTO ambition.sentence (<columns>) VALUES $placeholders");
while ($row = $source_data->fetch(PDO::FETCH_NUM)) {
$params += $row; // Append this row to $params
$count++;
if ($count != $batch_size) {
continue;
}
$stmt->execute($params);
// Reset variables for next batch
$params = array();
$count = 0;
}
if ($count) { // Handle the last batch that isn't the full size
$placeholders = implode(", ", array_fill(0, $count, "( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"));
$stmt = $pdo->prepare("INSERT INTO ambition.sentence (SESSIONID,
SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO,
DIALPLANNAME,TERMINATIONREASONCODE,ISCLEARINGLEGORIGINATING,
CREATIONTIMESTAMP,ALERTINGTIMESTAMP,CONNECTTIMESTAMP,DISCONNECTTIMESTAMP,
HOLDTIMESECS,LEGTYPE1,LEGTYPE2,INTERNALPARTYTYPE1,INTERNALPARTYTYPE2
,SERVICETYPEID1,SERVICETYPEID2,EXTENSIONID1,EXTENSIONID2,
LOCATION1,LOCATION2,TRUNKGROUPNAME1,TRUNKGROUPNAME2,SESSIONIDTRANSFEREDFROM
,SESSIONIDTRANSFEREDTO,ISTRANSFERINITIATEDBYLEG1,
SERVICEEXTENSION1,SERVICEEXTENSION2,SERVICENAME1,
SERVICENAME2,MISSEDUSERID2,ISEMERGENCYCALL,NOTABLECALLID,
RESPONSIBLEUSEREXTENSIONID,
ORIGINALLYCALLEDPARTYNO,ACCOUNTCODE,ACCOUNTCLIENT,ORIGINATINGLEGID
,SYSTEMRESTARTNO,PATTERN,HOLDCOUNT,AUXSESSIONTYPE,
DEVICEID1,DEVICEID2,ISLEG1ORIGINATING,ISLEG2ORIGINATING,
GLOBALCALLID,CADTEMPLATEID,CADTEMPLATEID2,ts,INITIATOR,
ACCOUNTNAME,APPNAME,CALLID,CHRTYPE,CALLERNAME,serviceid1,serviceid2) VALUES $placeholders");
$stmt->execute($params);
}
For this to work as I've written it, you need to ensure that the columns returned by the SELECT query are in the same order as the list you're inserting. Avoid using SELECT * when doing this, so you don't get any surprises if there's a change in the schema of the source table.
You probably know by now that inserting one row at a time, one transaction per row, is the slowest way to load data.
I have tested different ways of loading data, and I gave a talk at Percona Live 2017:
Load Data Fast!
TL;DR: Use LOAD DATA INFILE, even if you have to dump your source data into a CSV file first.
Here's an example, though I have not tested it:
$all_columns = "
`SESSIONID`, `SESSIONTYPE`, `CALLINGPARTYNO`, `FINALLYCALLEDPARTYNO`,
`DIALPLANNAME`, `TERMINATIONREASONCODE`, `ISCLEARINGLEGORIGINATING`,
`CREATIONTIMESTAMP`, `ALERTINGTIMESTAMP`, `CONNECTTIMESTAMP`,
`DISCONNECTTIMESTAMP`, `HOLDTIMESECS`, `LEGTYPE1`, `LEGTYPE2`,
`INTERNALPARTYTYPE1`, `INTERNALPARTYTYPE2`, `SERVICETYPEID1`,
`SERVICETYPEID2`, `EXTENSIONID1`, `EXTENSIONID2`, `LOCATION1`, `LOCATION2`,
`TRUNKGROUPNAME1`, `TRUNKGROUPNAME2`, `SESSIONIDTRANSFEREDFROM`,
`SESSIONIDTRANSFEREDTO`, `ISTRANSFERINITIATEDBYLEG1`, `SERVICEEXTENSION1`,
`SERVICEEXTENSION2`, `SERVICENAME1`, `SERVICENAME2`, `MISSEDUSERID2`,
`ISEMERGENCYCALL`, `NOTABLECALLID`, `RESPONSIBLEUSEREXTENSIONID`,
`ORIGINALLYCALLEDPARTYNO`, `ACCOUNTCODE`, `ACCOUNTCLIENT`, `ORIGINATINGLEGID`,
`SYSTEMRESTARTNO`, `PATTERN`, `HOLDCOUNT`, `AUXSESSIONTYPE`, `DEVICEID1`,
`DEVICEID2`, `ISLEG1ORIGINATING`, `ISLEG2ORIGINATING`, `GLOBALCALLID`,
`CADTEMPLATEID`, `CADTEMPLATEID2`, `ts`, `INITIATOR`, `ACCOUNTNAME`, `APPNAME`,
`CALLID`, `CHRTYPE`, `CALLERNAME`, `serviceid1`, `serviceid2`"
$select_sql = "
SELECT $all_columns FROM `cdrdb`.`session`
WHERE ts >= NOW() - INTERVAL 1 DAY";
$source_data = mysqli_query($conn, $select_sql);
$tmpfilename = tempnam('/tmp', 'data');
fp = fopen($tmpfilename, 'w'); // do proper error handling and use
while ($source = $source_data->fetch_assoc()) {
fputcsv($fp, array_values($source));
}
fclose($fp);
$tmpfilename = mysqli_real_escape_string($conn2, $tmpfilename);
$load_sql = "
LOAD DATA LOCAL INFILE '$tmpfilename'
IGNORE INTO TABLE `ambition`.`session`
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
( $all_columns )";
$conn2->query($load_sql);
Related
So I have this massive headache inducing query that I need to perform involving 65 form inputs needing to be injected into a database using mysqli prepared statements.
The issue I'm running into is that it says the # of variables I am attempting to call bind_param on does not match the # of "s"'s that I am using. I counted a dozen times and do not see where I am going wrong here. There are 65 variables, and 65 "s"'s.
Can anyone see something I'm missing? Or am I perhaps using the bind_param method in an incorrect manner?
// Preparing our query statement via mysqli which will auto-escape all bad characters to prevent injection
$query3 = 'INSERT INTO datashep_AMS.COMPLETE_APPLICATIONS (
project_name,
status,
funding_requested,
project_title,
program,
county,
parish,
name_of_watercourse,
which_is_a_tributary_of,
name_of_applicant,
contact_person_or_project_supervisor,
relationship_to_organization,
business_phone,
home_phone,
email,
signature_of_thesis_or_study_supervisor,
mailing_address,
postal_code,
website,
mailing_address_for_payment,
hst_registration_no,
total_cost_dollar,
total_cost_percent,
dollar_amount_requested_from_nbwtf,
percent_amount_requested_from_nbwtf,
descriptive_summary,
background_of_organization,
mandate,
years_in_existence,
membership,
accomplishments,
previous_project_name,
previous_project_number,
previous_project_amount_received_from_nbwtf,
summary_of_activities,
summary_of_Results,
project_title_2,
reason_and_or_purpose,
objectives,
project_description,
methods,
equipment_and_materials_required,
personnel_required,
proposed_start_date,
proposed_end_date,
type_of_data_to_be_stored,
where_will_it_be_housed,
monitoring,
short_term_achievement,
long_term_achievement,
previous_studies,
required_permits,
consultants,
short_term_commitment,
long_term_commitment,
project_duration,
project_evaluation,
promotion_of_project,
promotion_of_client,
publication_of_results,
community_benefits,
effects_on_traditional_uses,
possible_changes_in_public_access_to_areas,
possible_impact_on_wildlife_and_or_environment,
likelihood_of_future_requests_for_funding,
list_all_other_funding_sources_for_this_project
) VALUES (
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?
)';
// "Preparing" the query using mysqli->prepare(query) -- which is the equivalent of mysql_real_escape_string -- in other words, it's the SAFE database injection method
$stmt = $dbConnection->prepare($query3);
// "Bind_param" == replace all the "?"'s in the aforementioned query with the variables below
$stmt->bind_param("s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s", $project_name, $status, $funding_requested, $project_title, $program, $county, $parish, $name_of_watercourse, $which_is_a_tributary_of, $name_of_applicant, $contact_person_or_project_supervisor, $relationship_to_organization, $business_phone, $home_phone, $email, $signature_of_thesis_or_study_supervisor, $mailing_address, $postal_code, $website, $mailing_address_for_payment, $hst_registration_no, $total_cost_dollar, $total_cost_percent, $dollar_amount_requested_from_nbwtf, $percent_amount_requested_from_nbwtf, $descriptive_summary, $background_of_organization, $mandate, $years_in_existence, $membership, $accomplishments, $previous_project_name, $previous_project_number, $previous_project_amount_received_from_nbwtf, $summary_of_activities, $summary_of_Results, $project_title_2, $reason_and_or_purpose, $objectives, $project_description, $methods, $equipment_and_materials_required, $personnel_required, $proposed_start_date, $proposed_end_date, $type_of_data_to_be_stored, $where_will_it_be_housed, $monitoring, $short_term_commitment, $long_term_achievement, $previous_studies, $required_permits, $consultants, $short_term_commitment, $long_term_commitment, $project_duration, $project_evaluation, $promotion_of_project, $promotion_of_client, $publication_of_results, $community_benefits, $effects_on_traditional_uses, $possible_changes_in_public_access_to_areas, $possible_impact_on_wildlife_and_or_environment, $likelihood_of_future_requests_for_funding, $list_all_other_funding_sources_for_this_project);
// Perform the actual query!
$stmt->execute();
The number of characters in the type definition string must be equal to the number of placeholders (? marks) in the SQL query.
// three ? marks
$stmt->prepare("INSERT INTO table (one, two, three) VALUES (?,?,?)");
$stmt->bind_param("sss", $one, $two, $three);
// three s characters (and three variables as well)
Note that characters in the type definition string should not be separated by commas.
You can see this format demonstrated in the examples on the manual page.
there are 65 string params so if there are 65 s's you have the correct number. However the errors are appearing because you separated the s's by commas. Instead of $stmt->bind_param("s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s..."
it should be
$stmt->bind_param("sssssssssssssssss..."
This should solve your errors.
The character in the bind_param should not be separated by a comma.
If you have to bind two variables do this:
$stmt->bind_param('ss', $firstvariable, $secondvariable);
I've had some assistance in finishing this script which selects from a cloned table on a remote server and inserts the updated records to the identical table on another server. However, when running this in powershell now I get the message: Number of variables doesn't match number of parameters in prepared statement and Number of elements in type definition string doesn't match number of bind variables. I get 59 rows of each error for each row it's attempting to insert, so I know there's something wrong with all 59 elements of bind_param, but that's all I know.
I'm familiar with MYSQL but not so much with php and I"ve had nothing but problems with this. I just want a stable way to read the newest records from the remote server and insert them to the new server. I'm using the max SESSIONID which is an AI Primary Key to see what rows are new on the remote server.
Please help me to bypass these errors
<?php
ini_set('memory_limit', '256M');
// Create connection
$conn = new mysqli($servername, $username, $password);
$conn2 = new mysqli($servername2, $username2, $password2);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Check connection2
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
echo "Connected successfully";
//Start queries
$latest_result = $conn2->query("SELECT MAX(`SESSIONID`) FROM `ambition`.`session`");
$latest_row = $latest_result->fetch_row();
$latest_session_id = $latest_row[0];
//Select All rows from the source phone database
$source_data = mysqli_query($conn, "SELECT * FROM `cdrdb`.`session` WHERE `SESSIONID` > $latest_session_id");
// Loop on the results
while($source = $source_data->fetch_assoc()) {
// Check if row exists in destination phone database
$row_exists = $conn2->query("SELECT SESSIONID FROM ambition.session WHERE SESSIONID = '".$source['SESSIONID']."' ") or die(mysqli_error($conn2));
//if query returns false, rows don't exist with that new ID.
if ($row_exists->num_rows == 0){
//Insert new rows into ambition.session
$stmt = $conn2->prepare("INSERT INTO ambition.session (SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO,DIALPLANNAME,TERMINATIONREASONCODE,ISCLEARINGLEGORIGINATING,CREATIONTIMESTAMP,ALERTINGTIMESTAMP,CONNECTTIMESTAMP,DISCONNECTTIMESTAMP,HOLDTIMESECS,LEGTYPE1,LEGTYPE2,INTERNALPARTYTYPE1,INTERNALPARTYTYPE2,SERVICETYPEID1,SERVICETYPEID2,EXTENSIONID1,EXTENSIONID2,LOCATION1,LOCATION2,TRUNKGROUPNAME1,TRUNKGROUPNAME2,SESSIONIDTRANSFEREDFROM,SESSIONIDTRANSFEREDTO,ISTRANSFERINITIATEDBYLEG1,SERVICEEXTENSION1,SERVICEEXTENSION2,SERVICENAME1,SERVICENAME2,MISSEDUSERID2,ISEMERGENCYCALL,NOTABLECALLID,RESPONSIBLEUSEREXTENSIONID,ORIGINALLYCALLEDPARTYNO,ACCOUNTCODE,ACCOUNTCLIENT,ORIGINATINGLEGID,SYSTEMRESTARTNO,PATTERN,HOLDCOUNT,AUXSESSIONTYPE,DEVICEID1,DEVICEID2,ISLEG1ORIGINATING,ISLEG2ORIGINATING,GLOBALCALLID,CADTEMPLATEID,CADTEMPLATEID2,ts,INITIATOR,ACCOUNTNAME,APPNAME,CALLID,CHRTYPE,CALLERNAME,serviceid1,serviceid2)
VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") or die(mysqli_error($conn2)) ;
$stmt->bind_Param("i,s,s,s,i,i,s,s,s,s,i,i,i,i,i,i,i,i,i,s,s,s,s,i,i,i,s,s,s,s,i,i,i,i,s,s,s,i,i,s,i,i,i,i,i,i,i,i,i,s,i,s,s,s,i,s,i,i"
,$source['SESSIONTYPE']
,$source['CALLINGPARTYNO']
,$source['FINALLYCALLEDPARTYNO']
,$source['DIALPLANNAME']
,$source['TERMINATIONREASONCODE']
,$source['ISCLEARINGLEGORIGINATING']
,$source['CREATIONTIMESTAMP']
,$source['ALERTINGTIMESTAMP']
,$source['CONNECTTIMESTAMP']
,$source['DISCONNECTTIMESTAMP']
,$source['HOLDTIMESECS']
,$source['LEGTYPE1']
,$source['LEGTYPE2']
,$source['INTERNALPARTYTYPE1']
,$source['INTERNALPARTYTYPE2']
,$source['SERVICETYPEID1']
,$source['SERVICETYPEID2']
,$source['EXTENSIONID1']
,$source['EXTENSIONID2']
,$source['LOCATION1']
,$source['LOCATION2']
,$source['TRUNKGROUPNAME1']
,$source['TRUNKGROUPNAME2']
,$source['SESSIONIDTRANSFEREDFROM']
,$source['SESSIONIDTRANSFEREDTO']
,$source['ISTRANSFERINITIATEDBYLEG1']
,$source['SERVICEEXTENSION1']
,$source['SERVICEEXTENSION2']
,$source['SERVICENAME1']
,$source['SERVICENAME2']
,$source['MISSEDUSERID2']
,$source['ISEMERGENCYCALL']
,$source['NOTABLECALLID']
,$source['RESPONSIBLEUSEREXTENSIONID']
,$source['ORIGINALLYCALLEDPARTYNO']
,$source['ACCOUNTCODE']
,$source['ACCOUNTCLIENT']
,$source['ORIGINATINGLEGID']
,$source['SYSTEMRESTARTNO']
,$source['PATTERN']
,$source['HOLDCOUNT']
,$source['AUXSESSIONTYPE']
,$source['DEVICEID1']
,$source['DEVICEID2']
,$source['ISLEG1ORIGINATING']
,$source['ISLEG2ORIGINATING']
,$source['GLOBALCALLID']
,$source['CADTEMPLATEID']
,$source['CADTEMPLATEID2']
,$source['ts']
,$source['INITIATOR']
,$source['ACCOUNTNAME']
,$source['APPNAME']
,$source['CALLID']
,$source['CHRTYPE']
,$source['CALLERNAME']
,$source['serviceid1']
,$source['serviceid2']);
$stmt->execute();
}
}
?>
Your table is on AI auto-increment you dont need to add your PRIMARY KEY COLUMN in your INSERT STATEMENT
$stmt = $conn2->prepare("INSERT INTO ambition.session (SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO,DIALPLANNAME,TERMINATIONREASONCODE,ISCLEARINGLEGORIGINATING,CREATIONTIMESTAMP,ALERTINGTIMESTAMP,CONNECTTIMESTAMP,DISCONNECTTIMESTAMP,HOLDTIMESECS,LEGTYPE1,LEGTYPE2,INTERNALPARTYTYPE1,INTERNALPARTYTYPE2,SERVICETYPEID1,SERVICETYPEID2,EXTENSIONID1,EXTENSIONID2,LOCATION1,LOCATION2,TRUNKGROUPNAME1,TRUNKGROUPNAME2,SESSIONIDTRANSFEREDFROM,SESSIONIDTRANSFEREDTO,ISTRANSFERINITIATEDBYLEG1,SERVICEEXTENSION1,SERVICEEXTENSION2,SERVICENAME1,SERVICENAME2,MISSEDUSERID2,ISEMERGENCYCALL,NOTABLECALLID,RESPONSIBLEUSEREXTENSIONID,ORIGINALLYCALLEDPARTYNO,ACCOUNTCODE,ACCOUNTCLIENT,ORIGINATINGLEGID,SYSTEMRESTARTNO,PATTERN,HOLDCOUNT,AUXSESSIONTYPE,DEVICEID1,DEVICEID2,ISLEG1ORIGINATING,ISLEG2ORIGINATING,GLOBALCALLID,CADTEMPLATEID,CADTEMPLATEID2,ts,INITIATOR,ACCOUNTNAME,APPNAME,CALLID,CHRTYPE,CALLERNAME,serviceid1,serviceid2)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") or die(mysqli_error($conn2)) ;
need the change your bin_param
//example here i guess **SESSIONTYPE COLUMN IS INTEGER**
$sth->bindParam(':SESSIONTYPE', $source['SESSIONTYPE'], PDO::PARAM_INT);
I am trying to insert two rows at once using mysqli:bind::param on that few data has to repeat in two rows on mysql and few data has to change according to the array of the name[]. But the problem which i am facing only the array with index 0 is inserting in the mysql though in print_r($sql) is displaying two times true here is my function of inserting the data:
function insertSellingItem($customer_details,$po_no,$new_customer,$date,$address,$offer_no,$gstin,$dispatched,$invoice_no,$state,$invoice_date,$code,$challan_no,$remarks,$challan_date,&$serial_no,&$mat_des,&$pl_serial_no,&$hsn_code,&$unit,&$purchase_rate,&$tax_amount,&$total_cost,&$rate,&$quantity,&$item_value,&$discount,&$sgst,&$cgst,&$igst,&$amount,$pay_cost){
global $mysqli;
$stmt = $mysqli->prepare("INSERT INTO sellItems(
customer_details,
po_no,
new_customer,
date,
address,
offer_no,
gstin,
dispatched,
invoice_no,
state,
invoice_date,
code,
challan_no,
remarks,
challan_date,
serial_no,
mat_des,
pl_serial_no,
hsn_code,
unit,
purchase_rate,
tax_amount,
total_cost,
rate,
quantity,
item_value,
discount,
sgst,
cgst,
igst,
amount,
pay_cost
)
VALUES(
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?
)");
$stmt->bind_param("ssssssssssssssssssssssssssssssss",$customer_details,$po_no,$new_customer,$date,$address,$offer_no,$gstin,$dispatched,$invoice_no,$state,$invoice_date,$code,$challan_no,$remarks,$challan_date,$serial_no,$mat_des,$pl_serial_no,$hsn_code,$unit,$purchase_rate,$tax_amount,$total_cost,$rate,$quantity,$item_value,$discount,$sgst,$cgst,$igst,$amount,$pay_cost);
$stmt->execute();
$inserted_id = $mysqli->insert_id;
$stmt->close();
if($inserted_id>0)
{
return true;
}
else
{
return false;
}}
And the loop how i am sending the data in the in this function :
if(!empty($mat_des)){
for($i = 0; $i<count($mat_des); $i++) {
$sql = insertSellingItem($customer_details,$po_no,$new_customer,$date,$address,$offer_no,$gstin,$dispatched,$invoice_no,$state,$invoice_date,$code,$challan_no,$remarks,$challan_date,$serial_no[$i],$mat_des[$i],$pl_serial_no[$i],$hsn_code[$i],$unit[$i],$purchase_rate[$i],$tax_amount[$i],$total_cost[$i],$rate[$i],$quantity[$i],$item_value[$i],$discount[$i],$sgst[$i],$cgst[$i],$igst[$i],$amount[$i],$pay_cost);
print_r($sql);
}}
Where print_r(($mat_des)); is displaying count no 2 as i am passing the two rows in the name = mat_des[];
Any advice will be highly appreciated!
new here
I've come across this problem.
It doesn't seem to be able to use my id's from the two first statements in my last statements as a variable resource, so the sqlcharacter statement fails.
What do i do wrong?
$sqlimg = ("INSERT INTO cimages(image) VALUES(?)");
$stmtimg = $conn->prepare($sqlimg);
$stmtimg->bind_param('s', $image);
$stmtimg->execute();
$img_id = $stmtimg->insert_id;
// I insert the picture first, and retrieve it's ID
$sqlstats = ("INSERT INTO cstats(Strength, Dexterity, Constitution,
Intelligence, Wisdom, Charisma, Aligment) VALUES(?, ?, ?, ?, ?, ?, ?)");
$stmtstats = $conn->prepare($sqlstats);
$stmtstats->bind_param("iiiiiis", $strength, $dexterity, $constitution,
$intelligence, $wisdom, $charisma, $aligment);
$stmtstats->execute();
$stats_id = $stmtstats->insert_id;
// I insert the characters stats, and retrieve it's ID
// Last I insert The user_id and img_id and stats_id
$user_id = mysqli_real_escape_string($conn, $_POST['user_id']);
// I've used the session id to get the user_id already
$sqlcharacter = ("INSERT INTO characters(Cname, Clast, Crace, house,
location, Bgstory, user_id, img_id, stats_id) VALUES(?, ?, ?, ?, ?, ?, ?,
$img_id, $stats_id)");
$stmtChar = $conn->prepare($sqlcharacter);
$stmtChar->bind_param('ssssssiii', $Cname, $Clast, $Crace, $house,
$location, $Bgstory, $user_id, $img_id, $stats_id);
$stmtChar->execute();
The $sqlcharacter string looks like you've got two variables $img_id and $stats_id in there instead of ?, so I think that's why it's not binding those values.
Try changing this:
"INSERT INTO characters(Cname, Clast, Crace, house,
location, Bgstory, user_id, img_id, stats_id) VALUES(?, ?, ?, ?, ?, ?, ?,
$img_id, $stats_id)"
To this:
"INSERT INTO characters(Cname, Clast, Crace, house,
location, Bgstory, user_id, img_id, stats_id) VALUES(?, ?, ?, ?, ?, ?, ?,
?, ?)"
I have a function that is supposed to store the array to my mysql table yet nothing is showing up in my database. This is my first time using Mysqli as I used to use Mysql.
The function is passed a $uniqueRef ID that is saved into the Database, The work order array, $coreSales which is another array that gets saved in the Database and $mysqli which passes the MYSQLI connection.
This is My Code :
function storeInDB($uniqueRef, $wo, $coreSales, $mysqli){
$accountStatus = 0;
$requiresAttention = 2;
$stmt = $mysqli->prepare("INSERT INTO `workorder`(`id`, `uniqueRef`, `rep`, `repemail`, `date`, `event`, `otherNotes`, `repNotes`, `bookingNotes`, `reqInstallDate`, `tripplePlayPromo`, `fullName`, `address`, `contactNumber`, `accountNumber`, `custID`, `custEmail`, `cblPackage`, `cblNotes`, `cblEquipment`, `cblPromo`, `internetPackage`, `internetNotes`, `internetEquipment`, `internetPromo`, `phonePackage`, `phonePromo`, `portingNumber`, `phoneBook`, `portornew`, `cellorlandline`, `companyPortingfrom`, `servicesToDisco`, `alarm`, `intercom`, `nameOnBill`, `cellAccount`, `fromAddress`, `phoneNotes`, `creditName`, `creditContactNumber`, `creditAddress`, `creditAccount`, `status`, `requiresattention`, `creditAmount`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('issssssssssssssssssssssssssssssssssssssssssiii',
$idNum,
$uniqueRef,
$wo['rep'],
$wo['repemail'],
$wo['date'],
$wo['event'],
$wo['otherNotes'],
$wo['repNotes'],
$wo['bookingNotes'],
$wo['reqInstallDate'],
$wo['tripplePlayPromo'],
$wo['fullName'],
$wo['address'],
$wo['contactNumber'],
$wo['accountNumber'],
$wo['custID'],
$wo['custEmail'],
$wo['cblPackage'],
$wo['cblNotes'],
$wo['cblEquipment'],
$wo['cblPromo'],
$wo['internetPackage'],
$wo['internetNotes'],
$wo['internetEquipment'],
$wo['internetPromo'],
$wo['phonePackage'],
$wo['phonePromo'],
$wo['portingNumber'],
$wo['phoneBook'],
$wo['portornew'],
$wo['cellorlandline'],
$wo['companyPortingfrom'],
$wo['servicesToDisco'],
$wo['alarm'],
$wo['intercom'],
$wo['nameOnBill'],
$wo['cellAccount'],
$wo['fromAddress'],
$wo['phoneNotes'],
$wo['creditName'],
$wo['creditContactNumber'],
$wo['creditAddress'],
$wo['creditAccount'],
$accountStatus,//Status
$requiresAttention,
$creditAmount);//Requires Attention
echo $mysqli->error;
$stmt->execute();
$idNum = $mysqli->insert_id;
$stmt->close();
echo "<br>Stored in DB ID#" .$idNum ;
return $idNum;
}
Thanks