PHP MySQL Update Query not working with vars - php

$ID = trim($_GET["uid"]);
$Name = trim($_GET["name"]);
$result = $mysqli->query("UPDATE `Benutzer` SET `R_NAME`='$Name' WHERE `ID` = '$ID'");
The Result returns fine, but the Database is not updated. If I replace the vars with static values the Database IS updated.

Use mysqli prepare statement.
$stmt = $mysqli->prepare("UPDATE Benutzer SET R_NAME = ? WHERE ID = ?");
$stmt->bind_param($Name,$ID);
$stmt->execute();
$stmt->close();

Follow these steps:
Remove "trim" & use "mysql_escape_string".
Echo Check the values of Name & ID. Once you are getting them then follow up with the 3rd step.
Concatinate the sql string as shown by removing the tild operators:
$result = $mysqli->query("UPDATE Benutzer SET R_NAME ='".$Name."' WHERE ID = '".$ID."'");

What we pass in the query arguments is a string or we can say query in the form of string. you can change the query like below.
$result = $mysqli->query("UPDATE `Benutzer` SET `R_NAME`='".$Name."' WHERE `ID` = '".$ID."'");

Related

Escaping MySQL UPDATE (IF LENGTH)

I've created an UPDATE statement that updates only if the string's length is greater than 0.
I'm trying to escape quotes within my UPDATE statement once the condition is met. I've been using addslashes($name), but with this new condition addslashes no longer works.
Previous:
$mysqli->query("UPDATE table SET name='".addslashes($name)."' WHERE id=1") or die($mysqli->error);
Current:
$mysqli->query("UPDATE table SET name=IF(LENGTH($name)=0, name, '$name') WHERE id=1") or die($mysqli->error);
Where do I place addslashes() for this function to correctly escape characters? Will this function even work within this particular MySQL statement for PHP?
The problem with your second query is that $name inside the call to LENGTH needs to be in quotes too i.e.
$mysqli->query("UPDATE table SET name=IF(LENGTH('$name')=0, name, '$name') WHERE id=1") or die($mysqli->error);
To use addslashes in that query, you would write:
$mysqli->query("UPDATE table SET name=IF(LENGTH('".addslashes($name)."')=0, name, '".addslashes($name)."') WHERE id=1") or die($mysqli->error);
But really you should consider using a prepared statement instead; then you won't have to worry about escaping quotes. Additionally, you should check the length of $name in PHP and not run the query at all if it is empty. Something like this should work (I'm assuming you have a variable called $id which stores the id value for the update).
if (strlen($name)) {
$stmt = $mysqli->prepare("UPDATE table SET name=? WHERE id=?");
$stmt->bind_param('si', $name, $id);
$stmt->execute() or die($stmt->error);
}
If you have multiple pieces of data to update, you could try something like this:
$name = 'fred';
$city = '';
$state = 'SA';
$id = 4;
$params = array();
foreach (array('name','city','state') as $param) {
if (strlen($$param)) $params[$param] = $$param;
}
$sql = "UPDATE table SET " . implode(' = ?, ', array_keys($params)) . " = ? WHERE id = ?";
$types = str_repeat('s', count($params)) . 'i';
$params['id'] = $id;
$stmt = $mysqli->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute() or die($stmt->error);

How to make Where clause dynamic in mysql

After logging into ones account and clicking 'Accept' button the system should insert a sequence of numbers in mysql table under "otp" column for validation purpose. The problem here is I want to make it dynamic in the WHERE clause. It should recognize and insert otp according to user ids itself.
Following is the code.
if(isset($_POST['generate']))
{
$num = (rand(111111, 999999));
file_get_contents("somelink");
$query = mysqli_query($con, "UPDATE users SET otp='".$num."' WHERE id = 21");
$qry_run = mysqli_query($con, $query);
mysqli_close($con);
header("location: otp.php");
}
You should not use var concatenated with your sql .. this behavior can allow sql injection so you should use prepare bind_param and execute
and assuming you have in var the valure for match the id you coould use this var for param too
$con = $con->prepare("UPDATE users SET opt = ? WHERE id = ?");
$con->bind_param('ii', $num, $id);
$num = (rand(111111, 999999));
$id = 21;
$con->execute();
mysqli_close($con);
Have you thought about using RAND() in SQL?
UPDATE users SET otp = RAND() WHERE id = 21

Why is returning null values by using bind_param in Mysqli?

I try to get the first record in a database table, and i need the function bind_param of Mysqli.
$query = "SELECT `username`,`password` FROM `user` WHERE `id` = ?";
$result = $mysqli->prepare($query) or trigger_error($mysqli->error."[$query]");
$id = 1;
$result->bind_param("i",$id);
$result->execute();
I have solved this problem.
Adding $result->bind_result($username,$password) after $result->execute()

updating the data using implode in php

please help me out and sorry for my bad English,
I have fetch data , on basis of that data I want to update the rows,
Follows my code
I fetched data to connect API parameters
<?php
$stmt = $db->stmt_init();
/* publish store for icube*/
$stmt->prepare( "SELECT id,offer_id,name,net_provider,date,visible,apikey,networkid FROM " ."affilate_offer_findall_icube WHERE visible='1' ");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result( $id, $offer_id, $name, $net_provider, $date, $visible,$apikey,$networkid);
$sql = array();
if($rows>0)
{
while($info = $stmt->fetch() ) {
$jsondataicube = file_get_contents('filename/json?NetworkId='.$networkid.'&Target=Affiliate_Offer&Method=getThumbnail&api_key='.$apikey.'&ids%5B%5D='.$offer_id.'');
$dataicube = json_decode($jsondataicube, true);
foreach($dataicube['response']['data'][0]['Thumbnail'] as $key=>$val)
{
$offer_id = $dataicube['response']['data'][0]['Thumbnail']["$key"]['offer_id'];
$display = $dataicube['response']['data'][0]['Thumbnail']["$key"]['display'];
$filename = $dataicube['response']['data'][0]['Thumbnail']["$key"]['filename'];
$url = $dataicube['response']['data'][0]['Thumbnail']["$key"]['url'];
$thumbnail = $dataicube['response']['data'][0]['Thumbnail']["$key"]['thumbnail'];
$_filename = mysqli_real_escape_string($db,$filename);
$_url = mysqli_real_escape_string($db,$url);
$_thumbnail = mysqli_real_escape_string($db,$thumbnail);
$sql[] = '("'.$offer_id.'","icube","'.$_thumbnail.'","'.$_url.'")';
}
}
As I store values which have to be inserted in 'sql'
now
$stmt->prepare( "SELECT offer_id FROM " ."affilate_offer_getthumbnail_icube ORDER BY 'offer_id' ASC");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result($offer_id);
$sqlimplode = implode(',', $sql);
if($rows>0)
{
$query = "UPDATE affilate_offer_getthumbnail_icube WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}`
`
Insert query working well,but how can I update all the data like insert query ?
My Answer is refering to a "set and forget"-strategy. I dont want to look for an existing row first - probably using PHP. I just want to create the right SQL-Command and send it.
There are several ways to update data which already had been entered (or are missing). First you should alter your table to set a problem-specific UNIQUE-Key. This is setting up a little more intelligence for your table to check on already inserted data by its own. The following change would mean there can be no second row with the same value twice in this UNIQUE-set column.
If that would occur, you would get some error or special behaviour.
Instead of using PHPMyAdmin you can use this command to set a column unique:
ALTER TABLE `TestTable` ADD UNIQUE(`tablecolumn`);
After setting up your table with this additional intelligence, you alter your Insert-Command a little bit:
Instead of Insert you can drop and overwrite your Datarow with
REPLACE:
$query= "REPLACE INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100) VALUES (".$sqlimplode.")";
See: Replace Into Query Syntax
Secondly you can do this with the "On Duplicate Key"-Commando.
https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
$query= "INSERT INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100)
VALUES (".$sqlimplode.")
ON DUPLICATE KEY UPDATE net_provider = ".$newnetprovider.",
logo2020 = ".$newlogo2020.",
logo100 = ".$newlogo100.";";
Note: I think you missed some ( and ) around your $sqlimplode. I always put them around your implode. Maybe you are missing ' ' around strings as well.
Syntax of UPDATE query is
UPDATE table SET field1 = value1, field2 = value2 ...
So, you cannot pass your imploded array $sql to UPDATE query. You have to generate another sql-string for UPDATE query.
This is clearly incorrect:
$query = "UPDATE affilate_offer_getthumbnail_icube
WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
If the intention is to INSERT offer_id='".$offer_id."' and then UPDATE ... SET offer_id = '".$sqlimplode."'";
You have to use two separate queries, one for INSERT and then another one for UPDATE
An Example:
$query = "INSERT INTO affilate_offer_getthumbnail_icube
(col_name) VALUES('".$col_Value."')";
//(execute it first);
$query2 = "UPDATE affilate_offer_getthumbnail_icube SET
col_name= '".$col_Value."'" WHERE if_any_col = 'if_any_Value';
//(execute this next);
Try this:
$sqlimplode = implode(',', $sql);
if($rows>0)
{
/*$fields_values = explode(',',trim(array_shift($sql), "()"));
$combined_arr = array_combine(['offer_id','net_provider','logo2020','logo100'],$fields_values);
$sqlimplode = implode(', ', array_map(function ($v, $k) { return $k . '=' . $v; }, $combined_arr, array_keys($combined_arr))); */
$query = "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode." ON duplicate key update net_provider = values(net_provider),logo2020 = values(logo2020),logo100 = values(logo100)";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$sqlimplode = implode(',', $sql);
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}

Update table using variables

I want to update a table using a array but I can't get it to work. It inserts the date in the table but the update query doesn't work.
<?php
session_start();
$dateinsert = $_SESSION['aanwezigheidsdatum'];
$nameninsertarr = $_SESSION['namen'];
for ($i =2 ; $i<$_SESSION['totaalpersoneel'];$i++){
$test = $_GET["ureninsert".$i];
if ($test == ""){$test = X;}
$ureninsertarray[$i-2] = $nameninsertarr[$i-2]." = '".$test."'";
}
$ureninsertarr = implode(' , ',$ureninsertarray);
echo $ureninsertarr;
include("connectdb.php");
$query = "INSERT INTO Aanwezigheidslijst (dag) VALUES ('$dateinsert')";
mysql_query($query);
$query = "UPDATE 'Aanwezigheidslijst' SET $ureninsertarr WHERE dag = '$dateinsert'";
echo "<br>".$query;
$putquery = mysql_query($query);
if (!$putquery) echo "error";
?>
thats because u have written update syntax wrong.u have to specify column name in 'set'.fix this issue and ur update query will work.
$query = "UPDATE Aanwezigheidslijst
SET column_name=$ureninsertarr
WHERE dag = $dateinsert";
update syntax:
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
$query = "UPDATE 'Aanwezigheidslijst' SET $ureninsertarr WHERE dag = '$dateinsert'";
should be changed in
$query = "UPDATE `Aanwezigheidslijst` SET $ureninsertarr WHERE dag = '$dateinsert'";
But should use another way to talk with your database. (PDO?)
In PDO it would look like
$stmt = $dbh->prepare("UPDATE `Aanwezigheidslijst` SET $ureninsertarr WHERE `dag` = ?");
$dbh->execute(array($dateinsert));
You should also take care or params used in $ureninsertarr. Getting them directly from $_GET means that you don't really know what is beeing inserted into you DB. (!SQL Injection!)
PDO Manual
EDIT: as posted before, $ureninsertarr needs to be a string that also cointains the columns nam. Not only the values...

Categories