Hey I have an online database which needs to be populated with sensor values periodically. There are 7 variables(columns) coupled with a timestamp column to make each row of the table. Problem is these variables are pushed a few at a time with the rest as 0. Now I'm coding an algo which will only insert a row if all values of latest row (by timestamp) are filled completely(not 0), else it will update the latest row.
Here's my PHP code for one of the insert php files which inserts 3 variables at a time - temp, pressure and altitude.
<?php
// Prepare variables for database connection
$dbusername = "uxpertla_terr"; // enter database username, I used "arduino" in step 2.2
$dbpassword = "abc123"; // enter database password, I used "arduinotest" in step 2.2
$server = "localhost";
// Connect to your database
$dbconnect = mysqli_connect($server, $dbusername, $dbpassword);
// Prepare the SQL statement
$sdl = "SELECT * FROM uxpertla_test_db.testt ORDER BY time DESC LIMIT 1";
$snd=mysqli_query($sdl);
$row = mysqli_fetch_array($snd,MYSQLI_ASSOC);
if($row)
{
if($row['Temperature']==0||$row['Pressure']==0||$row['Humidity']==0||$row['Light']==0)
{
$sql = "UPDATE uxpertla_test_db.testt
SET temp='".$_GET["value"]."',
pressure='".$_GET["value2"]."',
altitude='".$_GET["value3"]."'
WHERE time=".strtotime($row['time'])."";
}
else
$sql = "INSERT INTO uxpertla_test_db.testt
(temp,pressure,altitude) VALUES('".$_GET["value"]."', '".$_GET["value2"]."','".$_GET["value3"]."')";
}
else
$sql = "INSERT INTO uxpertla_test_db.testt
(temp,pressure,altitude) VALUES('".$_GET["value"]."', '".$_GET["value2"]."','".$_GET["value3"]."')";
// Execute SQL statement
mysqli_query($sql);
?>
Sorry if the code's not pretty, but I need help with the where clause of update query in the second if block..
Figured out the answer.. :p
<?php
// Prepare variables for database connection
$dbusername = "uxpertla_terr"; // enter database username, I used "arduino" in step 2.2
$dbpassword = "abc123"; // enter database password, I used "arduinotest" in step 2.2
$server = "localhost";
// Connect to your database
$dbconnect = mysqli_connect($server, $dbusername, $dbpassword);
$sdl = "SELECT * FROM uxpertla_test_db.testt ORDER BY time DESC LIMIT 1";
$snd=mysqli_query($dbconnect,$sdl);
$row = mysqli_fetch_array($snd,MYSQLI_ASSOC);
if($row['Temperature']==0||$row['Pressure']==0||$row['Humidity']==0||$row['Light']==0)
{
$sql = "UPDATE uxpertla_test_db.testt
SET temp='".$_GET["value"]."',
pressure='".$_GET["value2"]."',
altitude='".$_GET["value3"]."'
ORDER BY time DESC LIMIT 1";
}
else
$sql = "INSERT INTO uxpertla_test_db.testt
(temp,pressure,altitude) VALUES('".$_GET["value"]."', '".$_GET["value2"]."','".$_GET["value3"]."')";
// Execute SQL statement
mysqli_query($dbconnect,$sql);
?>
Related
Not sure if this is even possible, I am trying to get it to where "ItemA" has a value of 100 in the database. Which I have assigned a value to problem, what I really want is if a user inputs 50 into an input field, that "ItemA" value will now show 150 when it is called back in a select query. I am unsure of how to add the value in a column and a users input together.
I am new to PHP and SQL, so please forgive me. Any help is greatly appreciated and I thank you for your time!
The PHP that I have:
<?
$payout = $_POST["payout"];
$payouts = $_GET["payout"];
$withdraw = $_POST["bank_withdraw"];
$cashspent = $_POST["cash_spent"];
$servername = "localhost";
$username = "*****";
$password = "*****";
$db = "*****";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error){
die("Connection failed: ". $conn->connect_error);
}
$sql = "UPDATE finances SET payout = '$payouts' + ? WHERE finance_id = 1";
$stmt = mysqli_stmt_init($conn);
if ( ! mysqli_stmt_prepare($stmt, $sql)){
die(mysqli_error($conn));
}
mysqli_stmt_bind_param($stmt, "ii",
$payout,
$payouts
);
mysqli_stmt_execute($stmt);
In this example, I am trying to have it where a user is able to add the two values from what is already in the database.
Item in database (payout) = 100
Input from user = 50
Item from database + input from user = 150, showing in database
if I understand your question correctly there are 2 parts:
Select payout from database and add it to the user input.
update the value in the database
For 1) select the payout from the database $select_sql = "SELECT payout FROM finances WHERE finance_id = 1"; and you could use a variable such as $increasedPayout and assign this new variable $increasedPayout = $payouts + $select_sql;
and then for 2) use the $increasedValue variable in your SQL UPDATE statement.
$sql = "UPDATE finances SET payout = '$increasedPayout' WHERE finance_id = 1";
I'm creating a signup form and am onto the confirmation email part. I want to find all values associated with one other value in a database.
Ex. I get the "key" that is in the URL, then want to find all the values associated with it. In my database there are 4 columns: STR (the key), USERNAME, PASSWORD, and EMAIL. If I get STR I want to get the username, password, and email that are in the same row as the key and then insert it into another table in the same database.
verify.php:
<?php
$username = $_GET['username'];
$password = $_GET['password'];
$email = $_GET['email'];
$servername = "localhost";
$user = 'usernamelol';
$pass = 'passwordlol';
$dbname = 'vibemcform';
$str = $_GET['str'];
$conn = new mysqli($servername, $user, $pass, $dbname);
/* The variable query gets the "key" from the dont database. I want to compare that value with the other values associated with it. Ex. the variables in the same row as the key. */
$query = mysqli_query($conn, "SELECT * FROM `dont` WHERE STR='".$key."'");
/* Below is my attempt. Feel free to change whatever you want. */
$sql = "SELECT USERNAME, PASSWORD, EMAIL FROM dont";
$result = $conn->query($sql);
if (!$query) {
die('Error: ' . mysqli_error($con));
}
if (mysqli_num_rows($query) > 0) {
if ($result -> num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$sqltwo = "INSERT INTO data (USERNAME, PASSWORD, EMAIL) VALUES ($row["USERNAME"], $row["PASSWORD"], $row["EMAIL"])";
}
}
}
echo 'Successfully verified your email!'; exit;
?>
Why not simpy use the insert ... select syntax?
insert into data(username, password, email)
select username, password, email from dont where str = :key
You can run this query right ahead, and then check how many rows were affected:
If no row was affected, then it means that the select did not bring a row back: so the :key was not found in the database
If a row was affected, then the key was found and the executed row was inserted
Note that you should use parametrized queries so your code is safe from SQL injection (and more efficient as well); recommended reading How can I prevent SQL injection in PHP??
I have an url as domain.com/abc?orderstatus=cancel
Now, when someone reaches this link, I want to run a query that deletes the last record from the database.
So this is what I tried:
<?php
// Code here for the way to connect to database and insert records which works
// Now I added this code so that only if its on the domain.com/abc?orderstatus=cancel url, it will delete the last record.
$orderstatus = $_GET['orderstatus'];
if($orderstatus == 'cancel') {
$sql3 = "delete from table order by CustomerID desc limit 1";
}
?>
However, this is not working for me. May I know what am I doing wrong?
ps: I tried to cut out as many sql codes which work so that it makes reading easy. If there is any info that I am missing, please do let me know and I'll put it in.
You can use MAX() for MySQL if you have autoincremented on the ID or whatever. MAX() will delete the highest number on the field you specify.
$sql3 = "DELETE FROM table_name
WHERE CustomerID = (SELECT x.id FROM (SELECT MAX(t.CustomerID) AS id FROM table_name t) x)";
//Execute that query
$query3 = mysqli_query($db_conn, $sql3);
If you want to perform DELETE on the basis of ORDER BY then you may have to write nested query. You will get a SQL syntax error if you go with delete from table order by CustomerID desc limit 1
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$orderstatus = $_GET['orderstatus']; // check for sql injections or XSS
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM {YOUR TABLE_NAME} WHERE {YOUR WHERE CLAUSE} ";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
Good day,
I have a problem and i dont know how to do a Counting id number instead of random numbers, please help me. Thank you.
My codes working on random id, but i want it in Counting number ID. Thanks
<?php
$hostname_conn = "localhost";
$database_conn = "user_id";
$username_conn = "root";
$password_conn = "";
$conn = mysql_pconnect($hostname_conn, $username_conn, $password_conn) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_conn,$conn);
// run an endless loop
while(1) {
$randomNumber = mt_rand(10, 100);// generate unique random number
$query = "SELECT * FROM tblrand WHERE the_number='".mysql_real_escape_string ($randomNumber)."'"; // check if it exists in database
$res =mysql_query($query,$conn);
$rowCount = mysql_num_rows($res);
$id=$randomNumber;
// if not found in the db (it is unique), then insert the unique number into data_base and break out of the loop
if($rowCount < 1) {
$con = mysql_connect ("localhost","root");
mysql_select_db("user_id", $con);
$sql = "insert into tblrand(the_number) values('".$randomNumber."')";
mysql_query ($sql,$con);
mysql_close ($con);
break;
}
}
echo "IT-FORM" .$id;
?>
CASE 1: id generated by server-side
At server side, configure mysql database to generate sequential unique id. Add a field in your
table with auto-increment
https://dev.mysql.com/doc/refman/5.7/en/example-auto-increment.html as suggested by
#Londeren
Client side just manage insert query to save data in database (not ids, just data related to ids).
Generally this solution is preferable: even if you have many clients, the database will manage all
the query methodically and efficiently.
CASE 2: id generated by client-side (not preferable, use CASE 1 if possible. Included this in
the answer because your question started from here)
You get the last id from database, generate a new one (last id + 1), and insert new id in the
database.
Client side manage select id query, generate new id, and insert query. You take the
risk that other clients generate the same id simultaneously and insert it in the database.
Supposing at server-side is everything ok, code at client-side could be this:
<?php
$hostname_conn = "localhost";
$database_conn = "user_id";
$username_conn = "root";
$password_conn = "";
$conn = mysql_pconnect($hostname_conn, $username_conn, $password_conn) or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_conn,$conn);
// run an endless loop
$count=1;
while(1) {
$query = "SELECT * FROM tblrand WHERE the_number='".mysql_real_escape_string
($count)."'"; // check if it exists in database
$res =mysql_query($query,$conn);
$rowCount = mysql_num_rows($res);
// if not found in the db (it is unique), then insert the unique number into data_base and break
out of the loop
if($rowCount < 1) {
$con = mysql_connect ("localhost","root");
mysql_select_db("user_id", $con);
$sql = "insert into tblrand(the_number) values('".$count."')";
mysql_query ($sql,$con);
mysql_close ($con);
$count++;
break;
}
}
echo "IT-FORM" .$count;
?>
This question already has answers here:
php/mysql with multiple queries
(3 answers)
Closed 3 years ago.
I've a doubt with mysqli_query..
this is a part of my code:
$con = db_connect();
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
$result = mysqli_query($con, $sql);
return $result;
I can't do the query...
If I try to do a query like this:
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
It works.
What's the problem?? I can't use SET with mysqli_query?
Thanks
You can not execute multiple queries at once using mysqli_query but you might want to use mysqli_multi_query as you can find out in the official documentation:
http://www.php.net/manual/en/mysqli.multi-query.php
Lets start with creating a working php script.
<?php
// replace for you own.
$host ="";
$user = "";
$password = "";
$database = "";
$con= mysqli_connect($host, $user, $password, $database);
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
// Begin SQL query
$sql = "SELECT * FROM users";
$result = mysqli_query($con,$sql) OR Die('SQL Query not possible!');
var_dump($result);
return $result;
var_dump($result);
// End SQL query
mysqli_close($con);
};
?>
INSERT query:
$sql= "INSERT INTO categorias(name) VALUES ('ssss')";
mysqli_query ($con,$sql) OR Die('SQL Query not possible!');
UPDATE and DELETE query:
$sql= "DELETE FROM users WHERE username = 'Hola';";
$sql.= "UPDATE users SET foreign_key_checks = 0 WHERE username = 'Hola'"; /* I made a guess here*/
mysqli_multi_query ($con,$sql) OR Die('SQL Query not possible!');
Check the SET query. I think something is missing. I have changed it to what I think was your aim.
The connection should be established like this:
$Hostname = "Your host name mostly it is ("localhost")";
$User = "Your Database user name default is (root)"//check this in configuration files
$Password = "Your database password default is ("")"//if you change it put the same other again check in config file
$DBName = "this your dataabse name"//that you use while making database
$con = new mysqli($Hostname, $User , $PasswordP , $DBName);
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
In this query:
put categorias in magic quotes(`) and column names also
For your next query do this:
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
Change to:
$sql= "SET foreign_key_checks = 0; DELETE FROM `users` WHERE `username` = 'Hola'";