Filtering SQL queries - php

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

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

Get specific information from a database to display on webiste

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*

MySQL SELECT sometimes found nothing even it exists

I have PHP script that runs every 3 hours that gets the amazon mws orders and save it into my database.
But before I insert an order into my table, I check first if the order exist
SELECT COUNT(*) total FROM orders WHERE transaction_id = "XXXXXXXXX"
But sometimes even if an order exist, the query will return 0. If return 0, I will insert the order into my table and it will end up duplicating the data.
This instance happens to me in my other PHP scripts and I don't understand the issue.
You should use something called as EXISTS for checking whether a row exists or not in your case order.
SELECT EXISTS(SELECT * FROM table1 WHERE ...);
SELECT EXISTS(SELECT * FROM tableName WHERE condition);
If your database uses master-slave mode,you can try to force the master to query.
You can also use the “INSERT IGNORE INTO orders ....” to ignore duplicate.
You may have an error in your MySQL query. I created a test table and write some code to print the result of the query which is working correctly.
You may not be using the quotations properly as this is the error most
of the time when you are working with queries in PHP
Here is the code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practise";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_errno());
}
$sql = "SELECT count(*) from test where title='Hello'";
$result = mysqli_query($conn,$sql);
$new =mysqli_fetch_array($result);
echo $new[0];
?>
</body>
</html>
And:
Image of the table where I am executing the query
The output against the MySQL query is:
2
The code works perfectly. If you have any other question, please share your code and I'll be more than happy to help you.

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));
}

Update Mysql with more than one edit

So I run this php script as cron jobs updating points for users on scoreboard.
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE scoreboard SET points='23' WHERE id=2500";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
This works fine for only one id at a time. How can I edit 3 id's with different points each? Thanks.
You don't usually update 3 IDs per query in a list of users for a scoreboard. One request at a time works just fine and including 3 won't make it faster, unless these 3 players all have the same score, but you specifically mentioned you wanted 3 IDs with different scores for each.
If it's about performance/efficiency, use prepared statements (mysqli's prepare) and use a loop after your prepare() in which you:
bind() the parameters (each time for a different user/points)
execute()
If you must.. you could...
update scoreboard
set points = case when ID = 2500 then '23'
when Id = 'XXXX' then 'YY'
when ID = 'YYYY' then 'XX' end
where ID in (2500,'XXXX','YYYY')
But single updates make more sense here. You could write the a bulk insert to a temp table and update from that table if you have a thousands of records to update with different values. This may be faster.

Categories