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();
?>
Related
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;
}
}
I tried to update a row in table showtable
Bugupdate
By using the php code below, binding a bugID to a SQL UPDATE statement to update the row I want to but it doesn't seem to work, is it the problem lie in my SQL statement ?
$id = $_GET['update'];
$games = htmlentities($_POST['games']);
$version = htmlentities($_POST['version']);
$platform = htmlentities($_POST['platform']);
$frequency = htmlentities($_POST['frequency']);
$proposal = htmlentities($_POST['proposal']);
$SQLstring2 = "UPDATE " .$TableName. " SET Game=?,Version=?,Platform=?,Frequency=?,Proposed solution=? WHERE BugID= " .$id;
if ($stmt = mysqli_prepare($DBconnect, $SQLstring2)) {
mysqli_stmt_bind_param($stmt,'sssss', $games, $version, $platform, $frequency, $proposal);
$QueryResult2 = mysqli_stmt_execute($stmt);
if ($QueryResult2 === FALSE) {
echo "<p>Unable to execute the query.</p>"
. "<p>Error code "
. mysqli_errno($DBconnect)
. ": "
. mysqli_error($DBconnect)
. "</p>";
} else {
echo "<h1> Thank you for your contribution";
}
mysqli_stmt_close($stmt);
}
mysqli_close($DBconnect);
Try to rename Proposed solution column to Proposed_solution and adapte the sql query like this :
$SQLstring2 = "UPDATE " .$TableName. " SET Game=?,Version=?, Platform=?, Frequency=?, Proposed_solution=? WHERE BugID= " .$id;
<?php
include('session.php');
?>
<?php
$conn = new mysqli("127.0.0.1","root","","foo");
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
$sew = $_SESSION['login_user'];
$a = $_GET["en"];
$l = 1;
$d = -1;
if($a == 1)
{
$sqlw = " INSERT into dlkeuser VALUES('$a','$sew')" ;
if ($conn->query($sqlw) === FALSE)
{
echo "you have already disliked the song";
}
else
{
//query1
$sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' ";
//query2
$sql = "UPDATE liking
SET count = count - 1 ";
if ($conn->query($sql) === TRUE) {
echo "you disliked the song";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
In this php code snippet, query1 is not working whereas query 2 is fine.
I am trying to insert (songid, userid) in dlkeuser(dislike) table against user i/p($_GET["en"]) and delete the record(songid,userid) from lkeuser(like) table if it exists. (songid,userid) pair is the composite primary key here. count is the net like/dislike of a song.
let's try this,
it will work
<?php
include('session.php');
?>
<?php
$conn = new mysqli("127.0.0.1","root","","foo");
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
$sew = $_SESSION['login_user'];
$a = $_GET["en"];
$l = 1;
$d = -1;
if($a == 1)
{
$sqlw = " INSERT into dlkeuser VALUES('$a','$sew')";
if ($conn->query($sqlw) === FALSE)
{
echo "you have already disliked the song";
}
else
{
//query1
$sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' " ;
//query2
$sql1 = "UPDATE liking
SET count = count - 1 ";
if ($conn->query($sql) === TRUE) {
echo "deleted the song";
}
if ($conn->query($sql1) === TRUE) {
echo "you disliked the song";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
You need to execute query1, before reuse your $sql variable.
//query1
$sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' " ;
$conn->query($sql);
//query2
$sql = "UPDATE liking
SET count = count - 1 ";
if ($conn->query($sql) === TRUE) {
You are not executing your query1 anywhere. Just the following code won't execute your query
$sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' " ;
You need another line like the following (as you did for query2)
if ($conn->query($sql) === TRUE) {
echo "you liked the song";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
This executes the query and also checks for errors.
When I print my code it only prints the question and description of id = 1 but not the rest of the table.
here is my code.
Please show me how to print my entire table which has like 20 questions or so...and also please show me how to make it so that the questions stay on the browser (even when I refresh the page) because currently the data does not stay on the browser when i refresh the page.
Thanks So Much!
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
} else {
echo "failed to fetch array";
}
}
?>
You need a for each loop:
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
} else {
echo "failed to fetch array";
}
}
?>
All I've done there is change:
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
to:
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
fetch_assoc() — Fetch a result row as an associative array
so it gets only 1 row you need to loop through the rest of the rows check the examples reference from php docs
I am working on a php script that stores message ids (Msg_ID, Ref_ID) in their corresponding user account tables.
What I've is, the Msg_ID is properly written, but the Ref_ID is always blank.
How ever when I run the query separately it works, but doesn't work in the script for some odd reason.
Here is the code :
$qry = "SELECT Ref_ID FROM Chat WHERE Msg_ID = " .$MsgID. ")";
$resp = mysqli_query($con, $qry);
$xx = mysqli_fetch_array($resp);
$ref_id = $xx['Ref_ID'];
foreach ($Array as $user){
$query = "Insert into ".$user."(POST_ID, REF_ID) values ('". $MsgID . "', '" .$ref_id. "')";
mysqli_query($con, $query);
}
The $ref_id is always blank and as a result, the blank value is written to the respective database.
Some help with what is wrong will be helpful.
Here is the full code :
<?php
function PostMainThread($Heading, $Message, $Author, $MarkedList){
$con=mysqli_connect("mysql.serversfree.com", "u521497173_root", "123456", "u521497123_mydb");
$Array = explode(',', $MarkedList);
if (mysqli_connect_errno()){
$response["success"] = 0;
$response["message"] = "Connection Failed.";
echo json_encode($response);
}else{
here:$MsgID = rand(1, 9999999);
$query = "Insert into Chat(Msg_ID, Header, MsgBody, Author) values (". $MsgID . "," . "'" . $Heading . "' ," .
"'" . $Message . "', '". $Author . "')";
$result=mysqli_query($con, $query);
if (!$result){
goto here;
}else{
//Put the MsgID in the respective user tables.
$qry = "SELECT Ref_ID FROM Chat WHERE Msg_ID = " .$MsgID. ")";
$resp = mysqli_query($con, $qry);
$xx = mysqli_fetch_array($resp);
$ref_id = $xx['Ref_ID'];
foreach ($Array as $user){
$query = "Insert into ".$user."(POST_ID, REF_ID) values ('". $MsgID . "', '" .$ref_id. "')";
mysqli_query($con, $query);
}
$response["success"] = 1;
$response["message"] = "Submission successful.";
mysqli_close($con);
echo json_encode($response);
}
}
}
function PostReplyToThread($PostID, $Author, $Reply){
$con=mysqli_connect("mysql.serversfree.com", "u521497123_root", "123456", "u521497123_mydb");
if (mysqli_connect_errno()){
echo 2;
}else{
$query = "Insert into Chat(Msg_ID, Header, MsgBody, Author) values (". $PostID . "," . "'" . " " . "' ," .
"'" . $Reply . "', '". $Author . "')";
$result=mysqli_query($con, $query);
if ($result){
echo 3;
}else{
echo 4;
}
mysqli_close($con);
}
}
if (isset($_POST['what_to_do'])){
if ($_POST['what_to_do'] == 0){
if ((isset($_POST['Title'])) &&(isset($_POST['Body']))&&(isset($_POST['Marked']))&&(isset($_POST['_Author']))){
PostMainThread($_POST['Title'], $_POST['Body'], $_POST['_Author'], $_POST['Marked']);
}
}else if ($_POST['what_to_do'] == 1){
if ((isset($_POST['Thread_ID'])) &&(isset($_POST['Answer']))&&(isset($_POST['_Author']))){
PostReplyToThread($_POST['Thread_ID'], $_POST['_Author'], $_POST['Answer']);
}
}
}else{
$response["success"] = 0;
$response["message"] = "Unspecified action";
echo json_encode($response);
}
Definition of the Chat table :
Create table Chat(Ref_ID INT Auto_Increment, Msg_ID INT, Header varchar(50), MsgBody varchar(500
), Author varchar(30), Primary Key(Ref_ID, Msg_ID));
$xx = mysqli_fetch_array($resp);
Will only return a numerically indexed array, as in $xx[0], $xx[1].
To use the column names, you need to use:
$xx = mysqli_fetch_array($resp, MYSQLI_ASSOC);
Or the shorter version:
$xx = mysqli_fetch_assoc($resp);
As a side note, don't forget security, when inserting data that comes from outside the function and could possibly have a quotes or SQL, it needs to be escaped!
$Heading = mysqli_real_escape_string($con, $Heading);
Otherwise it will come back to bite you.