Is something wrong with my query? - php

I'm working on a database with 3 tables, some with overlapping information. A few columns from each table can be updated by the user via the web app that I am creating. But... There is an issue. Not sure what it is, but my updates aren't happening. I am wondering if something is wrong with my query. (Actually, after debugging, I am quite certain there is).
if (empty($errors)) {
$query1 = "UPDATE owner SET
name = '{$name}'
WHERE ownerId= '{$ownerId}'";
$query1_result = mysql_query($query1);
if (mysql_affected_rows()==1) {
$query2 = "UPDATE queue_acl SET
date_expires = '{$date_expires}'
WHERE user_id='{$ownerId}'";
$query2_result = mysql_query($query2);
if (mysql_affected_rows()==2) {
$query3 = "UPDATE ownerOrganization SET
orgId = {$orgId}
WHERE ownerId = '{$ownerId}'";
$query3_result = mysql_query($query3);
if (mysql_affected_rows()==3) {
$_SESSION['name'] = $name;
$_SESSION['updates_occurred'] = true;
}
}
}
Sorry if it is trivial; I have never worked with multiple tables before.

It's not a good habit to update tables the way you do it. If the updates are relating somehow you might want to think about creating a transaction. Transactions make sure that all updates are executed (and if not, a rollback is done (which means no update will be executed)):
// disable autocommit
mysqli_autocommit($dblink, FALSE);
// queries
$query1 = mysqli_query($dblink, "UPDATE owner SET name = '{$name}' WHERE ownerId= {$ownerId}'");
$query2 = mysqli_query($dblink, "UPDATE queue_acl SET date_expires = '{$date_expires}' WHERE user_id='{$ownerId}'");
$query3 = mysqli_query($dblink, "UPDATE ownerOrganization SET orgId = {$orgId} WHERE ownerId = '{$ownerId}'");
if($query1 && $query2 && $query3)
{
mysqli_commit($dblink);
$_SESSION['name'] = $name;
$_SESSION['updates_occurred'] = true;
}
else
mysqli_rollback($dblink);
I haven't tested it but it guess it should work. Also you should take a look at mysqli or prepared statements since mysql_ is deprecated.

The first issue might be scope related. Your if conditionals are wrong?
If (result ==1)
{
if(result == 2)
{
...
}
}
Thus if your first result is more than 1 then all the internal conditionals will be skipped.
If I understand it should be:
if(result ==1)
{
}
elseif(result ==2)
{
}
...(other conditions)...
else
{
}
I would recommend a base case to catch if you have more results than you expect.
The second issue might be that you quote around all data except orgId = {$orgId}. This should probably be orgId = '{$orgId}' if the id is some random string then not quoting will cause issues.
One last concern is to check ownerId. If that is blank for some reason then your query will fail because where id=0 (assuming you have auto increment on) will never be true. Put a if(!empty(ownerId) conditional.

Related

How to check if the DB already have the data or insert new data

What I want is that php check if the client IP address is the same one which in the DB if it already exists, if not to insert new data.
well, it works if the client isn't already inserted in the database, but if he already exists php is skipping the update and trying to insert it again in the database............
I don't know whats wrong with it and couldn't figure out.
Here is my code:
<?php
$corruser = $_SESSION['user_name'];
$client_ip = $_SERVER['REMOTE_ADDR'];
require_once 'connections/dbc.php';
if (!$conn) {
echo "Error connecting the database";
exit();
} else{
$GUI = "SELECT * FROM `customers` WHERE user_name='$corruser'";
$GUI_response = mysqli_query($conn, $GUI);
if (!$row = mysqli_fetch_assoc($GUI_response)) {
echo "Error while query the database";
exit();
} else{
$customer_id = $row['customer_id'];
$check = "SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='$user_name' ";
$check_response = mysqli_query($conn,$check);
$check_result = mysqli_fetch_array($check_response, MYSQLI_NUM);
if ($check_result[0] > 1) {
$update_ip = "UPDATE `users-ipdb` SET `client_ip`='$client_ip' WHERE customer_id='$customer_id' AND user_name='$corruser' ";
$update_ip_result = mysqli_query($conn, $update_ip);
if (!$update_ip_result) {
echo "ERROR UPDATING DATA BASE";
exit();
}
} else{
$insert_new = "INSERT INTO `users-ipdb`(`customer_id`, `user_name`,`client_ip`) VALUES ('$customer_id','$corruser','$client_ip')";
$insert_new_result= mysqli_query($conn, $insert_new);
if (!$insert_new_result) {
echo "Error inserting new data in the database";
exit();
}
}
}
}
?>
I think you made an error with this code :
$check = "SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='$user_name' ";
$user_name variable doesn't exist, you should replace it with $corruser
That's why the code never goes into the UPDATE
First, make sure that your condition does work as expected. If customer_id is not a number the following line:
if ($check_result[0] > 1) {
can be possibly evaluated as if(0 > 1) let you read this:
Comparing String to Integer gives strange results.
The other comments mention "UPSERTS" which are explained here https://mariadb.com/kb/en/library/insert-on-duplicate-key-update/
The basic idea is that you can do
INSERT INTO `users-ipdb`(`customer_id`, `user_name`,`client_ip`)
VALUES ('$customer_id','$corruser','$client_ip')"
ON DUPLICATE KEY UPDATE client_ip='$client_ip';
and you get rid of the all the php logic. For this to work properly customer_id and user_name must be both part of the PRIMARY KEY.
If you need to query multiple tables, you can use joins - if you use ON DUPLICATE KEY UPDATE you don't need them, but still a good thing to know - https://mariadb.com/kb/en/library/join-syntax/
Last, but not least - it is a good habit to escape any value which may come from other sources. Maybe it is not your case, but some people tend to create usernames like Joe';DROP TABLE mysql.user;SELECT ' and it will destroy your database, because your query will become
SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='Joe';DROP TABLE mysql.user;SELECT ''
So be careful.

Which is the Fastest method to check Rows existence while fetching?

From the following Queries, Which one is the most optimal and fastest to use?
[COUNT(id)]
$SQL = "SELECT name, COUNT(id) as Count FROM names WHERE name = :name";
$row = $stmt->fetch();
if ($data['count'] > 0) {
while ($row) {
$name = $row['name'];
}
} else {
return;
}
OR [rowCount()]
$SQL = "SELECT name FROM names WHERE name = :name";
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch()) {
$name = $row['name'];
}
} else {
return;
}
OR [EXISTS]
$SQLEX = "SELECT EXISTS (SELECT name FROM names WHERE name = :name LIMIT 1)";
if ($stmt->fetchColumn == 1) {
$SQL = "SELECT name FROM names WHERE name = :name";
while (row = $stmt->fetch()){
$name = $row['name'];
}
} else {
return;
}
OR [RAW]
$SQL = "SELECT name FROM names WHERE name = :name";
$row = $stmt->fetch();
if ($row) {
while($row) {
$name = $row['name'];
}
} else {
return;
}
Also i wanted to know, Why does using $stmt->fetch() with $stmt->rowCount() allows me to fetch data, But using it with $stmt->fetchColumn doesn't?
First, if you have an index on names(name), then all should be quite comparable in speed.
Second, it is always worth trying such performance tests on your own system.
Third, if names are declared as unique (or primary key) in the names table, then all should be quite fast.
In general, though, the fastest way to determine if a row is available is:
SELECT EXISTS (SELECT name FROM names WHERE name = :name)
The LIMIT 1 in the subquery is unnecessary -- EXISTS stops at the first row (whether the database uses an index or a table scan).
In general, the first method using an aggregation is the worst solution. Without an index, it is going to result in a full table scan that reads the entire table. The second might or might not read the entire table, depending on whether the database starts returning matching rows as they are available. It also has the downside of returning more data.
Ok, it seems this question needs more than one answer...
f you need to check the existence only,
if there is an unique index for the field, all methods are equal, but some of them just make no sense.
if there is no unique index, then go for EXISTS
If you need to fetch the actual data and see if there was anything returned, then just select your data and fetch it:
if only one column from a single row is expected, then use fetchColumn()
if only one row is expected, then use fetch()
if multiple rows are expected, then use fetchAll()
and then use the resulting value to see whether your query returned any data.
So if you finally made your mind as to what you're asking about, here is the most optimal code for you:
$SQL = "SELECT name FROM names WHERE name = :name";
$data = $stmt->fetchAll(PDO::FETCH_COLUMN);
if (!$data) {
return;
}
foreach ($data as $name) ...
And there is nothing wrong with fetchColumn() other than your idea to use it.

update certain table column if else query

I'm trying to write a query to check which column to update. The user sends an action which they performed (a like or a comment) and I'm trying to update a table. Is it possible to check inside the query which column to update? For example:
DB structure:
id imageName imageLikesCount imageCommentsCount
$actionPerformed = "like";
mysqli_query($link, "UPDATE table (if $actionPerformed=like SET imageLikesCount+1
else imageCommentsCount+1)
WHERE imageName='$image'");
I'm not sure how to phrase that, if it's possible at all. Any advice? Thanks in advance!
though meverhart913 has a way to do it, the better way to do the same thing is to instantiate your variable based on the if condition, then just plug that variable into your string. This keeps you from having to repeat your string over and over as well as allows you to easily add additional conditions.
if($actionPerformed=="like"){
$col = imageLikesCount;
else{
$col = imageCommentsCount;
}
mysqli_query($link, "Update table SET '$col' = '$col + 1' where imageName = '$image'");
if($actionPerformed=="like"){
mysqli_query($link, "Update table SET imageLikesCount = imageLikesCount + 1 where imageName = '$image'");
}
else {
mysqli_query($link, "Update table SET imageCommentsCount = imageCommentsCount + 1 where imageName = '$image'");
}
I'm not a php programmer so my syntax won't be correct, but here are two ways to do it:
if ($actionPerformed == "like")
query for updating imageLikesCount
else if ($actionPerformed == "comment")
query for updating imageCommentsCount
else
whatever
Or
if ($actionPerformed == "like")
$column = "imageLikesCount";
else ($actionPerformed == "comment")
$column = "imageCommentsCount";
$sql = "update table set $column = $column + 1";
Then execute it.

Database not updating row

Before you assume I didn't establish a database connection, I did. the only portion of the code that does not update is the if empty statements.
All the values can be echoed out correctly, it's just that query doesn't work.
This is in directory config and named stuff.php
$user = $mysqli->real_escape_string($_SESSION['username']);
$user_query = "SELECT * FROM users WHERE username = '$user'";
$result = $mysqli->query($user_query);
$row = $result->fetch_assoc();
$referrer = $row['ref'];
$refearn = $row['refearn'];
verify.php
include('config/stuff.php');
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { // Get Real IP
$IP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$IP = $_SERVER['REMOTE_ADDR'];
}
if ($IP=="external server ip here") {
if (!empty($referrer)){
$mysqli->query("UPDATE users SET points=points+10, refearn = refearn+10 WHERE username='".$referrer."'") or die(mysqli_error($mysqli));
}
$mysqli->query("UPDATE users SET points=points+".$earnings.", completed = completed+1 WHERE username='".$subid."'") or die(mysqli_error($mysqli));
}
My guess is you could try to retrieve the value of points through a query then add to it so you're just updating to a simple value. However, if mysql_error() is returning an error, it should be easier to figure out.
Example:
$getPoints = mysql_query("SELECT points FROM table WHERE condition");
$points = mysql_result($getPoints, 0, "points");
$update = mysql_query("UPDATE table SET points=" . ($points+10) . " WHERE condition");
Hope that helps. Another consideration, though. Why use an endif structure unless you're breaking PHP tags to display content?
try this:
$mysqli->query("UPDATE `users` SET `points`=`points`+10, `refearn` = `refearn`+10 WHERE `username`='".$referrer."'") or die(mysqli_error($mysqli));
Hope this helps. What I think is, mysql query might be taking those as constant - not as the mysql rows. Try that

MySQL Update WHERE

I have a feeling that my syntax is incorrect but I can't narrow down what's going on. I have no issues running the statement in a phpMyAdmin SQL query, so hopefully I can get pointed in the right direction. My code is as follows:
else if ($resultdetails === 1) {
$query3 = "update customer_det set `10k`='$_10k',
`14k`='$_14k', `18k`='$_18k', `21k`='$_21k', `22k`='$_22k',
`24k`='$_24k', `925k`='$_925k', `coins`='$coins', `bars`='$bars'
where `id` = '".$uid."'";
$result3 = mysql_query($query3);
}
$resultdetails is a variable set with a EXISTS function. In the SQL query, it returns 1 for me, because the row I'm looking for does exist. So there should be no issues with that.
I tried the double ==, as well as the triple, and there doesn't seem to be any difference in results. I believe the triple === means that it's identical, i.e. the datatype is the same and the value is the same.
I think the issue here is the WHERE statement. Any ideas or suggestions would be greatly appreciated. I forgot to mention that customer_det is the table to be updated and id is the primary key, autoincremented. I pull the $uid variable from the database as well.
Your sql query is right !
But your else if is the problem !
see you add ===,
change it with == and i'm also doubt with your variable declare,
your code will look
like this:
else if ($resultdetails == 1) {
$query3 = "update customer_det set `10k`='".$_10k."',
`14k`='".$_14k."', `18k`='".$_18k."',
`21k`='".$_21k."', `22k`='".$_22k."', `24k`='".$_24k."', `925k`='".$_925k."', `coins`='".$coins."', `bars`='".$bars."' where `id` = '".$uid."'";
$result3 = mysql_query($query3);
}
EDIT:
if (CONDITION :: IF FOUND ON DATABASE) {
$query3 = "update customer_det set `10k`='".$_10k."',
`14k`='".$_14k."', `18k`='".$_18k."',
`21k`='".$_21k."', `22k`='".$_22k."', `24k`='".$_24k."', `925k`='".$_925k."', `coins`='".$coins."', `bars`='".$bars."' where `id` = '".$uid."'";
$result3 = mysql_query($query3);
} else {
// Insert query if not found
}
Check for the data type for $uid and $_blahblah
Try this query --
else if ($resultdetails == 1) {
$query3 = "update customer_det set `10k`='$_10k',
`14k`='$_14k', `18k`='$_18k', `21k`='$_21k', `22k`='$_22k',
`24k`='$_24k', `925k`='$_925k', `coins`='$coins', `bars`='$bars'
where `id` = $uid";
$result3 = mysql_query($query3);
}

Categories