I have 2 queries. Query #1 updates some things in the database, and Query #2 inserts some data into the table.
Code:
function add_like($id) {
$connection = new mysqli($host, $username, $password, $database);
$id = $connection->real_escape_string($id);
$query = $connection->query("UPDATE `posts` SET `post_likes` = `post_likes` + 1 WHERE `id` = '$id'");
$likes_query = $connection->query("INSERT INTO `likes` VALUES (".$_SESSION['user_login'].", $id)");
}
The first query ($query) should add 1 like to the database. So starting at 0 it should +1. Instead, it does +12.
The second query ($likes_query) does not INSERT INTO likes.
Any help would be much appreciated. Thanks!
UPDATE:
Changed the second query to:
$likes_query = $connection->query("INSERT INTO `likes` (`user_id`, `post_id`) VALUES ('$user', '$id')");
Final code:
function add_like($id) {
if (isset($_SESSION['user_login'])) {
$user = $_SESSION["user_login"];
}
else {
$user = "";
}
$connection = new mysqli($host, $username, $password, $database);
$id = $connection->real_escape_string($id);
$query = $connection->query("UPDATE `posts` SET `post_likes` = `post_likes` + 1 WHERE `id` = '$id'");
$likes_query = $connection->query("INSERT INTO `likes` (`user_id`, `post_id`) VALUES ('$user', '$id')");
}
All issues fixed. Thanks for all your comments!
Related
we have use this below code to avoid to insert dublicate entery in our databse
but in some case it's not working
$device_id = $_REQUEST['device_id'];
$fcm_id = $_REQUEST['fcm_id'];
$model_number = $_REQUEST['model_number'];
$os_version = $_REQUEST['os_version'];
$app_version = $_REQUEST['app_version'];
$created = round(microtime(true) * 1000);
if(isset($device_id)){
$exist = mysqli_query($con, "SELECT * FROM `user` WHERE `device_id`='$device_id'");
if(mysqli_num_rows($exist)>0){
mysqli_query($con, "UPDATE `user` SET `fcm_id`='$fcm_id', `topics`=0 WHERE `device_id`='$device_id'");
}
else{
mysqli_query($con, "INSERT INTO `user` (`device_id`, `fcm_id`, `model_number`, `os_version`, `created`) VALUES ('".$device_id."', '".$fcm_id."', '".$model_number."', '".$os_version."', '".$created."')");
}
try with this
$device_id = $_REQUEST['device_id'];
$fcm_id = $_REQUEST['fcm_id'];
$model_number = $_REQUEST['model_number'];
$os_version = $_REQUEST['os_version'];
$app_version = $_REQUEST['app_version'];
$created = round(microtime(true) * 1000);
if(isset($device_id))
{
$qry="UPDATE `user` SET `fcm_id`='$fcm_id', `topics`=0 WHERE EXISTS (SELECT * FROM `user` WHERE `device_id`='$device_id')";
if(!mysqli_query($con,$qry)){ mysqli_query($con, "INSERT INTO `user` (`device_id`, `fcm_id`, `model_number`, `os_version`, `created`) VALUES ('".$device_id."', '".$fcm_id."', '".$model_number."', '".$os_version."', '".$created."')");
}
Try this
$device_id = $_REQUEST['device_id'];
$fcm_id = $_REQUEST['fcm_id'];
$model_number = $_REQUEST['model_number'];
$os_version = $_REQUEST['os_version'];
$app_version = $_REQUEST['app_version'];
$created = round(microtime(true) * 1000);
if(isset($device_id)){
$stmt = $con->prepare("INSERT IGNORE INTO `user` (`device_id`, `fcm_id`,
`model_number`, `os_version`, `created`) VALUES (?, ?, ?,?,?)");
$stmt->bind_param($device_id, $fcm_id, $model_number, $os_version, $created );
if ($stmt->execute()) {
}
$stmt->close();
}
Update: Add to your tabekl following index,
But you should think about what you put in the index.
because only when all 4 Columns are identical, no new entry will be crated.
CREATE UNIQUE INDEX idx_insert_user
ON user (`device_id`, `fcm_id`,
`model_number`, `os_version`);
the insert ignore into will not enter duplicates into the table
For stoping the duplicate data on row from mysql database on insert query:
MySQL INSERT IGNORE statement
For update case you need to put your condition for duplicate handling.
After learning how to setup a environment with html, js, ajax, php and mysql I'm able to insert single instances into a table.
I'm trying to get it working with multiple entries into the table for quite a while now. I was reading several documentation pages and recommendations on here but couldn't really figure out what I'm missing.
To clarify: What I'm trying to do is to insert 2 of the same entity. I input SafetyStock and LotSize of the Material Pack thereupon, insert another Material named PET with different
There is no problem with getting the variables from ajax but i don't get the $stmt->bind_param line. What do I have to write there to make the code running?
I tried to just have two lines of stmt binding, but then it only wrote the last entry into the database. Another thing I did was execute the stmt and then overwrite the variables and then do execute again, wasn't working as well.
my actual insert.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "scm";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind settingssupplychaincomponents
$stmt = $conn->prepare("INSERT INTO test1 (settingsSupplyChainComponentsId, settingsSupplyChainId, componentId, safetyStockW, lotSizeW)
VALUES (?, ?, ?, ?, ?), (?, ?, ?, ?, ?)");
$stmt->bind_param("iiiii", $settingsSupplyChainComponentsId, $settingsSupplyChainId, $pack, $sspack, $lspack); //Pack
// set parameters for components
$settingsSupplyChainComponentsId = '';
$settingsSupplyChainId = $_POST['ssci'];
// set parameters for pack
$pack = 1;
$sspack = $_POST['sspack'];
$lspack = $_POST['lspack'];
// set parameters for PET
$pet = 2;
$sspet = $_POST['sspet'];
$lspet = $_POST['lspet'];
$values = array();
$stmt->execute($values);
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
you'll need to repeat the variables that should be inserted in both rows.
$stmt->bind_param("iiiiiiiiii",
$settingsSupplyChainComponentsId, $settingsSupplyChainId, $pack, $sspack, $lspack,
$settingsSupplyChainComponentsId, $settingsSupplyChainId, $pet, $sspet, $lspet);
I had this problem, there was no way of doing multiple entries, instead I used several $stmt, below is an example:
$sql = "SELECT TOP 1 SALDOS_DEUDA.FECHA_SALDOS FROM [dbo].[SALDOS_DEUDA]
WHERE FECHA_SALDOS = (SELECT MAX(FECHA_SALDOS) FROM dbo.SALDOS_DEUDA);";
$sql1 = "SELECT SUM(SALDO_DEUDA) / 1000000 AS SALDO_TOTAL FROM SALDOS_DEUDA
WHERE FECHA_SALDOS = (SELECT MAX(FECHA_SALDOS) FROM dbo.SALDOS_DEUDA);";
$sql2 = "SELECT (SUM(CASE WHEN TIPO_DEUDA = 'E' THEN SALDO_DEUDA ELSE 0 END) / SUM(SALDO_DEUDA)) AS PORCENTAJE_EXTERNO FROM SALDOS_DEUDA
WHERE FECHA_SALDOS = (SELECT MAX(FECHA_SALDOS) FROM dbo.SALDOS_DEUDA);";
$sql3 = "SELECT SUM(MONTO) AS TASA_FIJA FROM dbo.RIESGO_MERCADO_TASA
WHERE ANIO = (SELECT MAX(ANIO) FROM dbo.RIESGO_MERCADO_TASA)
AND MES = (SELECT MAX(MES) FROM dbo.RIESGO_MERCADO_TASA
WHERE ANIO = (SELECT MAX(ANIO) FROM dbo.RIESGO_MERCADO_TASA) )
AND TIPOTASA_ID = 1;";
$sql4 = "SELECT SUM(MONTO) AS MONEDA_LOCAL FROM dbo.RIESGO_MERCADO_TASA
WHERE ANIO = (SELECT MAX(ANIO) FROM dbo.RIESGO_MERCADO_TASA)
AND MES = (SELECT MAX(MES) FROM dbo.RIESGO_MERCADO_TASA
WHERE ANIO = (SELECT MAX(ANIO) FROM dbo.RIESGO_MERCADO_TASA) )
AND MONEDA_ID = 13;";
$sql5 = "SELECT (SUM(P.PROMEDIO * P.SALDO) / SUM(SALDO)) AS CPP
FROM dbo.PROMEDIO_PONDERADO P
INNER JOIN dbo.CG_CATEGORIA_PONDERADO C ON P.CATEGORIA_ID = C.CATEGORIA_ID
WHERE FECHA = (SELECT MAX(FECHA) FROM dbo.PROMEDIO_PONDERADO)
AND C.TIPO = 1;";
$stmt = sqlsrv_query( $conn, $sql);
$stmt1 = sqlsrv_query( $conn, $sql1);
$stmt2 = sqlsrv_query( $conn, $sql2);
$stmt3 = sqlsrv_query( $conn, $sql3);
$stmt4 = sqlsrv_query( $conn, $sql4);
$stmt5 = sqlsrv_query( $conn, $sql5);
I am reading a book on PHP, MYSQL, JAVASCRIPT and JQUERY. While reading, I do type the code and see how it worked. I have the following script which I ran to create a table named: "users', and subsequently update the table with two users. When I ran the script in my browser, it only created the new table but failed to update it with the new users. I do not receive any error. Below is the entire script.
<?php // setup_users.php
require_once 'login.php';
$connection = new mysqli($hn, $un, $pw, $db);
if ($connection->connect_error) die($connection->connect_error);
$query = "CREATE TABLE users (
forename VARCHAR(32) NOT NULL,
surname VARCHAR(32) NOT NULL,
username VARCHAR(32) NOT NULL UNIQUE,
password VARCHAR(32) NOT NULL
)";
$result = $connection->query($query);
if (!$result) die($connection->error);
$salt1 = "qm&g";
$salt2 = "ph!#";
$forename = 'Baban';
$surname = 'Sadik';
$username = 'bsadik';
$password = 'babansadik1';
$token = hash('ripemd128', "$salt1$password$salt2");
add_user($connection, $forename, $surname, $username, $token);
$forename = 'Abdullah';
$surname = 'Abubakar';
$username = 'aabubakar';
$password = 'abakar1';
$token = hash('ripemd128', "$salt1$password$salt2");
add_user($connection, $forename, $surname, $username, $token);
function add_user($connection, $fn, $sn, $un, $pw) {
$query = "INSERT INTO users VALUES('$forename', '$surname', '$username', '$token')";
$result = $connection->query($query);
if (!$result) die($connection->error);
}
?>
Where did go wrong please?
You just missed to put column names in the insertion query in add_user function and you are passing undefined variables
Do like this
$query = "INSERT INTO users(forename, surname, username, password)
VALUES('$fn', '$sn', '$un', '$pw')";
Your add_user function has parameters different to what you are trying to use in the query itself.
Change the query to the following:
INSERT INTO users VALUES('$fn', '$sn', '$un', '$pw')
Note that you should use prepared statements instead, as currently the code is susceptible to SQL Injection attacks. If the book you're using doesn't contain information on using prepared statements, scrap the book and find one that does instead.
i need to subtract an mysql update. here is the code:
<?php
session_start();
//=============Configuring Server and Database=======
$host = 'localhost';
$user = 'root';
$password = '';
//=============Data Base Information=================
$database = 'login';
$conn = mysql_connect($host,$user,$password) or die('Server Information is not Correct'); //Establish Connection with Server
mysql_select_db($database,$conn) or die('Database Information is not correct');
//===============End Server Configuration============
//=============Starting Registration Script==========
$username = mysql_real_escape_string($_POST['txtusername']);
//=============To Encrypt Password===================
//============New Variable of Password is Now with an Encrypted Value========
$insert = "UPDATE `users` SET `points` = (`points`-5) WHERE `username` = '".$username."'";
$insert = "UPDATE `users` SET `lodd` = (`lodd` +1) WHERE `username` = '".$username."'";
mysql_query($insert);
header('location: succes.php');
?>
the +1 work perfect but it dont work to -5... how can i do so that they get -5 points?
the +1 work correctly because the query with -5 will never be called as it is overwritten by the query that has +1.
you should have this code, (Although this is not the correct one)
$insert = "UPDATE `users` SET `points` = (`points`-5) WHERE `username` = '".$username."'";
mysql_query($insert);
// other codes
$insert = "UPDATE `users` SET `lodd` = (`lodd` +1) WHERE `username` = '".$username."'";
mysql_query($insert);
follow-up question: what are the dataypes of the two columns? are they unsigned or signed?
You're overwriting the first statement with the second. Try this:
$insert = "UPDATE `users` SET `points` = (`points`-5), `lodd` = (`lodd` +1) WHERE `username` = '".$username."'";
mysql_query($insert);
I need your help, I have a table whith two column, an id and numpos, i want that the id and numops has the same result.
exemple :
$cnx = mysql_connect( "localhost", "root", "" );
$db = mysql_select_db( "maincourante" );
$sql = mysql_query("INSERT INTO ops (id) values('')");
$req = mysql_query("SELECT LAST_INSERT_ID() as id FROM ops");
$data = mysql_fetch_array($req);
$upd = mysql_query("UPDATE `ops` SET `numops`=`idops` WHERE `idops`=$data");
mysql_query($upd, $cnx) or die(mysql_error());
mysql_close();`
thanks for your help
Try this:
This works for mysql:
INSERT INTO ops (`numops`) VALUES ((SELECT LAST_INSERT_ID())+1);
This works for php:
mysql_query("INSERT INTO ops (`numops`) VALUES (0)");
mysql_query("UPDATE ops `numops` ='".mysql_insert_id()."' WHERE `id` = '".mysql_insert_id()."'");
Or
mysql_query("INSERT INTO ops (`numops`) VALUES ('".mysql_insert_id()."')");
// this will only works if there is the same query executed before this.