session_start();
require 'db-conn.php';
$u1 = $_POST['ricevente'];
$u2 = $_POST['richiedente'];
if(isset($_POST['accetta'])){
$sql = "UPDATE amici SET amicizia=1 WHERE utenteDue='$u2' AND utenteUno = '$u1';";
$sql55 = "INSERT INTO notifiche (idRichiedente, idRicevente, tipoNotifica) VALUES ('$u2', '$u1', '2');";
$result55 = $conn->query($sql55);
$result = $conn->query($sql);
}elseif(isset($_POST['rifiuta'])){
$sql = "DELETE FROM amici WHERE utenteDue='$u2' AND utenteUno = '$u1'";
$result = $conn->query($sql);
}else echo "Si รจ verificato un errore";
This is my code, it only computes the $sql variable while not the $sql55. Can you please tell me why? The variables are fine and just okay (the first query goes well).
You are inserting post data directly into your query instead of using prepared statements, this is highly undesirable.
When should I use prepared statements?
https://www.php.net/manual/en/pdo.prepared-statements.php
But if you must do it this way, you need to concat the values into your query string as such ...
$sql55 = "INSERT INTO notifiche (idRichiedente, idRicevente, tipoNotifica) VALUES ('".$u2."', '".$u1."', '2');";
Related
I am in need of some help, please? I can successfully do a MySQL query using:
IP_Address/fund_list.php?Id_Number=555666
With this below:
$ID = $_GET['Id_Number'];
$sql = "SELECT * FROM fund_list WHERE Number = ".$ID;
Now I want to use 2 different things in my web call. Like:
IP_Address/fund_list.php?Id_Number=555666&Name=Billy
But I don't know how to write the 'get' line below.
$ID = $_GET['Id_Number'] & $Name = $_GET['Name']; <-- Does not work
I would think the SQL select statement would be:
$sql = "SELECT * FROM fund_list WHERE TheNumber = .$ID AND TheName = .$Name";
All the things I look up online, the syntax is overly confusing, I can't dissect it and make something work. Thank you.
To start with you should really be preparing your statements, passing data directly from a query string into a SQL query is really dangerous. You should also avoid using * in your SELECTs if you insist on not preparing them.
Your issue in this case is you need '' around TheName =
$sql = "SELECT * FROM fund_list WHERE TheNumber = {$ID} AND TheName = '{$Name}'";
Regardless, what you should be doing is this:
$sql = "SELECT Param1, Param2 FROM fund_list WHERE TheNumber = ? AND TheName = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("is", $ID, $Name);
$stmt->execute();
$stmt->bind_result($param1, $param2);
while($stmt->fetch()) {
//Your code
}
That code prevents SQL injection attacks, and a number of other potential issues you can create not using PDO or mysqli prepared statements.
Edit per request:
$ID = $_GET['Id_Number'];
$Name = $_GET['Name'];
$sql = "SELECT * FROM fund_list WHERE TheNumber = {$ID} AND TheName = '{$Name}'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
//your code
}
You need '' when comparing string parameters in SQL.
Have you tried doing this? This always works to me
$ID = $_GET['Id_Number'];
$Name = $_GET['Name'];
I have an issue with MySQLi and PHP.
I created a form, and once I type the desired values in and hit submit, the values are right away sent to the database. Nothing wrong with this.
What I want to happen is that: after hitting the submit button, PHP shall echo the result of the just-submitted entry. That is to say:
`INSERT INTO table VALUES (x, x, y) -> SELECT x, x, y FROM table ORDER BY id DESC LIMIT 1`
I have tried many methods to do this, but all of them either echo the previous entry (the one before the one just submitted) or plainly don't work.
I have tried mysqli_insert_id($conn) but this returns nothing.
This is where my code rests at at the moment:
$conn = mysqli_connect($server, $user, $pw, $BD);
if (!$conn) {
die ('<span style="color: #FF0000;">"connection failed: "</span>' . mysqli_connect_error());
}
$nome = $_POST['nome'];
$preco = $_POST['preco'];
$query = "INSERT INTO produtos(nome, preco) VALUES ('$nome', '$preco')";
$result = mysqli_insert_id($conn);
var_dump ($result);
if (mysqli_query($conn, $query)){
echo '<br>'."Succeeded!";
} else {
echo '<br>'."ERROR!" .'<br>'. $query ."<br>". mysqli_error($conn) .'<br><br>'. '<span style="color: #FF0000;">You have to fill all the fields.</span>';
}
mysqli_close($conn);
to note, if of any help, var_dump outputs int(0) at the moment.
Thanks in advance. I've been struggling like mad with this.
You can't get mysqli_insert_id without executing the query. Better use prepare statement to prevent from sql injection
$stmt = $conn->prepare("INSERT INTO produtos(nome, preco) VALUES (?,?)");
$stmt->bind_param('ss', $nome, $preco);
$stmt->execute();// execute query
$conn->insert_id;// get last insert id
Please see that you haven't even executed your query. On a side note, you should be aware of SQL injections and follow the below pattern:
$nome = mysqli_real_escape_string($conn, $_POST['nome']);
$preco = mysqli_real_escape_string($conn, $_POST['preco']);
$sql = "INSERT INTO produtos (nome, preco) VALUES ('".$nome."', '".$preco."')";
$query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$result = mysqli_insert_id($conn);
echo $result; // Check your result.
Use this:
$query = "INSERT INTO produtos(nome, preco) VALUES ('$nome', '$preco')";
$res=mysqli_query($conn,$query);
$result = mysqli_insert_id($conn);
var_dump ($result);`
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();
}
I'm having a problem with inserting info into the database. Strangely the update query works but not the insert query. I don't get any error either when submitting, it goes through correctly and echo account saved but nothing is inserted. What am i missing or doing wrong. please assist
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
This is because the INSERT command has different syntax:
INSERT into accounts SET $qpart "
is not usual, you can write it like this:
INSERT into accounts (column names) VALUES your values"
13.2.5 INSERT Syntax
You have double if(!$err){. Do you want both (!$err) into one? If the first (!$err) is for indicator for the second to insert, function SELECT can not be placed above the function INSERT indirectly.
try this:
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
// if(!$err){ again ...
if(!$accountid){
$q = "INSERT into accounts SET (column1) VALUES ($var1)";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}
else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
}
else{
//other code to handle if ($err)
}
Note: I would prefer using PDO to handle database, it's so simple scripting, besides, it's no longer supported
You have to understand that mysql functions have become deprecated. Either using mysqli or pdo would be the better option, but if you absolutely have to use mysql as a solution i would suggest not posting the form to itself, rather post to another php file as you will have less problems.In my environment it seems to work well as an interim solution while we are rewriting everything to use mysqli.If it a go and let me know.
I'm trying to retrieve the last id number inserted with mysql_insert_id() but always return 0, my id field is auto increment so I don't know why it returns 0 thanks. please help
include 'C:\xampp\htdocs\Student_evaluation\functions.php';
if(!loggedin())
{
header("Location: http://localhost/dev/userarea.php");
exit();
}
if(isset($_POST['submit']))
{
//get data
$name = $_POST['name'];
$f_lastname = $_POST['f_lastname'];
$second_lastname = $_POST['second_lastname'];
$student_number = $_POST['student_number'];
$semester_year = $_POST['semester_year'];
$course = $_POST['course'];
$section = $_POST['section'];
$grade = $_POST['grade'];
$student_perform = $_POST['student_perform'];
$comment_box = $_POST['comment_box'];
$sql = "INSERT INTO `students`(`name`, `first_lastname`, `second_lastname`, `numero_estudiante`, `semester`, `course`, `section`, `f_grade`, `students_perform`, `comments`)
VALUES ('$name','$f_lastname','$second_lastname','$student_number','$semester_year','$course','$section','$grade','$student_perform','$comment_box')";
$con = mysqli_connect("localhost","root","","rememberme");
$result = mysqli_query($con, $sql);
echo "ID of last inserted record is: " . mysql_insert_id();
}
You're using one library (mysqli) to perform the query, then another (mysql) to obtain the auto-increment ID. That can't work. Among other issues, you haven't even connected to the database with the second library!
Consistently use mysqli or, better yet, PDO, which will help you plug your blinding security flaw.
You should do something like this (using mysqli_insert_id):
$con = mysqli_connect("localhost","root","","rememberme");
$sql = "INSERT INTO ...";
$result = mysqli_query($con, $sql);
echo "ID of last inserted record is: " . mysqli_insert_id($con);
mysql_insert_id and mysqli_insert_id are both different and you are using mysqli so use mysqli_insert_id instead of mysql_insert_id and it's better to use mysqli instead of mysql.