Broken PDO Insert during while loop - php

I am trying to put together a simple php page to monitor my server. It downloads an XML, parses it during a while loop and then inserts a new row for each result. There are six records in the video_servers table, and the SELECT part is working great, till I try inserting the results, then it only loops through one time. If I take out the try INSERT portion, it will loop through the six times printing the var_dump. What am I missing on this? The insert works just fine once, then ends.
try {
$query = $db->prepare("SELECT * FROM video_servers");
$query->bindValue(':url', $url, PDO::PARAM_STR);
$query->bindValue(':title', $server, PDO::PARAM_STR);
$query->bindValue(':type', $type, PDO::PARAM_STR);
$query->execute();
}
catch (PDOException $e){
printf("something broke");// logError($e->getMessage(), $query->queryString, __FILE__, __LINE__ );
exit;
}
while($results = $query->fetch(PDO::FETCH_ASSOC)){
$xmlfile = simplexml_load_file('http://lalalala.com/connectioncounts');
$count = $xmlfile->ConnectionsCurrent;
$server = $results['title'];
$type = "active-connections";
try {
$query = $db->prepare("INSERT INTO dashboardserverstats (server, type, value) VALUES (:server, :type, :value)");
$query->bindValue(':server', $server, PDO::PARAM_STR);
$query->bindValue(':type', $type, PDO::PARAM_STR);
$query->bindValue(':value', $count, PDO::PARAM_STR);
$query->execute();
}
catch (PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
var_dump($results);
}

In the second query change the name of the variable $query. you are overwriting it.

Related

SQLSTATE[IMSSP]: Tried to bind parameter number 65536. SQL Server supports a maximum of 2100 parameters

I want to ask something what error is this. I want to display report book to PHP but the result showing like in picture
Here is my report book:
public function GetReportBook($id_book, $TanggalStart, $TanggalEnd)
{
// select all query
try {
require_once 'Database.php';
$sqlsrvquery = (" EXEC [dbo].[GetReportBook] #id_book=id_book, #TanggalStart=TanggalStart, #TanggalEnd=TanggalEnd");
// prepare query statement
$stmt = $this->conn->prepare($sqlsrvquery);
$stmt->bindParam('id_book', $id_book, PDO::PARAM_STR);
$stmt->bindParam('TanggalStart', $TanggalStart, PDO::PARAM_STR);
$stmt->bindParam('TanggalEnd', $TanggalEnd, PDO::PARAM_STR);
$stmt->execute();
while($r = $stmt->fetch(PDO::FETCH_OBJ)) {
print_r($r);
}
} catch (Exception $e) {
print_r($e->getMessage());
}
}
}
and here is the result showing in ASP.NET:
You need to consider the following:
You need to use named (:name) or question mark (?) parameter markers in the prepared statement.
You need to use an unambiguous datetime format (yyyymmdd in your case) for the value of :TanggalStart and :TanggalEnd parameters.
An example, based on your code:
public function GetReportBook($id_book, $TanggalStart, $TanggalEnd)
{
// select all query
try {
require_once 'Database.php';
$sqlsrvquery = ("
EXEC [dbo].[GetReportBook]
#id_book = :id_book,
#TanggalStart = :TanggalStart,
#TanggalEnd = :TanggalEnd
");
// prepare query statement
$stmt = $this->conn->prepare($sqlsrvquery);
$stmt->bindParam(':id_book', $id_book, PDO::PARAM_STR);
$stmt->bindParam(':TanggalStart', date('Ymd', strtotime($TanggalStart)), PDO::PARAM_STR);
$stmt->bindParam(':TanggalEnd', date('Ymd', strtotime($TanggalEnd)), PDO::PARAM_STR);
$stmt->execute();
while($r = $stmt->fetch(PDO::FETCH_OBJ)) {
print_r($r);
}
} catch (Exception $e) {
print_r($e->getMessage());
}
}
}

Do While loop works well with echo but loops only once with a function inside loop

This code is supposed to insert 100 rows into the DB.
Yet when I run it, it loops only once, inserts one row and stops.
I replaced the function call with :
echo $keywords[4].'<br>';
It works perfectly. with no probleb
What is missing so that it will insert all rows into DB?
what should I change q add so that the code will insert all rows in the file
Here is the loop code:
do{
//Insert row content into array.
$keywords = preg_split("#\<(.*?)\>#", $row);
//Insert relevant data into DB
add_data($keywords);
}
else{
// If row is irrelevant - continue to next row
continue;
}
}while (strpos($row, 'Closed P/L') != true);
Here is the function
function add_data($keywords)
{
global $db;
$ticket =$keywords[2];
$o_time = $keywords[4];
$type = $keywords[6];
$size = $keywords[8];
$item = substr($keywords[10], 0, -1);
$o_price = $keywords[12];
$s_l = $keywords[14];
$t_p = $keywords[16];
$c_time = $keywords[18];
$c_price = $keywords[20];
$profit = $keywords[28];
try
{
$sql = "
INSERT INTO `data`
(ticket, o_time, type, size, item, o_price, s_l, t_p, c_time, c_price, profit)
VALUES
(:ticket, :o_time, :type, :size, :item, :o_price, :s_l, :t_p, :c_time, :c_price, :profit)";
$stmt = $db->prepare($sql);
$stmt->bindParam('ticket', $ticket, PDO::PARAM_STR);
$stmt->bindParam('o_time', $o_time, PDO::PARAM_STR);
$stmt->bindParam('type', $type, PDO::PARAM_STR);
$stmt->bindParam('size', $size, PDO::PARAM_STR);
$stmt->bindParam('item', $item, PDO::PARAM_STR);
$stmt->bindParam('o_price', $o_price, PDO::PARAM_STR);
$stmt->bindParam('s_l', $s_l, PDO::PARAM_STR);
$stmt->bindParam('t_p', $t_p, PDO::PARAM_STR);
$stmt->bindParam('c_time', $c_time, PDO::PARAM_STR);
$stmt->bindParam('c_price', $c_price, PDO::PARAM_STR);
$stmt->bindParam('profit', $profit, PDO::PARAM_STR);
$stmt->execute();
//return true;
}
catch(Exception $e)
{
return false;
echo 'something is wrong. Here is the system\'s message:<br>'.$e;
}
}

inserting date using PDO and php

I'm trying to insert into a table, I have managed this using the same syntax for another query but this fails, the only difference is that this contains date information. Can anyone spot the problem?
The date is in this format: 2016-07-07.
try {
$sql2 = "INSERT INTO excavation.contexts_spatial
(area_easting,
area_northing,
context_number,
open_date,
close_date,
excavation_method,
contamination,
zooarchaeology_comments,
ceramic_comments) VALUES (
:area_easting,
:area_northing,
:context_number,
:open_date,
:close_date,
:excavation_method,
:contamination,
:zooarchaeology_comments,
:ceramic_comments)";
$stmt2 = $conn->prepare($sql2);
// prepare sql and bind parameters
$stmt2->bindParam(':area_easting', $area_easting, PDO::PARAM_INT);
$stmt2->bindParam(':area_northing', $area_northing, PDO::PARAM_INT);
$stmt2->bindParam(':context_number', $nextContext, PDO::PARAM_INT);
$stmt2->bindParam(':open_date', $open_date, PDO::PARAM_STR);
$stmt2->bindParam(':close_date', $close_date, PDO::PARAM_STR);
$stmt2->bindParam(':excavation_method', $excavation_method, PDO::PARAM_STR);
$stmt2->bindParam(':contamination', $contamination, PDO::PARAM_STR);
$stmt2->bindParam(':zooarchaeology_comments', $excavation_method, PDO::PARAM_STR);
$stmt2->bindParam(':ceramic_comments', $excavation_method, PDO::PARAM_STR);
//$stmt2->execute();
// insert a row
$area_easting = $_SESSION['area_easting'];
$area_northing = $_SESSION['area_northing'];
$nextContext = $_SESSION['nextContext'];
$open_date = $_SESSION['dateOpen'];
$close_date = $_SESSION['dateClose'];
$excavation_method = $_SESSION['excavationMethod'];
$contamination = $_SESSION['contamination'];
$zooarchaeology_comments = $_SESSION['zooarchaeologyComments'];
$ceramic_comments = $_SESSION['ceramicComments'];
$stmt2->execute();
echo "New records created successfully in contexts spatial<br />";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
You are executing your statement before setting the variables. Remove $stmt2->execute();
from below
$stmt2->bindParam(':ceramic_comments', $excavation_method, PDO::PARAM_STR);
$stmt2->execute(); // REMOVE THIS LINE
// insert a row
$area_easting = $_SESSION['area_easting'];

Trying to use prepare and bindParam to insert user data into SQL table

Trying to insert user input into a MYSQL database. I am utilizing the REPLACE INTO because the column email has a unique key to prevent duplication. The table name is launch_email. I am trying to prevent SQL injection by using prepare and bindParam, however I keep getting this error: Call to undefined function bindParam(). Any solutions?
PHP/SQL:
require(ROOT_PATH . "inc/database.php");
try {
$replace = $db->prepare("REPLACE INTO launch_email VALUES (:email_str)");
$replace = bindParam(":email_str", $email, PDO::PARAM_STR);
$replace->execute();
} catch (Exception $e) {
echo "Data could not be submitted to the database.";
exit;
}
EDIT: The code below solved my problem. I was assigning a method to a non-object.
require(ROOT_PATH . "inc/database.php");
try {
$replace = $db->prepare("REPLACE INTO launch_email VALUES (:email_str)");
$replace->bindParam(":email_str", $email, PDO::PARAM_STR);
$replace->execute();
} catch (Exception $e) {
echo "Data could not be submitted to the database.";
exit;
}
Remember bindParam is a method of the Classes PDO, MySQLi or whatever database you're using... So it must be called this way:
$replace->bindParam(":email_str", $email, PDO::PARAM_STR);
PDOStatement::bindParam is a PDOStatement method .
this should work
require(ROOT_PATH . "inc/database.php");
try {
$stm = $db->prepare("REPLACE INTO launch_email VALUES (:email_str)");
$stm->bindParam(":email_str", $email, PDO::PARAM_STR);
$stm->execute();
} catch (Exception $e) {
echo "Data could not be submitted to the database.";
exit;
}
bindParam is not a language function. It is a method of the PDOStatement object.
$replace->bindParam(":email_str", $email, PDO::PARAM_STR);
It would be better if instead of using $replace as your variable name, you call it something like $stmt so that it is more apparent what that object is.
Alternatively, you can pass your parameter at execution. By writing your code like this:
$stmt = $db->prepare("REPLACE INTO launch_email VALUES (?)");
if ($stmt)
{
// Execute query with parameter
$stmt->execute(array($email));
}
else
{
// Could not prepare statement
echo $db->errorInfo();
}

PDO insert only one record

I have been trying to overcome this problem for a while now and i need your help on this.
The code on the below only insert one record in mysql table and only one. Data from html forms are posted very well but it simple doesn't record more than once. I also use phpmyadmin and i don't know what is the problem. I'd be appriciated if you could help me.
Here is the code:
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$STH1 = $DBH->query("SELECT isim, adet, kategori
FROM stock
WHERE isim = '$isim' AND kategori = '$kategori'");
$STH1->setFetchMode(PDO::FETCH_ASSOC);
if($STH1->rowCount() == 0) {
echo "There is no such record";
}
else {
$STH2 = $DBH->prepare("INSERT INTO outgoing
(isim, adet, nereye, cikis_tarih, kategori)
values
(:isim, :adet, :nereye, :cikis_tarih, :kategori)");
$STH2->bindParam(':isim', $isim, PDO::PARAM_STR);
$STH2->bindParam(':adet', $adet, PDO::PARAM_STR);
$STH2->bindParam(':nereye', $nereye, PDO::PARAM_STR);
$STH2->bindParam(':cikis_tarih', $cikis_tarih, PDO::PARAM_STR);
$STH2->bindParam(':kategori', $kategori, PDO::PARAM_STR);
$STH2->execute();
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Instead of doing:
$STH2->bindParam(':isim', $isim, PDO::PARAM_STR);
$STH2->bindParam(':adet', $adet, PDO::PARAM_STR);
$STH2->bindParam(':nereye', $nereye, PDO::PARAM_STR);
$STH2->bindParam(':cikis_tarih', $cikis_tarih, PDO::PARAM_STR);
$STH2->bindParam(':kategori', $kategori, PDO::PARAM_STR);
$STH2->execute();
Execute it through an array:
$STH2->execute(array(':isim'=>$isim,
':adet'=>$adet,
':nereye'=>$nereye,
':cikis_tarih'=>$cikis_tarih,
':kategori'=>$kategori));

Categories