Trying to transfer json from a table to anther php - php

I have a problem and I don't know how to solve it. I want to transfer a json to another table and I get a syntax error.
This is my output
INSERT INTO saved_cmd ('id_user','value','store','totalPrice','hour','type_payement') VALUES ('11','"{\"lenght\":0,\"produits\":[{\"id\":29,\"name\":\"Tarte au fraise\",\"count\":1,\"price\":2,\"totalPrice\":2},{\"id\":28,\"name\":\"rose des sables\",\"count\":0,\"price\":2,\"totalPrice\":0}]}"','6','2.00','13:00','caisse')
===================================================
Error: INSERT INTO saved_cmd ('id_user','value','store','totalPrice','hour','type_payement') VALUES ('11','"{\"lenght\":0,\"produits\":[{\"id\":29,\"name\":\"Tarte au fraise\",\"count\":1,\"price\":2,\"totalPrice\":2},{\"id\":28,\"name\":\"rose des sables\",\"count\":0,\"price\":2,\"totalPrice\":0}]}"','6','2.00','13:00','caisse')<br>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''id_user','value','store','totalPrice','hour','type_payement') VALUES ('11','"{\' at line 1
I tried to encode my json but i have the same problem
and this is my php
$state = $row['states'];
$id_user = $row['id_user'];
$value = ($row['value']);
$panier = json_encode($value);
$store = $row['store'];
$totalPrice = $row['totalPrice'];
$hour = $row['hour'];
$type_payement = $row['type'];
if ($row['states'] != 4) {
$states = $state + 1;
$sql = "UPDATE cmd SET states = $states WHERE id = '$id'";
if ($conn->query($sql)) {
echo "good:up";
}
} else {
$sql = "INSERT INTO saved_cmd ('id_user','value','store','totalPrice','hour','type_payement') VALUES ('$id_user','$panier','$store','$totalPrice','$hour','$type_payement')";
echo $sql . "\n\n\n===================================================\n\n\n";
if ($conn->query($sql) === true) {
echo "good:save";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

Related

How can I add each result to my table in MySQL

I have a php file (with simple_HTML_Dom) which scrape all the URLs of a CSV file.
He extract all the info I need, and all OK, but now I want to add all these results on my MySQL table.
I want each result adds in one row in MySQL table.
That's the code I have so far:
<?php
require 'libs/simple_html_dom/simple_html_dom.php';
set_time_limit(0);
function scrapUrl($url)
{
$html = new simple_html_dom();
$html->load_file($url);
$names = $html->find('h1');
$manufacturers = $html->find('h2');
foreach ($names as $name) {
echo $name->innertext;
echo '<br>';
}
foreach ($manufacturers as $manufacturer) {
echo $manufacturer->innertext;
echo '<br>';
echo '<hr><br>';
}
}
$rutaCSV = 'csv/urls1.csv'; // Ruta del csv.
$csv = array_map('str_getcsv', file($rutaCSV));
//print_r($csv); // VerĂ¡s que es un array donde cada elemento es array con una de las url.
foreach ($csv as $linea) {
$url = $linea[0];
scrapUrl($url);
}
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
foreach ($csv as $linea) {
$sql = "INSERT INTO productos (nombre, nombreFabricante) VALUES($name, $manufacturer)";
print ("<p> $sql </p>");
if ($conn->query($sql) === TRUE) {
echo "Items added to the database!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
EDIT: I have updated the code. I have added also the price variable.
The error shown in the output is this one:
Notice: Undefined variable: name in C:\xampp\htdocs\bootstrap\csv2.php on line 69
Notice: Undefined variable: manufacturer in C:\xampp\htdocs\bootstrap\csv2.php on line 69
Error: INSERT INTO productos (nombre, nombreFabricante) VALUES(,)
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' 'https://url.com/es/product1.html', )' at line 1
How can I solve the error for the Notice: Undefined variable: name & price?
I want to add the $name and $manufacturer variables which are inside the function, to my MySQL table
I'm not sure where you define $name so you'll need to check that it's valid.
foreach ($csv as $linea) {
$sql = "INSERT INTO productos (name, manufacturer) VALUES('$name', '{$linea[0]}')";
print ("<p> $sql </p>");
if ($conn->query($sql) === TRUE) {
echo "Items added to the database!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
Try this code , Hope you are collecting each value separately but your need is to insert each set of result in the mysql table as a new row , try the below but it's a rough one make it as per your need.
require 'libs/simple_html_dom/simple_html_dom.php';
set_time_limit(0);
function scrapUrl($url)
{
$ar_name =array();
$ar_man = array();
$html = new simple_html_dom();
$html->load_file($url);
$names = $html->find('h1');
$manufacturers = $html->find('h2');
foreach ($names as $name) {
$ar_name[] = $name->innertext;
}
foreach ($manufacturers as $manufacturer) {
$ar_man[] = $manufacturer->innertext;
}
for($i=o;$i<sizeof($ar_name);$i++)
{
$sql = "INSERT INTO table(name, manufacturer)
VALUES ($ar_name[$i],$ar_man[$i])";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
//echo $url;
}
$rutaCSV = 'csv/urls1.csv'; // Ruta del csv.
$csv = array_map('str_getcsv', file($rutaCSV));

SQL Syntax Error id suddenly equals zero

Does anybody know what could be wrong here?
<?php
$q = intval($_GET['q']);
echo $q." "; // $q=2
$d = $_GET['d'];
echo $d." "; //$d=3priority
$m = preg_replace('/[0-9]+/', '', $d);
echo $m." "; //$m = priority
$s = intval($_GET['d']);
echo $s;// $s = 3
$sql = "UPDATE form SET $m = $q WHERE id = $s";
$result = $conn->query($sql);
if ($conn->query($sql) === TRUE) {echo "das";}
else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
I get the Error Message :
UPDATE form SET = 0 WHERE id = 0 You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the
right syntax to use near '= 0 WHERE id = 0' at line 1
However if I echo the $m/$q/$s/$d thy show the right values. But somehow they get changed to 0 in the sql statement.
Would be nice if you could help me out :)
Try This
$sql = "UPDATE form SET" . $m . "=" . $q . " WHERE id =" . $s;

Error in SQL syntax (quotes ???!!!)

Can someone help me to debug this
<?php
$file_name = basename(__FILE__,'.php');
include("conf.php");
include("XMLSoccer.php");
$years = 1; ///<-------NUMBER OF YEARS TO GO BACK
$leagueretrive = 3; ///<--------THE LEAGUE ID TO RETRIEVE DATA FOR
$date1 = date('y', strtotime("-$years years"));
$date2 = date("y");
//CHECKING IF TABLE EXIST IF NOT CREATE NEW
$table = $file_name;
$query = "SELECT ID FROM " . $table;
$resultat = mysqli_query($conn,$query);
if(empty($resultat)) {
echo "<p>" . $table . " table does not exist</p>";
$query = mysqli_query($conn,"CREATE TABLE IF NOT EXISTS $file_name (
Id int NOT NULL PRIMARY KEY,
HomeGoalDetails varchar(800) NOT NULL,
)CHARACTER SET utf8 COLLATE utf8_general_ci");
}
else {
echo "<p>" . $table . "table exists</p>";
} // else
/////GETING THE DATA FROM SERVICE
try {
$soccer = new XMLSoccer($api_key);
$soccer->setServiceUrl("http://www.xmlsoccer.com/FootballDataDemo.asmx");
$results = $soccer->GetHistoricMatchesByLeagueAndSeason(array("league"=>$leagueretrive,"seasonDateString"=>"$date1$date2"));
print_r($results);
} catch (XMLSoccerException $e) {
echo "XMLSoccerException: " . $e->getMessage();
}
foreach ($results->Match as $team) {
$id = $team->Id;
$homeGoalDetails = $team->HomeGoalDetails;
///INSERTING DATA INTO THE TABLE
$sql = "INSERT INTO $file_name (HomeGoalDetails)
VALUES ('$homeGoalDetails')
on duplicate key update HomeGoalDetails='$homeGoalDetails'";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The response what i get
Error: INSERT INTO testing2 (HomeGoalDetails) VALUES ('35': Stefan
Johansen;4': penalty Leigh Griffiths;') on duplicate key update
HomeGoalDetails='35': Stefan Johansen;4': penalty Leigh Griffiths;'
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near ': Stefan Johansen;4': penalty Leigh Griffiths;') on duplicate
key update HomeGo' at line 2 Process finished with exit code 0
You've got unescaped quotes in your query.
Try:
<?php
$file_name = basename(__FILE__,'.php');
include("conf.php");
include("XMLSoccer.php");
$years = 1; ///<-------NUMBER OF YEARS TO GO BACK
$leagueretrive = 3; ///<--------THE LEAGUE ID TO RETRIEVE DATA FOR
$date1 = date('y', strtotime("-$years years"));
$date2 = date("y");
//CHECKING IF TABLE EXIST IF NOT CREATE NEW
$table = $file_name;
$query = "SELECT ID FROM " . $table;
$resultat = mysqli_query($conn,$query);
if(empty($resultat)) {
echo "<p>" . $table . " table does not exist</p>";
$query = mysqli_query($conn,"CREATE TABLE IF NOT EXISTS $file_name (
Id int NOT NULL PRIMARY KEY,
HomeGoalDetails varchar(800) NOT NULL,
)CHARACTER SET utf8 COLLATE utf8_general_ci");
}
else {
echo "<p>" . $table . "table exists</p>";
} // else
/////GETING THE DATA FROM SERVICE
try {
$soccer = new XMLSoccer($api_key);
$soccer->setServiceUrl("http://www.xmlsoccer.com/FootballDataDemo.asmx");
$results = $soccer->GetHistoricMatchesByLeagueAndSeason(array("league"=>$leagueretrive,"seasonDateString"=>"$date1$date2"));
print_r($results);
} catch (XMLSoccerException $e) {
echo "XMLSoccerException: " . $e->getMessage();
}
foreach ($results->Match as $team) {
$id = $team->Id;
$homeGoalDetails = $team->HomeGoalDetails;
///INSERTING DATA INTO THE TABLE
$sql = "INSERT INTO $file_name (HomeGoalDetails)
VALUES ('".mysqli_real_escape_string($conn,$homeGoalDetails)."')
on duplicate key update HomeGoalDetails='".mysqli_real_escape_string($conn,$homeGoalDetails)."'";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

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);

SQL syntax error IN

I'm writing a script to figure out whether changes have been made to my data.
However i'm getting this error:
Error: UPDATE Workhours SET IN= '07:59' WHERE AFNumber='AF1585' AND
Date='09/07/2015' You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'IN= '07:59' WHERE AFNumber='AF1585' AND
Date='09/07/2015'' at line 1Error: UPDATE Workhours SET OUT= '14:04'
WHERE AFNumber='AF1585' AND Date='09/07/2015'
Any help please?
if (isset($_POST['submit']))
{
$sql = "SHOW COLUMNS FROM Workhours";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
$tempname = $row['Field'];
$sql2 = "UPDATE Workhours SET ".$row['Field']."= '$_POST[$tempname]' WHERE AFNumber='".$_GET["af"]."' AND Date='".$_GET["date"]."'";
$result2 = mysqli_query($con,$sql2);
if ($con->query($sql2) === TRUE) {
} else {
echo "Error: " . $sql2 . "<br>" . $con->error;
}
}
$sql3 = "SELECT * FROM Workhours WHERE AFNumber='".$_GET["af"]."' AND (".$row['Field']." NOT LIKE '".$_POST[$tempname]."')";
$result3 = mysqli_query($con,$sql3);
if (mysqli_num_rows($result3) > 0) {
// output data of each row
while($row3 = mysqli_fetch_array($result3)) {
$sql3 = "INSERT INTO `Changes` (`Table`, `AFNumber`, `Attribute`, `DateChanged`, `HRUser`, `OldValue`, `NewValue`)
VALUES ('Workhours', '".$_GET["af"]."', '".$row["Field"]."', '".date('dd/m/Y HH:mm:ss')."', '$login_session', '', '$_POST[$tempname]')";
if (mysqli_query($con,$sql3) === TRUE) {
} else {
echo "Error: " . $sql3 . "<br>" . mysqli_error($con);
}
}
}
echo '<script>swal("Success", "Changes have been saved", "success");</script>';
}
IN and OUT are keywords in MySQL. You have to escape the $row['Field'] with backticks.
$sql2 = "UPDATE Workhours SET `".$row['Field']."`= '$_POST[$tempname]' WHERE AFNumber='".$_GET["af"]."' AND Date='".$_GET["date"]."'";
Also you should use prepared statements for preventing SQL injection.

Categories