How to do two DB queries at once in PHP? - php

I have two queries but can I have them as just one
$sql = ("SELECT * FROM table WHERE title='$title' LIMIT 1");
$sql = ("UPDATE table SET views = views+1 where title='$title' ");
$query = mysql_query($sql) or die("Error Connecting To db");
At the moment the 2nd one works but not the first one.

This is your code:
$sql = ("SELECT * FROM table WHERE title='$title' LIMIT 1");
$sql = ("UPDATE table SET views = views+1 where title='$title' ");
$query = mysql_query($sql) or die("Error Connecting To db");
First, the first $sql will not run because you are overwriting the contents of that first $sql with new content in the next line.
Then just looking at your logic, here is your first query:
SELECT * FROM table WHERE title='$title' LIMIT 1
I assume that is to get the entry with the title equalling $title and nothing else, right? But then your next query is this:
UPDATE table SET views = views+1 where title='$title'
You are updating the value where title='$title' anyway. So the first query is not even needed. So problem solved, right? Well you might want to add the LIMIT 1 to the second query like this:
UPDATE table SET views = views+1 where title='$title' LIMIT 1
But honestly the logic of updating a DB based on whether an item title matches seems messy. What if two items have the same title? Yes, you are limiting things by 1 but by what criteria? If you have three items with the same title, which gets updated?
You need more differentiation for your app structure. But I think that is fair for what is essentially a newbie question.

Run the two queries separately
$sql1 = ("SELECT * FROM table WHERE title='$title' LIMIT 1");
$qry = mysql_query($sql1);
if (mysql_num_rows($qry) > 0)
{
while ($res = mysql_fetch_object($qry))
{
// -- contents --
}
$sql = ("UPDATE table SET views = views+1 where title='$title' ");
$query = mysql_query($sql) or die("Error Connecting To db");
}

Related

PHP - Like limit for posts not working

So far, I am trying to limit the user from liking a certain post more than once. The problem is that when I click "like" on a certain post, the like count will go up every time I click the link, even though it should be limited to just one.
This is the user.php file:
echo "<a href='likes.php?id=$row[0]'>$row[6]</a>";
The "id=$row[0]" indicates to the id_post column in the database. "$row[6]" is the column in the database which shows the like count.
Here is the likes.php file:
<?php
include 'db.php';
connect();
$id = $_GET['id'];
$sql1 = "SELECT * FROM posts";
$result1 = mysqli_query($link, $sql1) or die(mysqli_error($link));
$row = mysqli_fetch_row($result);
if ($row[6] == 0) {
$sql2 = "UPDATE posts SET likes = likes + 1 WHERE id_post = '$id'";
$result2 = mysqli_query($link, $sql2) or die(mysqli_error($link));
}
if ($row[6] == 1) {
exit(header("Location: user.php"));
}
header("Location: user.php");
?>
What's the problem with my code?
SELECT * FROM posts
Your query is selecting all rows from the posts table, and not filtering based on the ID in your $id variable.
Try changing your query to:
SELECT * FROM posts WHERE COLUMN_NAME = '$id'
This way $row[6] will refer to the correct ID in your posts table.

Simple delete query based on variable

I want to delete the record when the id column is equal to $id. Would this work?
$query = "DELETE FROM $TableName WHERE id=$id";
As a side i also want to set the number of rows that can be deleted to a
limit of 1. I know i have to use limit but i am unsure on its parameters
You could do
mysqli_query = ($con, "DELETE FROM `$TableName` WHERE id='$id' LIMIT 1");
That should do it exactly my friend

Find a next record after disabling a record?

I have a created a function changeIp() to disabled a record and return a new record. As you can see I am using 3 SQL query.
Is there a better way doing to reduce number of SQL queries?
function changeIp() {
// Find 1 record which is not disabled
$SQL = "SELECT * FROM ip WHERE disable = 0 order by id limit 1";
$qIp = mysql_query($SQL) or die(mysql_error());
$qrow = mysql_fetch_assoc($qIp);
// Disable a record
$id = $qrow['id'];
$SQL = "UPDATE ip set disable = 1 WHERE id = $id";
mysql_query($SQL) or die(mysql_error());
// Return the next record
$SQL = "SELECT * FROM ip WHERE disable = 0 order by id limit 1";
$qIp = mysql_query($SQL) or die(mysql_error());
$qrow = mysql_fetch_assoc($qIp);
return $qrow['ip'];
}
You should use "mysqli" or php, but that is a separate matter from your question.
Your queries are fine. You can't really do an update and select in a single statement. You can improve performance with an index on ip(id, disable). And, an index on ip(disable, id) might also be beneficial, depending on a number of factors.

PHP SQL - Random Select 1 Row, Where ID = x

I have a MySQL database and I need a PHP to pull a random row. I have successfully created
$query = "SELECT * FROM $usertable
WHERE region='UK'
ORDER BY RAND() LIMIT 1";
This successfully randomly pulls a row; however, it is not limited to where region=2.
I need to be able to:
pull randomly when region=UK
pull randomly when region=UK or ##
(where ## is actually another region, for example, YK = Yorkshire)
Basically I need it to select rows randomly but ONLY when region=UK.
region is a label for one of my fields/collumns, and UK is the content of the VARCHAR in that for a number of rows.
I have the rest of the code sorted.
I have a simple database and the php as follows:
<?php
//Sample Database Connection Syntax for PHP and MySQL.
//Connect To Database
$hostname="carbonmarketing.db.9606426.hostedresource.com";
$username="MarketReadOnly";
$password="Read0nly1";
$dbname="carbonmarketing";
$usertable="ClientList";
$advertfooter = "advertfooter";
mysql_connect($hostname,$username, $password) or die ("<html>%MINIFYHTML4333ddb1f6ba50276851b9f9854a5c817%</html>");
mysql_select_db($dbname);
# Check If Record Exists
$query = "SELECT * FROM $usertable
WHERE region='UK'
ORDER BY RAND() LIMIT 1";
$result = mysql_query($query);
if($result)
{
while($row = mysql_fetch_array($result))
{
$advertfooter = $row["$advertfooter"];
echo "$advertfooter";
}
}
?>
But, it's just pulling randomly for all values of the region column
Let me know if it would help for you to see the database.
Make and array with your regions and implode them:
$region = array('UK', 'YK');
$implode = implode("', '", $region);
$query = "SELECT * FROM `".$usertable."` WHERE `region` IN ('".$implode."') ORDER BY RAND() LIMIT 1";
$query = "SELECT * FROM $usertable
WHERE region IN ('UK','YK')
ORDER BY RAND() LIMIT 1";

Update table based on condition (While Loop)

So I am trying to update my table based on a singe parameter:
The dateEntered field must be blank.
And I want to randomly select 50 rows, and update the blank ownerID fields to "Tester"
Here is what I have:
<?php
include("includes/constants.php");
include("includes/opendb.php");
$query = "SELECT * FROM contacts WHERE dateEntered='' ORDER BY RAND() LIMIT 50";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
$firstid = $row['id'];
$query2 = mysql_query("UPDATE contacts
SET ownerID = 'Tester'
WHERE id = '$firstid'");
$result2 = mysql_query($query2) or die(mysql_error());
}
?>
It will update a single record, then quit and give me:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
The first part that selects the records works fine, its query2 that won't update all 50 records, just one. Maybe I am writing this wrong.
mysql_query needs only one time
$query2 = mysql_query("UPDATE contacts
SET ownerID = 'Tester'
WHERE id = '$firstid'");
$result2 = mysql_query($query2) or die(mysql_error());
to
$result2 = mysql_query("UPDATE contacts
SET ownerID = 'Tester'
WHERE id = '$firstid'");
These answers are spot on, so I will only add some additional information, and a suggestion. When you are querying mysql the first time, $query1 is being set to the result resource, which for
$query1 = mysql_query("UPDATE contacts SET ownerID = 'Tester' WHERE id = '$firstid'");
returns a result of 1 (Boolean TRUE), which is why your second query failed, cause "1" isn't a valid mysql query string. As Greg P stated, you can fix your current script by eliminating the secondary mysql query.
However, you could improve the script entirely, and make fewer sql calls, by using this.
<?php
include("includes/constants.php");
include("includes/opendb.php");
$query = "UPDATE contacts SET owenerID='Tester' WHERE dateEntered='' ORDER BY RAND() LIMIT 50";
$result = mysql_query($query) or die(mysql_error());

Categories