got the following code. All values are gotten through javascript and then sent through ajax. The var_dump($array) at the end works and display all the correct values. So they are all passed through correctly. The catch error for the try method also never pops up. The values are not being inserted into the sql table. Whats wrong?
Thanks in advance.
$name = $_GET['name'];
$category = $_GET['category'];
$subCategory = $_GET['subCategory'];
$date = $_GET['date'];
$address = $_GET['address'];
$city = $_GET['city'];
$state = $_GET['state'];
$host = $_GET['host'];
$imagePath = $_GET['imagePath'];
$info = $_GET['info'];
//turn into array
$array = array();
$array[0]=$name;
$array[1]=$category;
$array[2]=$subCategory;
$array[3]=$date;
$array[4]=$address;
$array[5]=$city;
$array[6]=$state;
$array[7]=$host;
$array[8]='j';//$imagePath;
$array[9]=$info;
try {
$con = new PDO('mysql:host=localhost;dbname=test');
$insert = $con->prepare(" INSERT INTO create
(name,category,subCategory,date,address,city,state,host,imagePath,info)
VALUES (?,?,?,?,?,?,?,?,?,?) ");
$insert->execute($array);
}
catch(PDOException $e) { //try
echo 'error';
//echo 'ERROR: ' . $e->getMessage();
}
var_dump($array);
create is a reserved word in mysql so you need to quote it in backticks:
INSERT INTO `create` ...
To have PDO throw exceptions, you need to add that after you open your connection:
$con = new PDO('mysql:host=localhost;dbname=test');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
By the way, I assume that you are logging into your database with a username and a password as well (the second and third parameter of the PDO constructor)...
Related
I try to store scraped data into my database. just to echo the result works perfectly, so the scraping is OK. But there must be an error in defining a variable and passing it to the mysql-insert. I get the message "New record created successfully". The result for the variable is empty and the date is there.
<?php
$html = file_get_contents('https://www.marketwatch.com/market-data/us?mod=market-data-center');
$scriptDocument = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html)){
$scriptDocument->loadHTML($html);
libxml_clear_errors();
$scriptDOMXPath = new DOMXPath($scriptDocument);
$scriptRow = $scriptDOMXPath->query('//th[starts-with(text(), "ISSUES:")]//following::td[6]');if($scriptRow->length > 0){foreach($scriptRow as $row){echo $row->nodeValue;}} // echo result works
$scriptRow = $scriptDOMXPath->query('//th[starts-with(text(), "ISSUES:")]//following::td[6]');if($scriptRow->length > 0){foreach($scriptRow as $row){$row->nodeValue = $nasdaq_dec;}} // defining variable does not work
};
$host_name = '';
$database = '';
$user_name = '';
$password = '';
try {
$conn = new PDO("mysql:host=$host_name; dbname=$database;", $user_name, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO `morgenroutine` (date,nasdaq_dec)
VALUES (NOW(), '$nasdaq_dec')";
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Now I got it! I changed the format in mysql to "text" and the line to:
$scriptRow = $scriptDOMXPath->query('//th[starts-with(text(), "ISSUES:")]//following::td[6]');if($scriptRow->length > 0){foreach($scriptRow as $row){$nasdaq_dec = $row->nodeValue;}}
I need some help
Is there a way to make this in PDO? https://stackoverflow.com/a/1899508/6208408
Yes I know I could change to mysql but I use a mssql server and can't use mysql. I tried some things but I'm not as good with PDO as mysql... It's hard to find some good examples of inserting array's into database with PDO. So quickly said I have a PDO based code connected to a mssql webserver.
best regards joep
I tried this before:
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$data = array_merge($mon_barcode, $mon_merk, $mon_type, $mon_inch, $mon_a_date, $mon_a_prijs);
try{
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
$insertData = array();
foreach($_POST['mon_barcode'] as $i => $barcode)
{
$insertData[] = $barcode;
}
if (!empty($insertData))
{
implode(', ', $insertData);
$stmt = $conn->prepare($sql);
$stmt->execute($insertData);
}
}catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
The code below should fix your problems.
$db_username='';
$db_password='';
$conn = new \PDO("sqlsrv:Server=localhost,1521;Database=testdb", $db_username, $db_password,[]);
//above added per #YourCommonSense's request to provide a complete example to a code fragment
if (isset($_POST['com_id'])) { //was com_id posted?
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
try {
$stmt = $conn->prepare($sql);
foreach ($mon_barcode as $i => $barcode) {
$stmt->execute([$com_id, $barcode, $mon_merk[$i], $mon_type[$i], $mon_inch[$i], $mon_a_date[$i], $mon_a_prijs[$i]]);
}
} catch (\PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
$conn = null;
When I add data to Database MySQL it fails.
//function add
public function add($name, $director, $cast, $genre,$release,$duration,$thumb,$plot,$another,$reviews,$critic)** {
$query = "INSERT INTO $this->table_name(name,director,cast,genre,release,duration,thumb,plot,another,reviews,critic) "
. "Values('$name','$director','$cast','$genre','$release',$duration,'$thumb','$plot','$another','$reviews',$critic)";
$data = parent::insert($query);
var_dump($query);
return $data;
}
//Add data
$info = new Info_Film();
if (isset($_POST['save'])) {
$name = $_POST['name'];
$director = $_POST['director'];
$cast = $_POST['cast'];`enter code here`
$genre = $_POST['genre'];
$release = $_POST['release'];
$duration = $_POST['duration'];
$thumb = $_POST['thumb'];
$plot = $_POST['plot'];
$another = $_POST['another'];
$reviews = $_POST['reviews'];
$critic = $_POST['critic'];
$info->add($name, $director, $cast, $genre,$release,$duration,$thumb,$plot,$another,$reviews,$critic);
}
?>
echo your old $query then copy and paste it in mysql query editor and Run it. You will what is the actual error and all query variables are blank or not.
$query = "INSERT INTO `$this->table_name` (`name`,`director`,`cast`,`genre`,`release`,`duration`,`thumb`,`plot`,`another`,`reviews`,`critic`) "
. " Values ('$name','$director','$cast','$genre','$release','$duration','$thumb','$plot','$another','$reviews','$critic')";
Echo & check all values then Replace above query.
release is a mysql reserved word, so you would need to quote it in backticks.
However, you could also be sql injecting yourself. You should really switch to a prepared statement to avoid that.
You should also add error handling and display errors during development. Both mysqli and PDO can throw exceptions but you need to tell them to do that.
Im trying to get the last id after inserting data into mysql.I already try using mysql_insert_id() but it seem doesn't work.
Below is the PHP code :
function addPhoneContact($customername ,$address ,$email ,$comment,$remarks){
$connection = MySQLConnection();
$conf = new BBSupervisorConf();
$log = new KLogger($conf->get_BBLogPath().$conf->get_BBDateLogFormat(), $conf->get_BBLogPriority() );
$query="INSERT INTO bb_customer
(customername,address ,email ,comment,remarks)
VALUES
('".$customername."','".$address."','".$email."','".$comment."','".$remarks."');";
$customerid = mysql_insert_id();
try {
$log->LogDebug("Query[".$query."]");
if (!mysql_query($query)){
die (mysql_error());
}else{
}
}catch(Exception $e){
$log->LogError($e->getMessage());
}
closeDB($connection);
return $customerid;
}
Thanks for your help.
Put this line
$customerid = mysql_insert_id();
After you have executed query by
mysql_query($query)
If mysql query is not executed it will not know about id.
Strongly consider not to use mysql_* functions.
Why shouldn't I use mysql_* functions in PHP?
function addPhoneContact($customername ,$address ,$email ,$comment,$remarks){
$connection = MySQLConnection();
$conf = new BBSupervisorConf();
$log = new KLogger($conf->get_BBLogPath().$conf->get_BBDateLogFormat(), $conf->get_BBLogPriority() );
$query="INSERT INTO bb_customer
(customername,address ,email ,comment,remarks)
VALUES
('".$customername."','".$address."','".$email."','".$comment."','".$remarks."');";
$customerid = mysql_insert_id(); //comment this out
try {
$log->LogDebug("Query[".$query."]");
if (!mysql_query($query)){
die (mysql_error());
}else{
}
}catch(Exception $e){
$log->LogError($e->getMessage());
}
$customerid = mysql_insert_id(); //add here
closeDB($connection);
return $customerid;
}
I have this simple code to make search results depending on relevance:
$stmt = $db->query('SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")');
$appCount = $stmt->rowCount();
echo $appCount;
And it's not showing any results!
Thanks in advance for your help,
Marcell
Stackoverflow's usability is below zero.
Because there is no way to make a half-screen banner shown to everyone posting a question under PDO tag:
Enable ERRMODE_EXCEPTION when connecting to PDO before asking a question.
Because it is pointless to ask without an error message, yet error message most likely will render a question unnecessary.
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);
$pdo = new PDO($dsn,'root','', $opt);
Try
'SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")'
in phpmyadmin and see if it really returns anything.
try this
<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'username';
$passdb = 'password';
try {
// Connect and create the PDO object
$db = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$db->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Define and perform the SQL SELECT query
$sql = "SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")";
$stmt = $db->query($sql);
// If the SQL query is succesfully performed ($stmt not false)
if($stmt !== false) {
$cols = $stmt->columnCount(); // Number of returned columns
echo 'Number of returned columns: '. $cols. '<br />';
// Parse the result set
foreach($stmt as $row) {
echo $row['id']. ' - '. $row['name']. ' - '. $row['category']. ' - '. $row['link']. '<br />';
}
}
$db = null; // Disconnect
}
print_r($sth->errorInfo());
}
?>
enclose your code in try and catch blocks, then you should get a clue to where your going wrong in your SQL syntax:
try {
// your code
} catch ( PDOException £e ) {
echo $e->getMessage();
exit();
}