I'm trying to retrieve a filename from a database from table HORSE and column HORSE_IMAGE
$path = "horse_images/".$row["HORSE_IMAGE"];
$query = "DELETE FROM HORSE WHERE HORSE_ID=".$_GET["horseno"]." AND HORSE_IMAGE=".$row["HORSE_IMAGE"];
Currently HORSE_IMAGE returns nothing, but if I change it to HORSE_ID or HORSE_NAME, it works.
i.e. If i echo $row["HORSE_NAME"] it returns "You Beauty".
If I look up the row in the database I can see the filename shop-1.jpg is there.
Any ideas?
If you want to change a single column of a row, use an UPDATE statement. DELETE is for removing complete rows only. And yes, escape anything before using it in your query.
"UPDATE HORSE SET HORSE_IMAGE = NULL WHERE HORSE_ID=".(int)$_GET["horseno"];
As far as I understood the question, ToBe's answer might be correct, but you really should consider using PDO for MySql queries, in order to prevent Sql injection.
Try:
<?php
$query = "UPDATE HORSE SET HORSE_IMAGE = NULL WHERE HORSE_ID = ?";
$db = new PDO(dsn, username, password);
$prep = $db->prepare($query);
$res = $prep->execute(array((int)$_GET["horseno"]));
?>
Take a look at the documentation: http://php.net/manual/de/book.pdo.php
Related
This question already has answers here:
How to insert values in a PHP array to a MySQL table?
(2 answers)
Closed 5 years ago.
I'm using PHP session variable to track character ID's between two tables, characters and character_data_store.
The session ID definitely has the correct ID as I have had to print its value before it goes into the mySQL query.
For testing I selected a user I knew had a rapsheet and used
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.`key` = 'RapSheet'
AND character_data_store.character_id = '216'";
Obviously I can't use this for all users as I need to confirm the right one has been selected so thats where the session variable comes in.
I've tried using:
$correctPlayer = $_SESSION['selpid'];
echo $correctPlayer; #confirm it's the right id and then remove
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.'key' = 'RapSheet'
AND character_data_store.character_id = '$correctPlayer'";
I did some searching on SO and I found that int's need to have double quotes around them not single quotes, I tried that and had no luck but someone else suggested putting the session ID in exactly which I tried next:
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.'key' = 'RapSheet'
AND character_data_store.character_id = {$_SESSION['selpid']}";
Each time I do this I get mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given which SO tells me is because this operation results to false, I assume because it's not accepting the playerID from selpid or $correctPlayer?
It definitely works with the testing user where the playerID is inserted directly into the query. But I can't think of a way to do that since I need to match the playerID from table "characters" where the search is done against their first and last name and then pull the rapsheet data against the same playerID in table "character_data_store".
How do I use a variable in the WHERE condition of a MySQL query using a php variable?
You have obvious error in your code. You are missing quotes in {$_SESSION['selpid']} and you are using quotes in column name. Your query should be
$usersql = "SELECT * FROM character_data_store WHERE character_data_store.`key` = 'RapSheet' AND character_data_store.character_id = '{$_SESSION['selpid']}'";
You should not use quotes in column name, instead use backquotes(`) if you really need. I recommend prepared statements.
There are multiple ways to do this. A naive way to do this would be-
$usersql = "SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ".$correctPlayer;
But to avoid sql injections I would recommend you use bindparam function to bind paramaters in a statement.
$sql="SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ?";
if($stmt = $dbh->prepare($sql)){
$stmt->bindParam(1, $correctPlayer, PDO::PARAM_STR);
$ql = $stmt->execute() or die("ERROR: " . implode(":", $dbh->errorInfo()));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$result['data'] = $row;
There are many questions on SO about this but I cannot find one that quite meets my situation.
I want to use the values in some fields/columns of a table to set the value of a third field/column
In other words something like:
table races
athleteid|difficulty|score|adjustedscore
$sqlSelect = "SELECT athleteid,difficulty,score FROM races";
$res = mysql_query($sqlSelect) or die(mysql_error());
while ($row = mysql_fetch_array($res)){
$adjustedscore=difficulty*score;
$sqlupdate = "UPDATE race, set adjustedscore = '$adjustedscore' WHERE athletes = 'athletes'";
$resupdate = mysql_query($sqlupdate);
}
My understanding, however, is that MYSQL does not support update queries nested in select ones.
Note, I have simplified this slightly. I am actually calculating the score based on a lot of other variables as well--and may join some tables to get other inputs--but this is the basic principal.
Thanks for any suggestions
You can run:
UPDATE `races`
SET `adjustedscore` = `difficulty` * `score`
WHERE `athleteid` IN (1, 2, 3, ...)
First of all, as previous commentators said, you should use PDO instead of mysql_* queries.
Read about PDO here.
When you'll get data from DB with your SELECT query, you'll get array. I recommend you to use fetchAll() from PDO documentation.
So, your goal is to save this data in some variable. Like you did with $row.
After that you'll need to loop over each array and get your data:
foreach($row as $r) {
//We do this to access each of ours athlete data
$adjustedscore= $row[$r]["difficulty"]* $row[$r]["score"];
//Next row is not clear for me...
$query = "UPDATE race SET adjustedscore = '$adjustedscore' WHERE athletes = 'athletes'";
And to update we use PDO update prepared statement
$stmt = $dbh->prepare($query);
$stmt->execute();
}
Ok, don't know if this is simple in practice as it is in theory but I want to know.
I have a single INSERT query were by in that query, i want to extract the AUTO_INCREMENT value then reuse it in the same query.
For example
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
$getId = mysqli_insert_id();
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
Apparently, am getting a blank value(I know because the mysqli_insert_id() is before the query, but I've tried all i could but nothing has come out as i want. Can some please help me on how to achive this
From my knoweldge this cant be done. Because no query has been run, MySQL is unable to return the ID of said query.
You could use a classic approach, pull the id of the previous record and add 1 to it, this is not a great solution as if a record is deleted, the auto increment value and the last value +1 may differ.
Run multiple queries and then use the insert_id (MySQLi is different to what you are using, you are best using $db->lastInsertId(); as mentioned in the comments.
Run a query before hand and store it as a variable;
SELECT auto_increment FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 'tablename'
I strongly recommend Option 2, it is simply the cleanest and most reliable method for what you are looking to achieve.
It seems the value required for $display_type is :$display_type + (max(id) + 1).
In order to get the max_id you'll have to do this query before :
$sql = "SELECT id FROM articles ORDER BY id DESC LIMIT 1";
$result = mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
// $maxid[0] will contains the value desired
// Remove the mysqli_insert_id() call - Swap $getid by ($maxid[0] + 1)
// and u're good to go
N.B. update the name of ur primary key in the query $sql.
EDIT :
Assuming the weakness of the query and the quick resarch i did.
Try to replace $sql by (don't forget to Update DatabaseName & TableName values) :
$sql = SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
That Should do it . More info on the link below :
Stackoverflow : get auto-inc value
I don't think this can be done. You'll have to first insert the row, then update display_type, in two separate queries.
Thanks guys for your opinions, out of final copy, paste, edit and fix; here is the final working code(solution)
`
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
//Select AUTO_INCREMENT VALUE
$sql = "SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'chisel_bk'
AND TABLE_NAME = 'articles'";
$result = $mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
$getId = $maxid[0];
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
This happens to do the magic!!!
`
I check if the the url is present first and see if he is up voting first time, if so then i will add the users repute to the upvoted column, but i want to add only to that url not to all urls, this code is adding to all all tuples in "upvotes" column, i want it to add only to a particular tuple.
<!Doctype html>
<html>
<?php
$c=$_GET['a'];// users name
$d=$_GET['b'];// usesrs id
$e=$_GET['c'];// users repute
$ur=$_POST['url'];
// Create connection
$con=mysqli_connect("localhost","root","","repute system");
if(mysqli_connect_errno()){
echo "ERROR ".mysqli_connect_error();
}
$sql = mysqli_query($con,"SELECT * FROM sites");
if (mysqli_num_rows($sql) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($sql))
{
if($ur == $row['URL'] && $d != $row['id'])
{
$ne = $row['upvotes'] + $e;
$sol = mysqli_query($con, "UPDATE sites SET upvotes = $ne ");
$bew = mysqli_query($con,"INSERT INTO v_sites(teacher_id,URL,vote) VALUES ('$d','$ur','$e')");
echo "Upvoted the site ";
echo $ur;
}
}
} else {
echo "Sorry before upvoting you have to block it first or you are trying to upvote your own report, in which you cant";
}
?>
</html>
You need a WHERE clause that matches the URL:
$stmt = mysqli_prepare($con, "UPDATE sites
SET upvotes = upvotes + 1
WHERE url = ? AND id = ?";
mysqli_stmt_bind_param($stmt, "ss", $ur, $d);
mysqli_stmt_execute($stmt);
You don't need the SELECT or while loop, since MySQL can find the matching rows and update them all by itself.
You also shouldn't have the INSERT query inside the loop, since it's inserting the same row each time.
And you should switch to prepared statements, as shown above, instead of inserting strings into your queries, since your code is subject to SQL injection.
All your rows are being updated because you are not using a where clause.
UPDATE sites SET upvotes = $ne
should be changed to:
UPDATE sites SET upvotes = $ne WHERE id='$d'
However, if $ne is also a string, $ne should also be quoted:
UPDATE sites SET upvotes = '$ne' WHERE id='$d'
Read up on UPDATE:
https://dev.mysql.com/doc/refman/5.0/en/update.html
"My table's name in sites it has 5 columns, which are URL,status,upvotes,downvotes, id and all are varchar with 30 length"
This tells me that id is VARCHAR also; not a good idea but that's up to you. It's best to use int for queries like this should all your id's be numerically-based.
Which is why using quotes WHERE id='$d' around the $d variable will be required.
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
I try to update a row in a database, but I can't do that. Here is my sql:
$sql = "UPDATE `voting_nomination_counter`
SET `quantity`=quantity+1
WHERE `nid` = '$nid'
AND nominee = '$nominee'";
I suspect the problem is here - AND nominee = '$nominee'"; because when I remove this from the query all works and updates fine. Help, please.
Try this:
$sql = "UPDATE voting_nomination_counter SET quantity=quantity+1 WHERE nid = '$nid' AND nominee = '$nominee'";
I solve this problem, if I want to update WHERE string = string I just need to use this statement UPDATE table SET field = REPLACE(field, 'string', 'anothervalue') WHERE field LIKE '%string%';, thanks guys!)
#excluded_once Looks like you were able to solve your issue. So in future do not ever use variable names directly into SQL string. Always use db_query or db_select and then always bind the variables into SQL, it will help you prevent from SQL injections and other attacks.