I am relatively new to web development and I am trying to query a MySQL database with a database through the following commands, however I unable to do so and I am getting the following as error:
PHP Code:
$query1 = "SELECT id_2 FROM idTable WHERE id = '$idno'";
$result1 = mysql_query($query1);
if (!$result1)
die("Database access failed(error 7): " . mysql_error());
/************ possible error point *******************/
$query2 = "SELECT * FROM Data NATURAL JOIN $result1 LIMIT $num,$last_num";
$result = mysql_query($query2);
if (!$result)
die("Database access failed(error 8): " . mysql_error());
Error:
Database access failed(error 8): Table 'Database.Resource' doesn't exist
Basically I have two tables. I need to choose some values from the 'id_2' column of idTable and depending upon the values chosen, I want to pick all the rows from the table 'Data' that match the corresponding ids by performing a join operation. Can anybody please tell me how to achieve the join of the resource returned and the table (Or in general, how do I solve my problem)?
SELECT d.*
FROM Data d
JOIN idtable i
ON i.id2 = d.id
WHERE i.id = $idno
ORDER
BY d.id
LIMIT $num,$last_num;
I am still not sure what is relations between these 2 tables but valid code and query should be something like :
$query1 = "SELECT * FROM Data
INNER JOIN idtable
ON idtable.id = Data.id_2
AND idtable.id = $idno
LIMIT $num,$last_num";
$result = mysql_query($query1);
if (!$result)
die("Database access failed : " . mysql_error());
But valid is not equal correct or good :-)
And once I've reread my own query, I have the same question as #Strawberry: why do we need join? why not just:
$query1 = "SELECT * FROM Data
WHERE Data.id_2 = $idno
LIMIT $num,$last_num";
$result = mysql_query($query1);
if (!$result)
die("Database access failed : " . mysql_error());
Related
Trying to insert a variable inside a string variable that will be used as a query.
$staffID = $_GET["staffID"];
$conn = mysqli_connect("localhost", "twa095", "twa095de", "factory095");
if ( !$conn )
{
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT staffName, orderID, orderDate, shippingDate
FROM purchase INNER JOIN staff ON purchase.staffID = staff.staffID
WHERE staffID = $staffID // Problem is over here.
GROUP BY orderDate"
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
?>
Getting this as error:
Problem with queryColumn 'staffID' in where clause is ambiguous
Also, is there a way I can have it check whether the given "staffID" (first line) is inside the database and if it isn't to terminate the script and display an error message before everything below it executes?
Actually staffID is present in both joined tables (purchase and staff). Mysql is confused either staffID is from purchase table or staff table. To resolve your problem add tablename. to the staffID in where clause of your query as:
$sql = "SELECT staffName, orderID, orderDate, shippingDate
FROM purchase INNER JOIN staff ON purchase.staffID = staff.staffID
WHERE staff.staffID = '{$staffID}' // Problem is over here.
GROUP BY orderDate"
Also as a best practice add {} around the variable inside another
string and single quotes in case variable is empty it will work fine.
Secondly, For checking if staff id is already in table and returning error you have to use mysqli_num_rows() inside the if clause and print error message to user as:
$sql = "SELECT staffName, orderID, orderDate, shippingDate
FROM purchase INNER JOIN staff ON purchase.staffID = staff.staffID
WHERE staff.staffID = $staffID // Problem is over here.
GROUP BY orderDate"
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
if(mysqli_num_rows($conn,$result)>0){
echo "Error Message";
exit;
}
You probably need single quotes around your variable name in your query:
WHERE staff.staffID = $staffID // Problem is over here.
Should change to:
WHERE staff.staffID = '$staffID'
I have 2 tables: "media" and "rating"
I need to retrieve all data from both tables where "media" has a title, description and a image. "rating" only stores the media id and a vote (1 - 5).
My problem is that when i try to retrieve data and the "rating" table is empty then no data is shown and if there are more votes in the "rating" table than in the "media" table then it show duplicates of the "media".
<?php
$query = "SELECT * ";
$query .= "FROM media, rating ";
$query .= "WHERE media.id = media_fkey";
$result = mysqli_query($link, $query);
if (!$result) {
die("Database query failed.");
}
?>
I hope that this makes sense. :-)
Thank you in advance!
// René
try this
$query = "SELECT * FROM media AS m JOIN rating AS r ON m.id = r.media_fkey"
$result = mysqli_query($link, $query);
if (!$result) {
die("Database query failed.");
}
or you can use the field name with object names other than *
SELECT m.id, m.data, r.media_fkey......
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";
I am trying to create a cron job that will select the sum of points from a transaction table.
Based on the Sum of the points and the employee id I must update the total point table.
I want to make sure that I am using the best method and that this will work.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT ID, SUM(POINTS) as Points, FROM Transactions WHERE Status = 1 Group By ID";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
mysql_query("UPDATE Totals SET Points=" + $row["Points"] + "WHERE ID=" + $row["id"]);
}
mysql_free_result($result);
?>
You can still join tables (and subqueries) on UPDATE statements. Try this one,
UPDATE Totals a
INNER JOIN
(
SELECT ID, SUM(POINTS) as Points,
FROM Transactions
WHERE Status = 1
Group By ID
) b
ON a.ID = b.ID
SET a.Points = b.Points
Hope this helps.
example of using PDO Extension (Code Snippet).
<?php
$query = "UPDATE Totals a
INNER JOIN
(
SELECT ID, SUM(POINTS) as Points,
FROM Transactions
WHERE Status = ?
Group By ID
) b
ON a.ID = b.ID
SET a.Points = b.Points";
$iStatus = 1;
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $iStatus);
$stmt->execute();
?>
PDO Manual
PDO PreparedStatement
Why can't you just test the script out out before you run it via a cron job? I can't spot anything that's wrong with the syntax; but then again, I only gave it a quick glance and I don't know what your table structure is like.
If you're looking for the BEST way to do things, then you should looking into using mysqli or PDO instead of the mysql functions. That way, you can make use of prepared statements, which won't be as taxing on your DBMS if you're planning on running multiple queries inside a loop. Prepared statements don't require you to make separate round trips to the server, whereas the old mysql functions do.
i have create a database with three tables. I have a table "field" which has an id_field from 1-5 and a table name slot which has start and end times. When i want to show all the available fields and times is okay but i when i want to show the field with id value 1 is still showing all the fields!!!!!
Here is my code:
echo("<select name='selSlot'>");
$mysql_link = mysql_connect("localhost","root","*********");
$db_select = mysql_select_db("nuevo", $mysql_link);
$query = "SELECT * FROM field WHERE id_field = 1 CROSS JOIN slot WHERE (id_field,id_slot) ".
"NOT IN(Select field_slot,res_slot From reservation WHERE res_date = '"
.$today['year']."-".$today['mon']."-".$today['mday']."') ORDER by id_field,id_slot";
$result = mysql_query($query)
or die ("Query '$query' failed with error message: " . mysql_error ());
$row = mysql_fetch_assoc($result);
echo "apoel";
while ($row) {
echo("<option value='" .$row['id_field'].",".$row['id_slot']."'>".$row['description'].
" ".$row['start_time']."-".$row['end_time']." </option>");
$row = mysql_fetch_assoc($result);
}
echo("</select>");
I dont know why it doesnt show me only the field with id one and is still showing me all the fields!!!!
Your query has two WHERE clauses:
.... WHERE id_field = 1 CROSS JOIN slot WHERE ...
It should result in a database error. Proper syntax is:
SELECT *
FROM field
CROSS JOIN slot
WHERE id_field = 1
AND (id_field,id_slot)
...