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);
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 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);
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 (?, ?, ?, ?, ?, ?, ?, ?, ?)")