PDO multi-record insert trouble - pdo
I am trying to do a multi-record insert statement using PDO with a MySQL database. After searching and working through some errors..I am at a point where I am stuck and need help.
inserting into 11-columns...and I believe there are 189 records to insert.
I have checked my ?'s array to ensure there are '11' ?'s in each () set.....and that there are 189 (?,?,?,?,?,?,?,?,?,?,?), sets in my 'value array' I pass in. So I think the problem lies with the 'data array' (and not the 'place holder' array). (if that makes any sense)
Example of query echo'd out:
QUERY: INSERT INTO fontEntries(date_entered, font_name, font_maker, font_format, optimized_for, font_price, font_image, font_url, description, youtube_id, ip_address) VALUES (?,?,?,?,?,?,?,?,?,?,?), (?,?,?,?,?,?,?,?,?,?,?), ......n
all 189 'sets' are there.
right now I'm stuck at an invalid parameter number error
my code:
<?php
$conn=new PDO("mysql:host=localhost; dbname=test;","root","");
//$conn->exec("SET CHARACTER SET utf8");
// displays all the file nodes
if(!$xml=simplexml_load_file('saberEntries.xml')){
trigger_error('Error reading XML file', E_USER_ERROR);
}
//print_r($xml);
$totalCount = 0;
$ip_address = $_SERVER["REMOTE_ADDR"];
$detailArray = array();
foreach($xml->entry as $fontEntry){
global $totalCount;
$details = array($fontEntry->fontName, $fontEntry->attributes()->submissionDate, $fontEntry->fontCreator. $fontEntry->fontFormat,$fontEntry->optimized,$fontEntry->fontPrice,$fontEntry->fontImage,$fontEntry->fontURL,$fontEntry->demoLink,$fontEntry->description,$ip_address);
//$detailArray[] = $details;
foreach($details as $item){
$detailArray[] = $item;
}
$totalCount++;
//echo ($totalCount + 1 '.) Array Check: '.$details[0] ."<br>");
}
echo "Total Entries in XML: $totalCount <br>";
echo "Total Array Length: ". count($detailArray) ."<br>";
//echo 'Array Check: '.$detailArray[0] ."<br>";
$qMarks = str_repeat('(?,?,?,?,?,?,?,?,?,?,?), ', count($detailArray)-1) . '(?,?,?,?,?,?,?,?,?,?,?)';
//echo 'Q-MARKS: '.$qMarks . '<br>';
//var_dump($detailArray) ."<br>";
$myQuery = "INSERT INTO fontEntries(date_entered, font_name, font_maker, font_format, optimized_for, font_price, font_image, font_url, description, youtube_id, ip_address) VALUES $qMarks";
$import_statement = $conn->prepare($myQuery);
$import_statement->execute($detailArray);
//check is insert was successful
if ($import_statement->execute()) {
//true
echo 'INSERT SUCCESSFUL';
}else{
//false
echo 'INSERT FAILED <br>';
$errorcode = $import_statement->errorCode();
echo 'ERROR CODE: '.$errorcode .'<br>';
$error = $import_statement->errorInfo();
echo 'ERROR CODE 2: '.$error .'<br>';
}
?>
error:
Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:\wamp\www\xml_tests\simpleXML_test.php on line 79
Line 79:
$import_statement->execute($detailArray);
Anybody point where my error is? Thanks.
working code: (thanks to Your common sense's advice/help)
<?php
$conn=new PDO("mysql:host=localhost; dbname=test;","root","");
//$conn->exec("SET CHARACTER SET utf8");
// displays all the file nodes
if(!$xml=simplexml_load_file('target_xml.xml')){
trigger_error('Error reading XML file', E_USER_ERROR);
}
$totalCount = 0;
$ip_address = $_SERVER["REMOTE_ADDR"];
foreach($xml->entry as $fontEntry){
$details = array($fontEntry->attributes()->submissionDate, $fontEntry->fontName, $fontEntry->fontCreator, $fontEntry->fontFormat, $fontEntry->optimized, $fontEntry->fontPrice, $fontEntry->fontImage, $fontEntry->fontURL, $fontEntry->description, $fontEntry->demoLink, $ip_address);
//dump/parse into one big/long (1-dimensional) array to pass to PDO
foreach($details as $item){
$detailArray[] = $item;
}
$totalCount++;
echo ('Entry#: '.$totalCount.'<br/>');
}
echo "Total Entries in XML: $totalCount <br>";
echo "Total Array Length: ". count($detailArray) ."<br><br>";
$qMarks = str_repeat('(?,?,?,?,?,?,?,?,?,?,?), ', $totalCount-1 ). '(?,?,?,?,?,?,?,?,?,?,?)';
//echo 'Q-MARKS: <br>'.$qMarks . '<br>';
//print_r($detailArray) ."<br>";
//var_dump($detailArray) ."<br>";
$myQuery = "INSERT INTO fontEntries(date_entered, font_name, font_maker, font_format, optimized_for, font_price, font_image, font_url, description, youtube_id, ip_address) VALUES $qMarks";
$import_statement = $conn->prepare($myQuery);
$import_statement->execute($detailArray);
//check is insert was successful
if ($import_statement->execute()) {
//true
echo 'INSERT SUCCESSFUL';
}else{
//false
echo 'INSERT FAILED <br>';
$errorcode = $import_statement->errorCode();
echo 'ERROR CODE: '.$errorcode .'<br>';
$error = $import_statement->errorInfo();
echo 'ERROR CODE 2: '.$error .'<br>';
}
?>
instead of $detailArray[] = $details; make it
foreach ($details as $item) $detailArray[] = $item;
Related
I am stuck, mysqli_query() expects at least 2 parameters
I have a problem with a code in php it shows me this as errors. register mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\search_engine\insert.php on line 99 And this is the code : <?php $db = new PDO('mysql:host=localhost;dbname=srgn;charset=utf8mb4', 'root', '123456'); if(isset($_POST["submit"])) { $s_link = $_POST["s_link"]; $s_key = $_POST["s_key"]; $s_des = $_POST["s_des"]; { $sql = "insert(site_link, site_key, site_des) values('$s_link', '$s_key', '$s_des')"; $rs = mysqli_query($sql); if($rs) { echo "<script> alert('Site uploaded successfully') </script>"; } else { echo "<script> alert('Uploading failed, please try agin.') </script>"; } } } ?> Where is the error please, and how can I set it?
Pass on the connection link as the first parameter and the SQL query as the second parameter. This is required as you are doing procedural code. Refer to the link below for more details http://php.net/manual/en/mysqli.query.php
How to conditionally send email alert in perl
I have a perl script which is printing the table content from Oracle DB in HTML format. My script will run on a daily basis , which will just email the o/p of the simple sql query (select query) Now i want my script to stop email alert whenever record count of the table is NULL i.e no records in the table. Here is my partial script $retCode = executeSQL("select firstname,lastname,employee_id from employee"); if ($retCode) { push(#HTML, "<tr><td> </td><td></td><td>"); push(#HTML, "<td></td><td></td></tr>\12"); } push(#HTML, "</table>\12\12"); push(#HTML, "COUNT : $count\12"); &sendMail; sub sendMail { $sub = "sample data"; $from = 'xyz#abc.com'; $to = 'xys#abc.com'; open(MAIL, "|/usr/lib/sendmail -t"); print MAIL "From: $from \12"; print MAIL "To: $to \12";print MAIL "Cc: $Cc \12"; print MAIL "Subject: $sub \12"; print MAIL "Content-Type: text/html \12"; print MAIL "Content-Disposition:inline \12"; print MAIL #HTML; close(MAIL); } sub executeSQL { my $SQL = $_[0]; chomp($SQL); print "$SQL\12"; my $hostname = $ENV{"ORACLE_DB"}; my $dbh = CommonFunctions::connect_DBI( $hostname, "USERNAME", "PASSWORD" )|| die "ERROR : Unable to connect to $hostname: $DBI::errstr\n\n"; my $sth = $dbh->prepare($SQL); $sth->execute or die "EXEC ERROR $sth->errstr"; $count = 0; while (#ary = $sth->fetchrow_array) { $count++; push(#HTML, "<tr>"); foreach(#ary) { chomp($_); push(#HTML, "<td>$_</td>"); print "$_,"; } push(#HTML, "</tr>\12"); } }
The solution is already there in the code. The program doesn't add table rows to the HTML body of the email if there are no rows returned from the DB query. Hence, you neeed to move the send command into that condition. if($retCode) { push(#HTML,"<tr><td> </td><td></td><td>"); push(#HTML,"<td></td><td></td></tr>\12"); push(#HTML,"</table>\12\12"); push(#HTML, "COUNT : $count\12"); &sendMail; }
I think the big miss here is at the end of executeSQL where you failed to have a return clause indicating whether or not you found any rows in the query. if (executeSQL("select firstname,lastname,employee_id from employee")) { push(#HTML, "<tr><td> </td><td></td><td>"); push(#HTML, "<td></td><td></td></tr>\12"); push(#HTML, "</table>\12\12"); push(#HTML, "COUNT : $count\12"); &sendMail; } sub sendMail { # no changes } sub executeSQL { my $SQL = shift; print "$SQL\12"; my $hostname = $ENV{"ORACLE_DB"}; my $dbh = CommonFunctions::connect_DBI( $hostname, "USERNAME", "PASSWORD" ) || die "ERROR : Unable to connect to $hostname: $DBI::errstr\n\n"; my $sth = $dbh->prepare($SQL); $sth->execute or die "EXEC ERROR $sth->errstr"; my $count = 0; while (#ary = $sth->fetchrow_array) { # no changes } $sth->finish; $dbh->disconnect; return $count; # this is what I think you're missing } That said, there is some other room for improvement, some of which has already been mentioned: Consider passing a reference to #HTML instead of using it as a global -- loose coupling Probably should close out your SQL -- I added the $sth->finish and $dbh->disconnect as examples Have you looked into HTML::Table? I use it a lot, and it's a real time-saver. Creating HTML on the fly is always a last resort for me
PDO LastInsertId returning nothing
For some reason I cannot get the LastInsertId from my PDO insert. I am receiving nothing back, if I place it inside the execute I get -1 because the insert query hasn't run. However when just after the execute to grab the last ID inserted nothing is returned. php 5.1.6 PECL pdo = 0.1.0 I have looked at following questions and many other stack exchange questions. lastInsertId does not work in Postgresql PDO lastInsertId() returns 0 PDO lastInsertId issues, php However the difference is nothing is returned compared to 0. No errors are recorded either. See the code below. Connection try { $conn = new PDO("pgsql:host=localhost port= dbname=", "", ""); echo "PDO connection object created"; } catch(PDOException $e) { echo $e->getMessage(); } insert / return the last id $stmt = $conn ->prepare("INSERT INTO sheet_tbl (site_id, username, additionalvolunteers) VALUES(?,?,?)"); $stmt->bindParam(1,$site_id); $stmt->bindParam(2,$username1); $stmt->bindParam(3,$additionalvolunteers); $site_id = $_POST['site_id']; $username1 = $user->name; $additionalvolunteers = $_POST['additionalvolunteers']; $stmt ->execute(); $newsheetID = $conn->lastInsertId('sheet_id'); echo $newsheetID . "last id";
You should be using $newsheetID = $conn->lastInsertId('sheet_id_**seq**'); Just add _seq after id.
Assumming sheet_id type is SERIAL you can use LASTVAL() TRY (Not tested as I dont have postgresql) $newsheetID = $conn->query("SELECT LASTVAL()"); echo $newsheetID . "last id";
I use postgresql in C# with the "RETURNING rowkey" and its has always worked for me. I also use pdo/php in a lot of applications. However i dont have a postgres database open to the server right now for testing. This could should work but it is not tested. $site_id = $_POST['site_id']; $username1 = $user->name; $additionalvolunteers = $_POST['additionalvolunteers']; $stmt = $conn ->prepare("INSERT INTO sheet_tbl (site_id, username, additionalvolunteers) VALUES(:site_id, :username1, :additionalvolunteers) RETURNING row_id"); $success = $stmt->execute([ 'site_id' => $site_id, 'username1' => $username1, 'additionalvolunteers' => $additionalvolunteers ]); // unsure about this $newsheetID = $stmt->fetchColumn(); echo $newsheetID . " last id";
PHP 5 display mysql table error - Call to undefined function mysql_results()
I premise I'm new to php. I've tried to create a php page that displays the content of a MySQL database. As I try it in localhost I have this warning: "Fatal error: Call to undefined function mysql_results() in C:\xampp\htdocs\phplessons\guestbook_displayer_2.php on line 18". It seems the db connection works. Someone have a tip? This is my code: <html> <head></head> <title>Display MySQL db</title> <body> <?php $db=mysql_connect("localhost","root","mypassword"); //db connection mysql_select_db ("prova001"); //choose a db $res=mysql_query("SELECT * from php_guestbook"); //query a table $num=mysql_num_rows($res); // begin table echo "<table border=1>"; echo "<tr><td>Nr.</td><td>First name</td>"; echo"<td>Last name</td><td>Country</td>"; echo"<td>E-Mail address</td><td>Telephone</td></tr>"; // contatore for ($i=0; $i<$num; $i++) { $cg=mysql_results($res,$i,"firstname"); // line 18 this var is undefined. $nm=mysql_results($res,$i,"lastname"); //Probably also the others have a similar problem. $np=mysql_results($res,$i,"country"); //Can it be due to a bad record counter? $st=mysql_results($res,$i,"email"); $tl=mysql_results($res,$i,"telephone"); $lf=$i+1; // echo "<tr><td>$lf</td><td>$cg</td><td>$nm</td><td>$np</td><td>$st</td><td>$tl</td></tr>"; } echo "</table>"; mysql_close($db); ?> </body>
You have probably made a typo. The method is mysql_result() without 's'. But, you can shorten your query result handling by this way ; // query $res=mysql_query("SELECT * from php_guestbook"); //query a table // begin table echo "<table border=1>"; echo "<tr><td>Nr.</td><td>First name</td>"; echo"<td>Last name</td><td>Country</td>"; echo"<td>E-Mail address</td><td>Telephone</td></tr>"; while ($item = #mysql_fetch_assoc($res)) { // do something with var $item; $cg = $item['firstname']; $nm = $item['lastname']; // ect }
How to do mysql_fetch_array in Magento
I want to create a drop down option using Magento module that populate the data from the database I created. Previously, I have this code in My IndexController.php which is work. This is the first code. public function dropdownAction() { if (file_exists('./app/etc/local.xml')) { $xml = simplexml_load_file('./app/etc/local.xml'); $tblprefix = $xml->global->resources->db->table_prefix; $dbhost = $xml->global->resources->default_setup->connection->host; $dbuser = $xml->global->resources->default_setup->connection->username; $dbpass = $xml->global->resources->default_setup->connection->password; $dbname = $xml->global->resources->default_setup->connection->dbname; } else { exit('Failed to open ./app/etc/local.xml'); } $link = mysql_connect($dbhost,$dbuser,$dbpass); mysql_select_db($dbname) or die("Unable to select database"); $tblname = $tblprefix.'my_db_table'; $result = mysql_query("SELECT dropdowndata FROM ".$tblname.""); echo '<select>'; while ($ary = mysql_fetch_array($result)){ echo "<option>" . $ary['dropdowndata '] . "</option>"; } echo "</select>"; mysql_close($link); } But I think the code above is not the Magento way. Do you agree? Now, I want to populate the data with this code in IndexController.php. This is the second code. public function dropdownAction() { $options= Mage::getModel('my/model')->getCollection(); foreach($options as $option){ $optionData = $option->getDropdowndata (); echo "<select>"; echo "<option>" .$optionData."</option>"; echo "</select>"; } } Using the code above, the data was populated but one data with one drop down option. So there are so many drop down options appear on the browser, each drop down option will contain only one data. I think I am missing the while ($ary = mysql_fetch_array($result)). But I confuse how to include that code? So, my question is how to do mysql_fetch_array in Magento? Or can somebody please explain how to make the second code above work like the first code.
getData() function returns an array of the whole data, and of course need move 'select' nodes out of the foreach echo "<select>"; foreach($options as $option){ $optionData = $option->getData(); echo "<option>" .$optionData['somekey'] ."</option>"; } echo "</select>"; But I think would be better use the magento magic functions, for example if you have 'entity_id' column in DB you can get value using $option->getEntityId(), etc...
And why do you have select inside of foreach? I think something like this will solve your problem: public function dropdownAction() { $options= Mage::getModel('my/model')->getCollection(); echo "<select>"; foreach($options as $option){ $optionData = $option->getDropdowndata (); echo "<option>" .$optionData."</option>"; } echo "</select>"; }