php delete sql query not working - php

<?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.

Related

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

SQL and POST requests

How do I handle variables from POST requests? Lets say I have tables like this And I want to update the votes variable wherever a specific id is.
So for the code I have this
$vote = $_POST["votes"];
$sentid = $_POST["sentid"];
along with something like this
UPDATE `my_exampleo202s`.`President Candidates` SET votes = votes + 1 WHERE `President Candidates`.`id` = sentid
And in the post request I send the sentid with a number. sentid=3
This doesn't work though. I'm not able to give any errors or anything because I'm not viewing it from a browser.
Any idea what the proper way is that I'm supposed to do this?
(Here's the code I have right now if it's needed)
<?php
$vote = $_POST["votes"];
$sentid = $_POST["sentid"];
$conn = new mysqli("localhost","exampleo202s","","my_exampleo202s");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE `my_exampleo202s`.`President Candidates` SET votes = votes + 1 WHERE `President Candidates`.`id` = sentid";
if ($conn->query($sql) === TRUE) {
echo "<br>Record updated successfully <br>";
} else {
echo "<br>Error updating record: <br>" . $conn->error;
}
$conn->close();
?>
UPDATE
<?php
$vote = $_POST["votes"];
$sentid = $_POST["sentid"];
$conn = new mysqli("localhost","jusavoting10rxx9s3","","my_jusavoting10rxx9s3");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE `my_jusavoting10rxx9s3`.`President Candidates` SET votes = votes + 1 WHERE `President Candidates`.`id` = $sentid";
if ($conn->query($sql) === TRUE) {
echo "<br>Record updated successfully <br>";
} else {
echo "<br>Error updating record: <br>" . $conn->error;
}
$conn->close();
?>
Try echo your $_POST value if it doesn't work:
<?php
$vote = $_POST["votes"];
$sentid = $_POST["sentid"];
$conn = new mysqli("localhost","exampleo202s","","my_exampleo202s");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE `my_exampleo202s`.`President Candidates` SET votes = votes + 1 WHERE `President Candidates`.`id` = $sentid";
if ($conn->query($sql) === TRUE) {
echo "<br>Record updated successfully <br>";
} else {
echo "<br>Error updating record: <br>" . $conn->error;
}
$conn->close();
?>

if cells are null insert syntax

I'm trying to check whether major, grade and university in candidates table, are empty, if so then insert in university...Else...
Is my syntax appropriate?
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
while($row5 = mysqli_fetch_array($result5)) {
$major = $row5['Major'];
$grade = $row5['Grade'];
$university = $row5['University'];
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`major`, `degree`, `univ`, `afnumber`) VALUES ('$major','$grade','$university','".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
else
{
Use the follwing code
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`major`, `degree`, `univ`, `afnumber`) VALUES ('$major','$grade','$university','".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
else
{
well you are saying that if major, grade and university are empty than insert those empty values in university but the question here is why you want to enter those values if they are empty, even if you want to do so along with inserting afnumber using "$_GET["af"]" variable than you can use following code..
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`afnumber`) VALUES ('".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
its quite short and fulfill the purpose but make sure you have checked null in database for major, grade and univ fields in university table .

Displaying ALL data from sql table in PHP?

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

PDO row count confusion

I am making a login page that checks for matching values in a database if the SELECT query returns a matching row with username and password then it will return a row count of 1. The way I have it coded right now when I echo the variable that stores the row count it will echo 26 for some reason and I'm not to sure why.
Would someone explain if I am doing something wrong or if this is normal behavior and where that value is coming from?
function checkLogin($conn,$myusername,$mypassword,$row,$row1){
try {
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
if($results->fetchColumn() > 0) {
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
$rowCount = count($row);
echo $rowCount;
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
echo $count;
}
else {
print "NO ROWS";
}
}
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}
Your code, $rowCount = count($row);, is counting the columns in the current row - not the number of rows returned by the query.
On the same note, you are echoing a second count related variable, $count, but you neither declare-it nor increment it in your code. It looks like this one is the one that's supposed to be counting the number of rows you loop through. If this is true, you should set it as $count = 0; before the loop and use $count++; within it:
$count = 0;
foreach ($conn->query($sql) as $row) {
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
$count++;
}
echo $count;
Also, you're currently using PDO's rowCount prior to selecting a user, and you're using it properly. You could just store that result into a variable and use it to tell how many rows you are receiving:
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
$numRows = $results->fetchColumn();
if($numRows > 0) {
... rest of your code ....
function checkLogin($conn,$myusername,$mypassword,$row,$row1)
{
try
{
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql))
{
$count = $results->fetchColumn();
echo "$count\n";
if($count > 0)
{
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
}
else
{
print "NO ROWS";
}
}
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
}

Categories