php Update sql and Query - php

I want to do a query in php, output the data on the page and then modify it in the database.
How do I do that?
Currently I do it like this but it dose not work:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM pics WHERE id = '$id'";
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
$dir = $row["dir"];
$likes = $row["likes"];
}
$sqlq = "UPDATE pics SET likes='$likes+1' WHERE id='$id'";
$conn->query($sqlq);
$conn->close();
But the like dose not add to the database.

If you echo your $sqlq out using
echo $sqlq;
you'll see that the '$likes+1' isn't doing what you expect.
You could really simplify it by doing
$sqlq = "UPDATE pics SET likes=likes+1 WHERE id='$id'";
which removes any risk of two users updating the database at teh same time overwriting each other.
But you should really check out using "parameterized queries" as that would solve all your problems (and may your queries safer). Check the examples in the manual http://php.net/manual/en/mysqli-stmt.bind-param.php

Related

Delete last record only when a certain URL is present

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();
?>

Updated a MySQL table with PHP

This seems so easy. My code checks out, and even if I run the resetting fuction in phpMyAdmin it works, but for some reason the table never updates when I run the php.
<?php
$servername="localhost" ;
$username="***" ;
$password="***" ;
$dbname="***" ;
$conn=new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `Alert` FROM `poonpad_daveAlert` WHERE 1";
$result = $conn->query($sql);
if ($result == 1) {
echo "wow, stuff is happening. resetting."; resetting();
} else {
echo "this place is dead";
}
function resetting() {
$sql = "UPDATE `poonpad_daveAlert` SET `Alert`=2 WHERE 1";
}
$conn->close();
?>
First, I'd use the below to execute the query.
$result = mysqli_query($conn,$sql);
Second, instead of (result==1) which I'm not sure is intended for what purpose, you should use (mysqli_num_rows($result)>0).
Third, for the resetting function, I think you need to mention the column name for the WHERE condition which you set to 1 as well as the main $sql query, and you don't need the WHERE if you have to select all rows.
"UPDATE `poonpad_daveAlert` SET `Alert`=2 WHERE [column-name]=1";

Issue with JOIN in PHP MySQL

Having a bit of a struggle here with adding JOINs to a query. I am connecting to two separate databases (on the same server). For this reason, I am writing this mysqli simply and will convert to a prepared statement once it's working.
// REMOVED: DB VARIABLES
$conn = new mysqli($servername, $username, $password, $db_connective_data);
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
$conn2 = new mysqli($servername, $username, $password, $db_resources);
if ($conn2->connect_error) { die("Connection failed: " . $conn2->connect_error); }
$sql = "SELECT * FROM downloads LEFT JOIN resource_data ON downloads.resource_id_REF=resource_data.resource_id WHERE downloads.user_basics_id_REF='$user_id'";
$result = $conn->query($sql);
$number_of_download_rows_returned = mysqli_num_rows($result) -1;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$resource_id_REF[] = $row['resource_id_REF'];
$download_date[] = date('Y-m-d', strtotime($row['download_date']));
$resource_title[] = $row['resource_title'];
$resource_title_link[] = str_replace(" ", "-", $row['resource_title']);
}
}
$conn->close();
A query without a JOIN works fine (albeit without returning the resource_title):
$sql = "SELECT * FROM downloads WHERE downloads.user_basics_id_REF='$user_id' ORDER BY downloads.download_date DESC";
What am I missing here? The first code sample will return no results. The second one will return three.
Any assistance is greatly appreciated.
Here is a list of the different database names that I reference. As I stated, some data is in the "connective_data" db and some is in the "resources" db.
$db_connective_data = "connective_data";
$db_lists = "lists";
$db_messaging = "messaging";
$db_resources = "resources";
$db_users = "users";
I can't seem to get two of them connected. Am I missing something strikingly obvious here?
There is no need to create 2 connections if the databases are located on the same mysql server. You can simply reference tables from another database as databasename.tablename.
As a result, you can join 2 tables from 2 different databases as:
$sql = "SELECT * FROM yourdatabase1.downloads LEFT JOIN yourdatabase2.resource_data ON yourdatabase1.downloads.resource_id_REF=yourdatabase2.resource_data.resource_id WHERE yourdatabase1.downloads.user_basics_id_REF='$user_id'";
Obviously, you need to substitute your real database names for yourdatabase1 and yourdatabase2 in the above query.
Update: Are you sure you need so many databases? These seem to be tables to me, not databases.

Simple and effective way to echo the result of a query in PHP?

I'm new to MySQL and PHP and I m struggling to echo my queries (the results not the text!)
I have searched for this but nothing seems to work properly, the best I managed to do was echoing the text of the query. I might have some fatal mistakes but here is my code:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db("atoma",$dbhandle)
or die("Could not select atoma");
$sql1 = mysql_query("SELECT (MAX(GRADE)) as maximum FROM thema3");
$r = mysql_fetch_array($sql1); // will return the result
echo $r['maximum'];
$sql2 = "SELECT COUNT(DISTINCT NAME) FROM thema2";
$sql1 = "SELECT AVG(GRADE) FROM thema3";
mysql_close($dbhandle);
?>
I get nothing as a result.
I have these 3 queries and all I want is just to print their results. I've written code for echoing only one of the 3 since the other 2 will be echoed as the first one I want to believe.
Your code seems incorrect because, the connection is mysqli and fetching is using mysql
$conn = new mysqli($servername, $username, $password, $dbname);
....
$sql1 = mysql_query("SELECT (MAX(GRADE)) as maximum FROM thema3");
$r = mysql_fetch_array($sql1); // will return the result
A full example of W3Schools
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
http://www.w3schools.com/php/php_mysql_select.asp
When you use max, avg, etc you pull only one result, so with the $result[0] you has the result you want
Edit:
If you're new, maybe you come to see read this:
http://codular.com/php-mysqli
So A) would leave using an outdated way to call the database, and B) with this in principle bringing the first row you would have the result of AVG, MAX, etc. when only one row which returns you if you make this types of sentences ;)

PHP: mysqli_query is not working [duplicate]

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'";

Categories