Related
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 was always using normal querys for inserting data into the database but now I want to make it with prepared statements. I'm already using statements to select data in all my files but insert never worked... And now I ran out of ideas again. Maybe someone can see what I did wrong.
$animeId = $_POST['animeId'];
$username = $_POST['username'];
$rating = $_POST['rating'];
$story = $_POST['story'];
$genre = $_POST['genre'];
$animation = $_POST['animation'];
$characters = $_POST['characters'];
$music = $_POST['music'];
//Datum auslesen
$date = date("Y-m-d H:i:s");
if($insertRating = $con->prepare("INSERT INTO anime_rating (animeId, rating, story, genre, animation, characters, music, user, date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?"))
{
$insertRating->bind_param("iiiiiiiss", $animeId, $rating, $story, $genre, $animation, $characters, $music, $username, $date);
$insertRating->execute();
$insertRating->close();
}
You have an errant comma in your query:
music, user,) VALUES (?, ?, ?, ?, ?, ?, ?
^^^
HERE
It should be
music, user) VALUES (?, ?, ?, ?, ?, ?, ?
In the statement:
INSERT INTO anime_rating (
animeId,
rating,
story,
genre,
animation,
characters,
music,
user /* 8 columns */)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?") /* 10 parameters */
There are 8 columns listed to insert values into and 10 parameters specified in the values section. Also as pointed out there is the extra comma in the list of values.
The number of columns must match the number of parameters and the number of parameters binding in the following statement:
`$insertRating->bind_param("iiiiiiiss", $animeId, $rating, $story, $genre, $animation, $characters, $music, $username, $date);`
Two errors in the statement:
INSERT INTO anime_rating (animeId, rating, story, genre, animation, characters, music, user,) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?"
^ here and ^ ^
remove the comma
add a closing parentheses before the end of the string.
remove one ,?
Furthermore you should chop one is from the binding:
$insertRating->bind_param("iiiiiiss", $animeId, $rating, $story, $genre, $animation, $characters, $music, $username, $date);
if($insertRating = $con->prepare("INSERT INTO anime_rating (animeId, rating, story, genre, animation, characters, music, user, date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?"))
The last (") should be placed after the first ) at the end
New code:
if($insertRating = $con->prepare("INSERT INTO anime_rating (animeId, rating, story, genre, animation, characters, music, user, date) 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