MYSQL DELETE query not affecting rows - php

Here is a function I have in my php file
function deleteLocation() {
global $con;
$val = $_POST['id'];
$escaped = mysqli_real_escape_string($con,$val);
$sql = "DELETE FROM settings WHERE value = '".$escaped."'";
if(!mysqli_query($con,$sql)){
die("Query failed:" . mysqli_error($con));
} else {
die("DELETE FROM settings WHERE value = '".$escaped."' / num rows affected: " . mysqli_affected_rows($con));
}
}
Here is the text that is returned on the page
DELETE FROM settings WHERE value = 'asdasd ' / num rows affected: 0
If I take the first part, and run it on my phpmyadmin page,
DELETE FROM settings WHERE value = 'asdasd '
it will correctly delete the row, but as you can see from the output, 0 rows are affected when the script is run on the page.
If anyone can help to fix this I will be very grateful.
PS: The connection string and user permissions are indeed set up correctly, because every other function in this file works properly
EDIT: Got it, the space at the end of the string was a newline character that was sent from my javascript.

I tried re-creating your problem on my machine and the only time I get the same message as you is when that item was already deleted from the table (or when it wasn't there in the first place)

This was a pretty unique situation, so I don't know how much this would help other people but,
I had an array of strings that all had \n at the end, so I had to do
str[value] = str[value].trim();
foreach value in the array. It turns out that this was not a php problem, but rather js

Related

Value goes up by 2 instead of 1, also some array error's i don't understand

So i have this problem i can't figure out. but what the problem is that when i press the right arrow in the page, the value has to go up by 1, not 2. and when pressed the left button, it should go -1 and that works normally.
i try to get all the id's from the database and put it in a array. the functions check the array for end and first values and put's the data to the page input.
here is the code where i struggle with:
// checks if the variable has not been set, otherwise errors and problems will occur
if (empty($_SESSION["huidigeklant"])) {setHuidigeKlant();}
// common variables set to use
$id[] = $_SESSION["id"];
// makes a pre connection to check if a value can be set up or down to prevent errors in the input page.
$result = mysqli_query($conn, "SELECT * from klanten"); // run the query and assign the result to $result
while ($row=mysqli_fetch_assoc($result)) {
array_push($id, $row["id"]);
}
// checks first and last array value of the session id
function checkfirstklant(){ $firstID = reset($id); return $firstID; }
function checklastklant(){ $lastID = end($id); return $lastID; }
// checks first if the right or left button has been pressed and checks after that if the value is already at the first or end array
if (isset($_POST['leftbutton'])){
if (($firstID = checkfirstklant()) != $_SESSION["huidigeklant"]) {
$_SESSION['huidigeklant']--;
echo "huidige klant = " . $_SESSION["huidigeklant"];
}
}
if (isset($_POST['rightbutton'])){
if (($lastID = checklastklant()) != $_SESSION["huidigeklant"]) {
$_SESSION['huidigeklant']++;
echo "huidige klant = " . $_SESSION["huidigeklant"];
}
}
one thing to mention and already figured that out. the "setHuidigeKlant() sets $_SESSION["huidigeklant"] to 1".
so my question is: How can i prevent the program to set the value to 1, but still set the value to 1 if it hasn't been set in the first place?
i coudln't find a specific answer for this, but if you do. send a link to it please
thanks in advance ;)
So i already found my problem xD
what Difster already said at the post above, i need to isset my $_SESSSION["huidigeklant"] instead of checking if it is empty.
and i have to check if i am already at the end of the variable in the if statement instead of letting that doing by a function.
so now everything works as requested ;)
thanks again
Try this:
if (!isset($_SESSION["huidigeklant"])) { $_SESSION["huidigeklant"] = 1;}

MySQL UPDATE function refuses to update database

I've been trying to make this code work for hours now but I can't seem to find solution. I've serached all relevant topics and tried to change the code, punctuation etc. but none of them worked for me.
The result is always "Success!" but the database update never works (checked in phpmyadmin).
I hope that you can find the error. The code is the following:
if(empty($_POST['nev']) || empty($_POST['orszag']) || empty($_POST['telefonszam']) || empty($_POST['iranyitoszam'])
|| empty($_POST['megye']) || empty($_POST['varos']) || empty($_POST['utca'])) {
echo "Failure! Missing data...";
}
else {
$nev = mysql_real_escape_string($_POST['nev']);
$orszag = mysql_real_escape_string($_POST['orszag']);
$telefonszamm = mysql_real_escape_string($_POST['telefonszam']);
$iranyitoszam = mysql_real_escape_string($_POST['iranyitoszam']);
$megye = mysql_real_escape_string($_POST['megye']);
$varos = mysql_real_escape_string($_POST['varos']);
$utca = mysql_real_escape_string($_POST['utca']);
$shipping_query = mysql_query("UPDATE users
SET Name=".$nev.", Phone=".$telefonszam.",
Country=".$orszag.", State=".$megye.",
City=".$varos.", ZIP=".$iranyitoszam.",
Road=".$utca."
WHERE EmailAddress='" . $_SESSION['EmailAddress'] . "'");
echo "Success!";
}
Thank you for your help!
You're missing quotes around the strings in your query.
$shipping_query = mysql_query("UPDATE users
SET Name='".$nev."', Phone='".$telefonszam."',
Country='".$orszag."', State='".$megye."',
City='".$varos."', ZIP='".$iranyitoszam."',
Road='".$utca."'
WHERE EmailAddress='" . $_SESSION['EmailAddress'] . "'");
You also no error checking on your query. So whether it succeeds or fails it will always say, "success". You need to check to see if there is a MySQL error ir rows updated before you can declare success.
Name, Phone, Country etc etc seam like VARCHARs. so, it should be treated as a string.
So, query should be like.
"UPDATE users SET Name='".$nev."', Phone='".$telefonszam."',Country='".$orszag."', State='".$megye."',City='".$varos."', ZIP='".$iranyitoszam."',Road='".$utca."' WHERE EmailAddress='" . $_SESSION['EmailAddress'] . "'"
As other answers have pointed out, you're missing quotes around your string variables.
When you're MySQL queries are failing to execute, try echoing your queries while debugging to see what exactly you're sending to the database.
$myValue = "Green";
$mySQL = "UPDATE MyTable SET MyColor = " . $myValue;
$myQuery = mysql_query($mySQL);
echo $mySQL;
Spotting the error visually is much easier when the entire SQL string is assembled in one piece.
You can also copy the assembled SQL string and paste it straight into a phpmyadmin query to get debugging information from it.

PHP update query, code revision

I have two functions on the same webpage, each of them will update one different table on the same database depending which button you press.
This function modifies one table and works:
function SaveMItem()
{
$DayOfWeekNumber = 0;
if ($_POST['selDayOfTheWeek'])
{$DayOfWeekNumber = $_POST['selDayOfTheWeek'];}
mysql_query("UPDATE tblMItem SET ItemText = '" . $_POST['txtFirstOne'] . "' WHERE MenuItemID = " . (1 + $DayOfWeekNumber));
echo "SaveMItem Ok";
}
function SavetblAnnouncement(){
mysql_query("UPDATE TblAnuncios SET Title=".$_POST['txtAnnouncementTitle']. ",Content=".$_POST['txtAnnouncementContent']." WHERE 1");
echo "Completed announcement" ;
}
When I press SaveMItem button I can see the message SaveMItem Ok and it saves new values on Table.
When I press SavetblAnnouncement button I can see the message Completed announcement but the table TblAnuncios will not get updated.
As this is on the same file, the Database is the same and the function SaveMItem is able to update the table I suppose the connexion to the DB is ok.
Can anyone let me know what am I doing wrong?
Thanks in advance.
You're missing quotes around the values.
$title = mysql_real_escape_string($_POST['txtAnnouncementTitle']);
$txt = mysql_real_escape_string($_POST['txtAnnouncementContent']);
mysql_query("UPDATE TblAnuncios SET Title='".$title. "',Content='".$txt."' WHERE 1");
You should also escape the string, both to prevent SQL injection and also to make the query correct if the title or text contains quote characters.

URL and link text from database

I am currently still learning PHP so some things I still struggle with.
I have been taking it slowly and reading tutorials which has helped but I can't figure this one out.
I have a database table (in mysql) with let's say, 100 urls. There is a column called 'url' and a second column 'text'. I already have the pagination code which works, so will also be using that.
What I want to do is echo out the URLs (which are all in folder called blog in the root of my site), but use the text as the link.
So for example the first three rows in my table might be:
url
001.php
002.php
003.php
text
random text
some random text
more text
when echoed out the links show the text from the column text like:
random text
some random text
more text
and will open to the relevant url when clicked
I'm guessing it will need some kind of loop to collect all the URLs and save me adding the link text in manually, and then my pagination code will split them up.
This is my first time asking a question on here, so if it wasn't clear enough or you need more info, let me know.
I have done multiple searches on the internet but can't seem to find a tutorial.
Assuming you connect to a local mysql server with username "root" and password "root", and have your url's stored in a table named url_table in a database named url_database you could do something like:
$connection = mysql_connect("127.0.0.1","root","root"); // Connect to the mysql server
mysql_select_db("url_database"); // Open the desired database
$query = "SELECT url,text FROM url_table"; // Query to select the fields in each row
$result = mysql_query($query); // Run the query and store the result in $result
while($row = mysql_fetch_assoc($result)) // While there are still rows, create an array of each
{
echo "<a href='".$row['url']."'>".$row['text']."</a>"; // Write an anchor with the url as href, and text as value/content
}
mysql_close($connection); // close the previously opened connection to the database
What you need is to:
get your result array from the database. Use something like
$query = "SELECT * FROM urls";
$result = mysql_query($query);
For every row in your results table, show the corresponding url. Note that calling mysql_fetch_array on a result resource, returns the first row of the results table when called for the first time, the second on second time etc. The function returns false when there are no more rows to return.
(See more on that in the mysql_fetch_array() documentation)
While( $row = mysql_fetch_array($result) ){
echo '<a href='.$row['url'].'>'.$row['text'].'</a>';
}
Here is a sample you can start with:
$con = mysql_connect("host","user","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT the_url, the_text FROM my_table");
while($row = mysql_fetch_array($result))
{
echo '"' . $row['the_text'] . ' <br />';
}
mysql_close($con);
First, you want to select only the relevant lines in your database for the page that the user is currently viewing. For example, if the user is viewing page 2, with entries 15-30 present, we only want to pull those entries from the database. This is an efficiency concern.
The code you're after is something like this:
$link = mysql_connect(/*connection parameters go here*/);
if ($link === false)
die;
mysql_select_db('my_database');
$result = mysql_query("SELECT text, url FROM my_table LIMIT 15,30");
print "<ul>\n";
while ($row = mysql_fetch_assoc($result)) {
print "<li>{$row['text']}</li>\n";
}
print "</ul>\n";
mysql_close();
The first three lines establish a connection to the database, and exit the script if an error occurs.
The next line selects the appropriate database on the server.
The next block runs the appropriate query for the second page. After the query is run, a 'result' is stored in $result. This result is comprised of a number of rows, and mysql_fetch_assoc($result) obtains those lines one at a time. It then formats these lines into the appropriate link format and outputs them. The entire set of links is wrapped in a dot-point list.
Finally, mysql_close() closes the connection to the database.
I'm assuming since you just started you're probably doing all this procedurally.
First you want to query the database and get the info you need.
<?php
$result = mysqli_query($link, "SELECT url, text FROM table_name");
while ($row = mysqli_fetch_array($result)) $hrefs[] = $row;
foreach ($hrefs as $href) {
echo "".$href['text']."";
}
?>
Please note I've done no error handling here.

Query that works in SQL but not in PHP

I am having trouble with an SQL query that I have inserted into a piece of PHP code to retrieve some data. The query itself works perfectly within SQL, but when I use it within my PHP script it says "Error in Query" then recites the entire SQL statement. If I copy and paste the SQL statement from the error message directly into MySQL it runs with no errors.
From my research I believe I am missing an apostrophe somewhere, so PHP may be confusing the clauses, but I am not experienced enough to know where to insert them.
The query is using a variable called $userid which is specified earlier in the PHP script.
$sql= <<<END
SELECT sum(final_price)
FROM (
SELECT Table_A.rated_user_id, Table_B.seller, Table_B.final_price
FROM Table_A
INNER JOIN Table_B ON Table_A.id=Table_B.id
) AS total_bought
WHERE seller != $userid
AND rated_user_id = $userid
UNION ALL
SELECT sum(final_price)
FROM (
SELECT Table_A.rated_user_id, Table_C.seller, Table_C.final_price
FROM Table_A
INNER JOIN Table_C ON Table_A.id=Table_C.id
) AS total_bought
WHERE seller != $userid
AND rated_user_id = $userid
END;
After this section the script then goes on to define the output and echo the necessary pieces as per usual. I'm happy with the last part of the code as it works elsewhere, but the problem I am having appears to be within the section above.
Can anyone spot the error?
Edited to add the following additional information:
All of the fields are numerical values, none are text. I have tried putting '$userid' but this only makes the error display the ' ' around this value within the error results. The issue remains the same. Adding parenthasis has also not helped. I had done a bit of trial and erorr before posting my question.
If it helps, the last part of the code bieng used is as follows:
$result = mysql_query($sql);
if (!$res) {
die('Error: ' . mysql_error() . ' in query ' . $sql);
}
$total_bought = 0;
while ($row = mysql_fetch_array($result)) {
$total_bought += $row[0];
}
$total_bought = number_format($total_bought, 0);
echo '<b>Your purchases: ' . $total_bought . '</b>';
echo "<b> gold</b>";
You're checking !$res, it should be !$result:
$result = mysql_query($sql);
if (!$result) {
die('Error: ' . mysql_error() . ' in query ' . $sql);
}
I suppose, you're echo()ing the query somewhere and copy-pasting it from the browser. Could it be that the $userid contains xml tags? They wouldn't be displayed in the browser, you would have to view the page source to spot them.
you should test with $userid quoted, and parentheses around the two statements.
I'm assuming that rated_user_id is a numeric field, but what type is seller? If it's a character field, then $userid would have to be quoted as streetpc suggests.
Another thing to check is that you have at least one space after the end of your lines for each line of the query. That has tripped me up before. Sometimes when going from your editor/IDE to the database tool those problems are silently taken care of.

Categories