PHP/SQL Query - Inserting a Variable Inside a String Variable - php

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'

Related

How to use join properly when i want to get a specific row in another column

I have two columns, one of them is (users) and the other one is (user_messages).
Now, I want to get just the users which has then name "unreaden" inside (user_messages).
$user="select * from users LEFT OUTER JOIN user_messages.msg_seen='unreaden' ON users.id=user_messages.m_id";
After that just count them and put the amount of them next to username in brauser with the help of mysqli num_rows. After the query when I check it, it gives me boolean (false). I think the problem is with the query. Can you check if there is an error with my code on joins?
A simple solution should look something like this.
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "select users.name as user_name, count(user_messages.id) as no_of_unread_messages "
." from users LEFT OUTER JOIN user_messages ON ( users.id = user_messages.user_id AND user_messages.msg_seen='unreaden')";
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row["user_name"]." ". $row["no_of_unread_messages"];
}
mysqli_free_result($result);
}

How to output a value of an other table from an indexed field in mySQL?

I have two MySQL tables
users with id, user_formOfAdress and serveral additional fields. Field user_formOfAdress contains the id of table formofadress
formofadress with id, formOfAdress_german and serveral additional fields, for example id 1 = Mr., id 2 = Mrs.
The record of the users table is identified by a Session variable.
To output not the id of the field user_formOfAdress but the value of the table formofadress.formOfAdress_german (for example Mr. or Mrs.) I have written this:
if(array_key_exists("id", $_SESSION) && $_SESSION['id']){
$uid = $_SESSION['id'];
$link = mysqli_connect("localhost:3307", "root", "Dinah123", "proficrm");
$query = "
SELECT formofadress.ID AS formofadress_ID, formofadress.formOfAdress_german, users.ID, users.user_formOfAdress
FROM `formofadress`
LEFT JOIN users
ON formofadress.formofadress_ID = users.user_formOfAdress
WHERE `users.ID` = '".$uid."'
LIMIT 1
";
$result = mysqli_query($link, $query);
$record = mysqli_fetch_assoc($result);
$user_formOfAdress = $record['formOfAdress_german'];
}
"FROM formofadress" because I want to output the Mr. or Mrs. of this table, but I have to use also the users table because of the Session ID which is also the id of the users record ...
Not every record in the users table has a value in user_formOfdAdress (value 1, 2 or NULL) but every record in the formofadress table has a fixed value.
Error is:
Undefined variable: user_formOfAdress located in the last row
It's my first time to use JOINs and I'm unfortunately not able to solve this issue even after a long time of searching.
Correct code:
if(array_key_exists("id", $_SESSION) && $_SESSION['id']){
$uid = $_SESSION['id'];
$link = mysqli_connect("localhost:3307", "root", "Dinah123", "proficrm");
$query = "
SELECT formofadress.ID, formofadress.formOfAdress_german, users.ID, users.user_formOfAdress
FROM formofadress
LEFT JOIN users
ON formofadress.ID = users.user_formOfAdress
WHERE users.ID = '".$uid."'
";
$result = mysqli_query($link, $query);
$record = mysqli_fetch_assoc($result);
$user_formOfAdress = $record['formOfAdress_german'];
}
There were problems with your SQL syntax. You used LEFT JOIN to join users to formofadress while users sometimes can't follow and you will possibly get a NULL value. I also cleaned up your other query syntax so it is more readable.
Also, check to see if the database is expecting an INT for $uid. If not then return the apostrophes ''.
if(array_key_exists("id", $_SESSION) && $_SESSION['id'])
{
$uid = $_SESSION['id'];
$link = mysqli_connect("localhost:3307", "root", "Dinah123", "proficrm");
$query = "SELECT u.ID, u.user_formOfAdress, f.ID, f.formOfAdress_german,
FROM users u LEFT JOIN formofadress f ON f.formofadress_ID = u.user_formOfAdress
WHERE u.ID = ".$uid." LIMIT 1";
// if database is not expecting `INT` for `u.ID` then return the apostrophes ' '
$result = mysqli_query($link, $query);
// mysqli_fetch_assoc returns case sensitive keys
$record = mysqli_fetch_assoc($result);
$user_formOfAdress = $record['formOfAdress_german'];
}

Joining a resource and a table in php / mysql

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

SQL CASE WHEN STATEMENt into PHP VARIABLE

I have that problem:
I have SQL Statement:
SELECT Amount FROM cicmpy
INNER JOIN (SELECT DealerCode, sum(Amount) as Amount FROM
(SELECT DealerCode, LOG as LogtLimit,TemporaryCreditLimit as TemporaryCreditLimit,
CASE WHEN TemporaryCreditLimit>0 then TemporaryCreditLimit ELSE LOG END as Amount
FROM LOG_DATA WHERE Status = 1 group by DealerCode) x
on x.DealerCode=debcode where debnr is not NULL and ltrim(debcode) = '21021287'`
and I want this statement into php $query variable.
try like this,it will solve your error.
$sql = "Put your query"; //put your query in php variable
$result = mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($result)) {
do stuff...
}
For More Reference

PHP update table data based on other table

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.

Categories