• 0

Need help inserting into MySQL database table using PDO.


Question

Here's the code:


<?php
class DB {
private $_conn;

public function openDB() {
$dsn = "mysql:host=localhost;dbname=news";
$username = "root";
$password = "password";

try {
$this->_conn = new PDO( $dsn, $username, $password );
$this->_conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
echo "Connection failed: " . $e->getMessage();
}
}

public function closeDB() {
$this->_conn = null;
}

public function selectData( $myQuery ) {
$rows = $this->_conn->query( $myQuery );

foreach ( $rows as $row ) {
echo "Index: " . $row['id'] . "<br />";
echo "Title: " . $row['title'] . "<br />";
}
}

public function insertData( $tableName ) {

$q = $this->_conn->prepare("DESCRIBE " . $tableName);
$q->execute();
$getFields = $q->fetchAll(PDO::FETCH_COLUMN);

$dbFieldCount = count( $getFields );
$implodedFields = implode( ", :", $getFields );

//$sql = "INSERT INTO " . $tableName . " ( " . implode( ", ", $getFields ) . " ) VALUES ( :" . $implodedFields . " )";
$sql = "INSERT INTO " . $tableName . " VALUES ( :" . $implodedFields . " )";
echo "$sql<br />";

try {
$insert = $this->_conn->prepare( $sql );

foreach ( $getFields as $dbKey => $dbValue ) {
foreach( $_POST as $formKey => $formValue ) {
if ( $dbValue == 'id' ) {
$insert->bindValue( '\":' . $dbValue . '\"', null, PDO::PARAM_INT );
echo "$dbValue<br />";
break;
} else if ( is_int( $formValue ) && $dbValue == $formKey ) {
$insert->bindValue( '\":' . $dbValue . '\"', $formValue, PDO::PARAM_INT );
echo "$formValue<br />";
break;
} else if ( is_string( $formValue ) && $dbValue == $formKey ) {
$insert->bindValue( '\":' . $dbValue . '\"', $formValue, PDO::PARAM_STR );
echo "$formValue<br />";
break;
}
}
}

$insert->execute();
} catch ( PDOException $e ) {
echo "Query failed: " . $e->getMessage();
}
}

}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php

if ($_POST) {
$conn = new DB();
$conn->openDB();
$conn->insertData( 'login' );
$conn->closeDB();
}

?>

<form action="#" method="POST" name="register">
<label for="username">Username</label><br />
<input type="text" id="username" name="username"><br />
<label for="password">Password</label><br />
<input type="password" id="password" name="password"><br />
<label for="email">Email Address</label><br />
<input type="text" id="email" name="email"><br />
<input type="submit" value="Submit" />
</form>

</body>
</html>
[/CODE]

The database table only contains the four fields that the query is attempting to insert into. For some reason I get the error: Query failed: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined.

I have troubleshot by echoing the output of the foreach loops and it always returns four items, I'm not sure what parameter isn't defined. I have also played around with including the field names in the $sql string as well as not including them. Same results either way. Please help if you can.

5 answers to this question

Recommended Posts

  • 0

You shouldn't be wrapping the bindValue column names in quotes (that's why it isn't finding any of the parameters), e.g. change:

$insert->bindValue( '\":' . $dbValue . '\"', $formValue, PDO::PARAM_STR );[/CODE]

to

[CODE]$insert->bindValue( ":$dbValue", $formValue, PDO::PARAM_STR );[/CODE]

Same with all the other bindValue calls. You don't actually even need the ":" in newer versions but it's probably better to keep it in for compatibility reasons.

--------

Two extra notes about the code,[i] all[/i] posted values are strings in PHP, so your [b]is_int[/b] conditional will never be true, and you don't need the second loop, just check if [b]array_key_exists([/b][b]$dbValue, $_POST)[/b] then access the key directly. Also, be careful if you're going to use a function like that in production across a lot of forms so you don't accidently open yourself up to a mass assignment vulnerability :p.

  • 0

Thanks for you help, that worked beautifully. My goal with this function is to kind of make it a universal INSERT function that can be reused for any insert call. I'll have to do some research on avoiding a mass assignment vulnerability now though. Thanks so much for your help :-)

This topic is now closed to further replies.
  • Posts

    • SQL Server Management Studio 22.7 brings "What's New" page, T-SQL formatting, and lots more by Usama Jawad SQL Server Management Studio (SSMS) is the tool of choice for most developers working with SQL infrastructure and data. Microsoft recently released SSMS version 22, and in the past few months, it has been steadily releasing point upgrades to refine the integrated development environment (IDE). Now, it has released SSMS version 22.7.0 with a bunch of new features and interfaces. For starters, SSMS 22.7 has netted a native "What's New" page, which highlights the top features and bug fixes present in the latest release. However, Microsoft says that this page won't annoy you much as it will only show up each time you update SSMS, and once you dismiss it, it won't be shown again to you until the next release. Secondly, Microsoft has finally introduced T-SQL formatting inside SSMS. The good thing about this is that it does not require installing any additional components, as it is built into the native experience. All you have to do is right-click the query editor window and select Format SQL from the context menu. Additionally, you also have several customization options at your disposal, such as the ability to automatically place semicolons at the end of a statement, split clauses across multiple lines, and more. However, this capability is only in preview for now. Additionally, Microsoft has introduced a preview of Agent Mode, which allows the AI model to automatically perform complex workflows on your behalf. Furthermore, Agent Mode will operate in read-only mode by default, so that you don't have to worry about the AI model accidentally deleting your data. On a related note, Microsoft is finally allowing users to configure the execution context of GitHub Copilot. This can be controlled per database using the CONSTITUTION.md file, where you specify the user details for the agentic executor. You can find details about this and additional bugfixes in Microsoft's blog post here.
    • I only use 3 extensions in Zen. I don't need or want a ton of stuff in my browser i don't use.
    • I prefer to choose my own ad bockers, not what the browser seems to think I need. i remember the days when a browser was just that, now they try and be everything and add stuff in that not all of us want. I bet Brave is full of AI rubbish? I will stick with Zen, not perfect, but better than others.
    • PDF-XChange Editor 11.0.1.0 by Razvan Serea PDF-XChange Editor is a comprehensive PDF editor that allows you to create, view, edit, annotate, and digitally sign PDF documents with ease. With advanced features like OCR, document security, and PDF optimization, PDF-XChange Editor is a powerful tool for both personal and professional use. Whether you need to edit text, images, or links, or add comments, stamps, or watermarks, PDF-XChange Editor provides all the necessary tools to make your PDFs look perfect. Additionally, it supports a wide range of file formats, including PDF, XPS, and DOCX, making it easy to convert and share your documents. PDF-XChange Editor key features: Edit text and images in PDF documents Add and remove pages from PDF files Annotate and markup PDFs with comments, highlights, and stamps Use OCR to convert scanned documents into searchable text Create and fill out PDF forms Sign and certify PDF documents digitally Add and edit hyperlinks within PDFs Extract text and images from PDF files Batch process multiple PDF files at once Customize the interface to your preferences Work with multiple documents in tabs Convert PDFs to other formats such as Word, Excel, and HTML Use advanced redaction tools to permanently remove sensitive information Add customizable headers and footers to PDFs Merge multiple PDF documents into a single file Split PDF documents into multiple files Add watermarks to PDF documents Use the measurement tools to calculate distances and areas in PDFs ....and much more PDF-XChange Editor 11.0.1.0 changelog: Fixed a crash in the new Open/Save dialog box when creating a new folder in an unavailable network path. (49552) Fixed a rare/infrequent crash on some dynamic XFA forms after changing their field values. [installer] Fixed an issue where shortcuts were lost during an upgrade from the previous version. [installer] Fixed an issue preventing migration of serial keys during updates from version 10. Fixed the issues with the shell context menu after installation of version 11. Fixed the issue with filtering comments. (49478) Fixed the issue that caused "Error [IO subsystem]: Invalid access mode." when converting PDFs to MS Office formats. Fixed an issue with the context menu position on some multi-monitor systems. (48467) Fixed an issue with handling complex custom file filters, displayed by JS, in the new Open/Save Files dialog box. (49486) Fixed several issues with the new 'Select Folder' dialog box. (49505) Fixed an issue with the new custom 'Open File' dialog box when using double-click to open it. (49498) Fixed an 'infinite' loop/proliferation in the 'Open Files' and 'Manage Places' dialog boxes. (49526) Fixed an issue with handling the mouse wheel inside the document "Find" box. (49539) Fixed an incorrect behaviour in the 'Go back (Alt+Left)' button in the new Open/Save Files dialog box. (49510) Fixed an issue with the shortcut keys (Alt+Left/Right) after navigating via breadcrumb paths in the new Open/Save Files dialog box. (49554) [installer] Fixed an issue with redrawing the progress text in the EXE installers. Fixed the issue where a mouse click outside of the polyline/polygon context menu during annotation creation would cancel the annotation. (49475) We switched back to using the system Open/Save/SelectFolder dialog box by default, instead of using the new one, because some popular features such as the QuickAccess/Recent items are missing in the new version. These will be added in a future release. Replaced the 'Extension' column in the new Open/Save File dialog box with a more user-friendly 'Type' column. Also fixed some issues when handling the 'Show file extension' option. (49497) Added the ability to authenticate local network shares in the new Open/Save Files dialog box. (49557) Improved the handling of dates after 01.01.2030 in XFA files - now such dates are stored properly when set via the dropdown widget. Flags NoZoom and NoRotate are now respected for only a limited subset of annotations. Download: PDF-XChange Editor (64-bit) | Portable ~300.0 MB (Shareware) Download: PDF-XChange Editor (32-bit) | Portable ~200.0 MB Download: PDF-XChange ARM64 | 276.0 MB Download: PDF-XChange Portable @PortableApps.com | 97.0 MB View: PDF-XChange Editor Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • One Month Later
      johnjacobb40 earned a badge
      One Month Later
    • One Year In
      Primer1st earned a badge
      One Year In
    • Experienced
      JayZJay went up a rank
      Experienced
    • Reacting Well
      Sir_Timbit earned a badge
      Reacting Well
    • Week One Done
      rubentuben8 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      513
    2. 2
      PsYcHoKiLLa
      231
    3. 3
      +Edouard
      144
    4. 4
      ATLien_0
      86
    5. 5
      Steven P.
      82
  • Tell a friend

    Love Neowin? Tell a friend!