Get specific information from a database to display on webiste - php

I have got it to call all information I want to show on the website but I actually only need certain data showing such as only things with project id of 1.
I've tried a few different while functions.
//creating connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, user_id, project_id, hours FROM hours_worked";
$result = $conn->query($sql);

Just change your sql query to:
$sql = "SELECT id, user_id, project_id, hours FROM hours_worked WHERE project_id ='".$project_id."';
Change the WHERE clause according to your need.
If you want to display just the records associated with a particular user, then change the WHERE clause to:
WHERE user_id = *ENTER USER ID HERE*

Related

Filtering SQL queries

I'm creating a php query trying to filter from a specific SQL table specific Events.
For example table is called tbl_events and one specific column is showing user ID data let's call it USER_ID
The table has more than 50.000 data lines so if I try and filter it with php it takes TOO much time. So my try is to filter it with SQL before I show the query to the php table and see if it becomes faster.
I want to filter the query in order NOT to show the ones who have an ID let's say "2"
My code is the following (and its obviously not working)
$GetEventsList = GetDataWhere("tbl_events","USER_ID!=2",0);
I'm new in SQL commands so be patient :)
Is this what you're looking for?
Query:
SELECT * FROM tbl_events WHERE USER_ID != '2'
So to implement this with php I would suggest:
$servername = "Your server ip here";
$username = "Database_username_here";
$password = "Database_password_here";
$dbname = "Database_name_here";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM tbl_events WHERE USER_ID != '2'";
// Run $sql content as sql script in db.
$result=$conn->query($sql);

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

Trying to output the richest user in my database through php

I know this is a bit of a rookie question but I'm trying to output the richest user's name on my website.
So my table is called Users
I have Column 1 ('Name') containing the names of all the users, and Column 2 ('Bank') containing their account balance.
I would like to find the richest user and output them on my website.
This is what I've got so far.
while ($row2 = mysqli_fetch_array($sqldataGang, MYSQLI_ASSOC)) {
$sqlgetGang = 'select name from gangs where bank = (select max(bank) from gangs) order by bank;';
$sqldataGang = mysqli_query($dbcon, $sqlgetGang) or die('Connection could not be established');
$welthiestGang = $row2['name'];
}
I know that there is a connection to the database as I have other statistics from other tables working... I have no idea why this isn't working... Thanks for the help in advance :)
$sql = 'SELECT name FROM gangs ORDER BY bank DESC LIMIT 1';
That should do it.
You need to fetch a row from your $sqldataGang query object.
Add a line something like this to your program to fetch the result right after your call to mysqli_query()
$row2 = mysqli_fetch_array($sqldataGang, MYSQLI_ASSOC);
But, also, beware. A wise programmer always checks queries for errors. You can see how to do that in the examples here.
Use this query
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT name,bank FROM Users order by bank desc limit 1";
$result = mysqli_query($conn, $sql);
This will give you the richest person in your website

PHP script, select on server 1 and insert on server 2 if iD doesn't exist (i.e. new records)

We have a phone system database on one server that we cloned/dumped to our local server, but now we need to keep our version updated. Obviously, tables and schema are the same, I just want to run this scheduled script to update with new records that don't exist on the local table (i.e. records that were created since last update).
Below is a test select/insert block. The select query worked on it's own originally, but now I've modified it to use a loop with hopes of using numrows and a foreach to capture everything in the select.
The session table has about 35 columns so I'm looking for the best way to go about this without having to declare every column. I originally tried to do this using update on duplicate key or insert/ignore using a not exists but I don't really know what I'm doing.
Basically, once I select everything, if my table on server 2 doesn't contain a record with the SESSIONID primary key, I want to insert it. I just need some assistance creating this loop script.
Example:
if the table on server 1 has 2 rows with sessionID 12345, and 12346, but my table on server 2 only has up to sessionID 12344, I want to insert the whole records for those two IDs.
//Defining credentials
$servername = "";
$username = "";
$password = "";
$servername2 = "";
$username2 = "";
$password2 = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
$conn2 = new mysqli($servername2, $username2, $password2);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Check connection2
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
echo "Connected successfully";
//Query to select * from Session table on server 1
$query1 = "select * from cdrdb.session";
$results = mysqli_query($conn1, $query1);
foreach ($results as $r => $result) {
$stmt1 = mysqli_prepare($conn2, "insert into ambition.session a where not
exists(a.SESSIONID)");
mysqli_stmt_execute($stmt1) or die(mysqli_error($conn2));
}

php Update sql and Query

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

Categories