How to insert parsed data to mysql? - php

How to insert parsed data in mysql, but before we need to check if record exist or not.
And I need to record item parsed description to item with parsed ID.
For example on my DB I have a lot of products with ID and another column and with empty "description" column. And I need to feel this empty column with current decsription.
include 'simple_html_dom.php';
$db = mysqli_connect('localhost', 'mysql', 'mysql', 'database');
$site = 'http://optnow.ru/catalog';
$data = file_get_html($site);
$catalogLink = array();
$i = 0;
if(!empty($data)) {
foreach($data->find('div.cat-name a') as $catalog) {
$catalogLink['url'] = $catalog->href;
$urls[] = $catalogLink;
}
foreach($urls as $url => $k) {
foreach($k as $n) {
$catalogLink = 'http://optnow.ru/' . $n . '?page=0';
$productData = file_get_html($catalogLink);
foreach($productData->find('.link-pv-name') as $link) {
$productLink['url'] = $link->href;
$productUrls[] = $productLink;
}
foreach($productUrls as $href) {
$link = 'http://optnow.ru/' . $href['url'];
$product = file_get_html($link);
foreach($product->find('.block-d .btns-d .btn-buy') as $productId) {
if(!empty($productId)) {
$dataId = $productId->{'data-offerid'};
}
}
foreach($product->find('.description div div p') as $description) {
if(!empty($description)) {
$query = "INSERT INTO snowcore_parser_products (`description`) WHERE `remote_id` = " . $dataId . " VALUES (" . $description->plaintext . "');";
$sql = mysqli_query($db, $query);
print_r($sql);
}
}
}
}
}
}

Related

Search Json array inside a col with php sql query

I need some help please.
Currently my mariadb is set up with one column as a json array.
I would like to search the array from a users input, then combine it with the first and last name of the user stored in the database.
In the database:
Columns: firstname, lastname and suburbs_i_cover (containing the json array)
ex: ["Pretoria","Cape Town","Garden Route"]
I would like the sql statement that would search the suburbs_i_cover and allow me to combine the first and last name.
So far I have this:
<?php
//echo JUri::getInstance();
if (isset($_GET['category'])) {
$catetogry = $_GET['category'];
$name = $_GET['name'];
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query = ("SELECT * FROM #__jsn_users"); //not sure what goes here
$db->setQuery($query);
$results = $db->loadObjectList();
foreach($results as $obj) {
$value = json_decode($obj->suburbs_i_cover);
$value = array_filter($value, 'strlen'); //removes null values
but leaves "0"
$value = array_filter($value); //removes all null
values
if (!empty($value)) {
$value2 = $obj->firstname;
$value3 = $obj->lastname;
echo $value2 . ' '. $value3;
//echo "<br>";
// echo sizeof($value);
echo "<br>";
if (is_array($value)) {
foreach ($value as $sub_value) {
echo $sub_value;
echo "<br>";
}
}
echo "<br>";
echo "<hr>";
}
}
}
I got a working solution:
To use: in_array($name, $value)
<?php
//echo JUri::getInstance();
if (isset($_GET['category'])) {
$catetogry = $_GET['category'];
$name = $_GET['name'];
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query = ("SELECT * FROM #__jsn_users");
$db->setQuery($query);
$results = $db->loadObjectList();
foreach($results as $obj) {
$value = json_decode($obj->suburbs_i_cover);
$value = array_filter($value, 'strlen'); //removes null values
but leaves "0"
$value = array_filter($value); //removes all null
values
if (in_array($name, $value)) {
$value2 = $obj->firstname;
$value3 = $obj->lastname;
echo $value2 . ' '. $value3;
echo "<br>";
echo "<hr>";
}
}
}
?>

Trying to get property of non-object CRUD

I am making a CRUD system for blog publications, but it's kinda strange, another developer (with more experience) looked to my coded and for him it's all right too, but this error (Notice: Trying to get property of non-object in C:\xampp\htdocs\genial\painel\inc\database.php on line 32) remains appearing.
My database code:
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
function open_database() {
try {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
return $conn;
} catch (Exception $e) {
echo $e->getMessage();
return null;
}
}
function close_database($conn) {
try {
mysqli_close($conn);
} catch (Exception $e) {
echo $e->getMessage();
}
}
function find( $table = null, $id = null ) {
$database = open_database();
$found = null;
try {
if ($id) {
$sql = "SELECT * FROM" . $table . " WHERE id = " . $id;
$result = $database->query($sql);
if ($result->num_rows > 0) {
$found = $result->fetch_assoc();
}
}
else {
$sql = "SELECT * FROM " . $table;
$result = $database->query($sql);
if ($result->num_rows > 0) {
$found = $result->fetch_all(MYSQLI_ASSOC);
}
}
} catch (Exception $e) {
$_SESSION['message'] = $e->GetMessage();
$_SESSION['type'] = 'danger';
}
close_database($database);
return $found;
}
function find_all( $table ) {
return find($table);
}
function save($table = null, $data = null) {
$database = open_database();
$columns = null;
$values = null;
//print_r($data);
foreach ($data as $key => $value) {
$columns .= trim($key, "'") . ",";
$values .= "'$value',";
}
$columns = rtrim($columns, ',');
$values = rtrim($values, ',');
$sql = "INSERT INTO " . $table . "($columns)" . " VALUES " ($values);";
try {
$database->query($sql);
$_SESSION['message'] = 'Registro cadastrado com sucesso.';
$_SESSION['type'] = 'success';
} catch (Exception $e) {
$_SESSION['message'] = 'Nao foi possivel realizar a operacao.';
$_SESSION['type'] = 'danger';
}
close_database($database);
}
function update($table = null, $id = 0, $data = null) {
$database = open_database();
$items = null;
foreach ($data as $key => $value) {
$items .= trim($key, "'") . "='$value',";
}
$items = rtrim($items, ',');
$sql = "UPDATE " . $table;
$sql .= " SET $items";
$sql .= " WHERE id=" . $id . ";";
try {
$database->query($sql);
$_SESSION['message'] = 'Registro atualizado com sucesso.';
$_SESSION['type'] = 'success';
}
catch (Exception $e) {
$_SESSION['message'] = 'Nao foi possivel realizar a operacao.';
$_SESSION['type'] = 'danger';
}
close_database($database);
}
Sorry if it's not right idled.
I put an space on the code after the "FROM" at
$sql = "SELECT * FROM" . $table . " WHERE id = " . $id;
The error remains the same but know on line 36 that is:
if ($result->num_rows > 0) {
$found = $result->fetch_all(MYSQLI_ASSOC);
}
Turned the code on line 36 to:
$if (result = $database->query($sql)) {
The error disappeared, others problems not relative to this question happened.
Just in case this question isn't closed as off-topic -> typo generated, I'd better provide an acceptable answer.
Add a space between FROM and $table in your SELECT query.
Check for a non-false result from your query.
Your new code could look like this:
$sql = "SELECT * FROM `$table`";
if ($id) {
// assuming id has been properly sanitized
$sql .= " WHERE id=$id"; // concatenate with WHERE clause when appropriate
}
if ($result = $database->query($sql)) { // only continue if result isn't false
if ($result->num_rows) { // only continue if one or more row
$found = $result->fetch_all(MYSQLI_ASSOC); // fetch all regardless of 1 or more
}
}
$sql = "INSERT INTO " . $table . "($columns)" . " VALUES " ($values);"; has too many double quotes in it -- you can tell by how Stack Overflow highlights the characters. I could say that you could clean up the syntax, but it would ultimately be best to scrap your script and implement prepared statements.

How to use single for each loop for multiple array to update single sql statement

I want to use single for each for two array.
array 1 : has path of images (path is dynamic as per user need)
array 2: has values description field of each image (description is dynamic as per user need)
I want to insert both array in sql table using only one sql statement.
<?php $sql="INSERT INTO posts(title,description,category,createdBy,pictureURL,CreatedAt) VALUE ('$title',
'$description','$category','$creatdby','Admin/PostImages/$finalpath',now());";
$result = mysqli_query($conn,$sql);
if($result)
{
$upload_directory = 'PostImages/';
$field_values_array = $_REQUEST['desc'];
$x=0;
foreach($field_values_array as $value1){
foreach ( $_FILES['photo']['name'] AS $key => $value ){
//Move file to server directory
if(move_uploaded_file($_FILES["photo"]["tmp_name"][$x], $upload_directory . $_FILES["photo"]["name"][$x])){
$finalpath=$upload_directory . $_FILES["photo"]["name"][$x];
}
if (isset($_SESSION['p_id'])){
$p_id = $_SESSION["p_id"];
}
$sql1="INSERT INTO `postimages`(`p_id`,`description`, `img_path`) VALUES ('$p_id','$value1','$finalpath')";
$result1 = mysqli_query($conn,$sql1);
$x++;
}
}
header("Location: uploadpost_test.php");
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
} ?>
I refactor and clean up your codes. Try this.
if(isset($_SESSION['p_id']))
{
$p_id = $_SESSION["p_id"];
}
$values = '';
$next = ',';
$len = count($field_values_array);
foreach($field_values_array as $x=>$value1)
{
if(move_uploaded_file($_FILES["photo"]["tmp_name"][$x], $upload_directory.$_FILES["photo"]["tmp_name"][$x]))
{
$tmp_name = $_FILES["photo"]["tmp_name"][$x];
$finalpath = $upload_directory.$tmp_name;
$next = $x >= $len-1 ? '' : $next;
$values .= "VALUES('$p_id','$value1','$finalpath')".$next;
}
}
$sql1="INSERT INTO `postimages`(`p_id`,`description`, `img_path`) $values";
$result1 = mysqli_query($conn,$sql1);

how to check success on insert using OCI

I have the following code but i am not sure how to check if insert is success. execute returns resource id. I would like to check if success and return all errors on fail.
public function persist()
{
$update = FALSE;
if(!is_array($this->tablePrimaryKey)) {
if(!empty($this->fieldVals[$this->tablePrimaryKey])) {
$update = true;
}
}
if ($update) {
$sql = "UPDATE " . $this->tableName . " SET ";
$binds = [];
foreach ($this->fieldVals as $key=>$val) {
if ($key != $this->tablePrimaryKey) {
if(in_array($key, $this->DATE_IDS)) {
$sql .= '"' . strtoupper($key) . '" = sysdate,';
} else {
$bind = 't_' . $key;
$binds[$bind] = $val;
$sql .= '"' . strtoupper($key) . '" = :' . $bind . ',';
}
}
}
$sql = substr($sql,0,-1);
$sql .= " WHERE " . $this->tablePrimaryKey . " = '" . $this->fieldVals[$this->tablePrimaryKey] ."'";
} else {
$binds = $fields = $date_fields = [];
if(!empty($this->tablePrimaryKey) && !is_array($this->tablePrimaryKey)) {
$this->fieldVals[$this->tablePrimaryKey] = $this->generateNewPrimaryKey();
}
foreach ($this->fieldVals as $key=>$val) {
$bind = ':t_' . $key;
if (in_array($key, $this->DATE_IDS)) {
$date_fields[] = strtoupper($key);
} else {
$binds[$bind] = $val;
$fields[] = strtoupper($key);
}
}
$sql = 'INSERT INTO ' . $this->tableName . '("' . implode('","', $fields);
if(count($date_fields) >0) {
$sql .= '","';
$sql .= implode('","', $date_fields);
}
$sql.='") VALUES (' . implode(',', array_keys($binds));
if(count($date_fields) >0) {
$cnt=0;
foreach($date_fields as $date) {
$cnt++;
if(preg_match('/NULL/i', $this->fieldVals[strtolower($date)], $result)) {
$sql .= ",NULL";
} elseif(isset($this->fieldVals[strtolower($date)])) {
$sql .= ",TO_DATE('" . (new DateTime($this->fieldVals[strtolower($date)]))->format("Y-M-d H:i:s") . "', 'yyyy/mm/dd hh24:mi:ss')";
} else {
$sql .= ",sysdate";
}
}
}
$sql .= ')';
}
$this->oiDb->parse($sql, $binds);
return $this->oiDb->execute();
}
I run $result = $oiRequests->hydrate($reportingRequest)->persist();. $reportingRequest is key,value pair of columns/values. $result contains resource id. $oiRequests is my model.
I have tried
$num_rows = oci_fetch_assoc ($result);
print_r($num_rows);
returns
Warning: oci_fetch_assoc(): ORA-24374: define not done before fetch or execute and fetch in /var/SP/oiadm/docroot/dev/uddins/requestportal/requestportal_ajax.php on line 65
Most of the OCI functions return false on error. This means you can do a simple check on the return value and, if it's false, call oci_error().
For the specific case of checking if an INSERT statement worked you can reference the example code for oci_commit(). The relevant part of that example is duplicated here:
// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1. The two flags are equivalent
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

Give back more than one mysql result in an php class

I'm trying to build my own CMS in classes.
Now I have got a problem when I try to get data from my MySQL database
Instead of one item i'd like to get an collection of all my items
At the end I'd like to get an Object so I can read it out like : $item->id
Here's my code :
static function getContentItems($id, $active, $sort_by, $sort_type, $limit) {
if (isset($id) && !empty($id)) {
$where .= "WHERE id = ".$id;
}
if (isset($active) && !empty($active)) {
$where .= " AND active = ".$active;
}
if (isset($sort_by) && !empty($sort_by)) {
$where .= " ORDER BY ".$sort_by;
if (isset($sort_type) && !empty($sort_type)) {
$where .= " ".$sort_type;
}
}
if (isset($limit) && !empty($limit)) {
$where .= " LIMIT 0,".$limit;
}
if (isset($where) && !empty($where)) {
$query = "SELECT * FROM content ".$where;
} else {
$query = "SELECT * FROM content";
}
$result = mysql_query($query)or die(mysql_error());
$item = new ContentItem();
while ($data = mysql_fetch_array($result)) {
$item->id = $data['id'];
}
return $item;
}
}
dont start your $where string with .
if (isset($id) && !empty($id)) {
$where = "WHERE id = ".$id;
}
and alwez print your $query
Better Solution
if (!empty($id) {
$where = " WHERE id = ".$id;
if (!empty($active)) {
$where .= " AND active = ".$active;
if (!empty($sort_by)) {
$where .= " ORDER BY ".$sort_by;
if (!empty($sort_type)) {
$where .= " ".$sort_type;
}
}
}
}
if (empty($limit)) {
$where .= " LIMIT 0,".$limit;
}
and later
$item = new ContentItem();
$data = array(); $i=0;
while ($data = mysql_fetch_object($result)) {
$search_result[$i] = $data;
$i++;
}
return $search_result;
and any id can be retrieve by $search_result[$i]->id
Why don't you use Arrays?
Like this:
$collection = array();
while ($data = mysql_fetch_array($result)) {
$item = new ContentItem();
$item->id = $data['id'];
$collection[] = $item; //Appends the item to the array
}
return $collection;
You can access your array in this way:
$collection = YourClassName::getContentItems(...);
foreach($collection as $item) {
// do something with each $item
print_r($item);
}
Look into using mysql_fetch_object http://php.net/manual/en/function.mysql-fetch-object.php instead of mysql_fetch_array.. it returns rows the db as an object already

Categories