PHP SQL select query not working - php

My sql, keeps on producing an error with an empty result. I'm trying to select a past student from the database that has got the same grades and results as a past student stored in the database. I'm using pdo statements to prepare the statements.
I keep on getting returned empty queries, even though in the database there is a student that has taken maths (subject 1) and got an A (grade1). This query won't work.
$query = $db->prepare("SELECT * FROM paststudent WHERE subject1 = :subject1 AND grade1 = :grade1");
.
if ($autumn != "" and $winter == "" and $spring == "" and $summer == "") {
$query = $db->prepare("SELECT * FROM paststudent WHERE subject1 = :subject1 AND grade1 = :grade1 AND subject2 = :subject2 AND grade2 = :grade2 AND subject3 = :subject3 AND grade3 = :grade3 AND subject4 = :subject4 AND grade4 = :grade4 AND autumn = :autumn");
// binds the value to the query variable
$query->bindValue(':subject1', $subject1, PDO::PARAM_STR);
$query->bindValue(':grade1', $grade1, PDO::PARAM_STR);
$query->bindValue(':subject2', $subject2, PDO::PARAM_STR);
$query->bindValue(':grade2', $grade2, PDO::PARAM_STR);
$query->bindValue(':subject3', $subject3, PDO::PARAM_STR);
$query->bindValue(':grade3', $grade3, PDO::PARAM_STR);
$query->bindValue(':subject4', $subject4, PDO::PARAM_STR);
$query->bindValue(':grade4', $grade4, PDO::PARAM_STR);
$query->bindValue(':autumn', $autumn, PDO::PARAM_STR);
// executes the query
$query->execute();
// the value of the query is stored to result
$result = $query->fetch(PDO::FETCH_ASSOC);
// fetch() instead of fetchAll just gets the first result
}

can you please dump your sql query here, that will be easy to solve your problem. what i can see that all the AND condition and if any of AND condition false then you will get empty result.

Related

two condition for where Clause in SQL

I want execute a sql query with my php code but it is wrong and I don't know what is my problem!
$end_type = $executed[end_type];
$start_type = $executed[start_type];
$sql = "SELECT * FROM `wants` WHERE ((`car`=? AND $start_type=? AND $end_type=?) OR (`car`=? AND $start_type=? AND $end_type='all'))";
$query = $con->prepare($sql);
$query->bindValue(1, $executed[car]);
$query->bindValue(2, $executed[start_place]);
$query->bindValue(3, $executed[end_place]);
$query->execute();
$results = $query->fetchall();
sendmsg($user_id, $results);
sendmsg is my massage sender function and it don't return any array even an empty array!
why? what in my solution?
The main issue here seems to be that you have five ? placeholders in your prepared statement, but are only binding three values. There might be some way to recycle binding values in PHP, but in this case I would rephrase your query as:
SELECT *
FROM wants
WHERE car = ? AND start_type = ? AND end_type IN (?, 'all');
Updated PHP code:
$sql = "SELECT * FROM wants WHERE car = ? AND start_type = ? AND end_type IN (?, 'all')";
$query = $con->prepare($sql);
$query->bindValue(1, $executed[car]);
$query->bindValue(2, $executed[start_place]);
$query->bindValue(3, $executed[end_place]);
$query->execute();
$results = $query->fetchall();

PHP PDO getting different MySQL results than workbench

When running a query in phpMyAdmin workbench the results are as expected, a total has a value. However, when running the same code in PHP PDO total is always 0. Here's the SQLFiddle.
PHP Code:
$stmt = "
SELECT COUNT(*) as `total`
FROM `provider_availability`
WHERE `provider_availability`.`practitioner_id` = :practitioner_id
AND `provider_availability`.`weekday` = :weekday
AND `provider_availability`.`ID` != :edit_id
AND `deleted` = 0
AND ( :start_time BETWEEN `provider_availability`.`starting_time` AND `provider_availability`.`ending_time`
OR :end_time BETWEEN `provider_availability`.`starting_time` AND `provider_availability`.`ending_time` )";
$query = $this->connection->prepare($stmt);
$query->bindValue(':practitioner_id', $_SESSION['user']['ID'], PDO::PARAM_INT);
$query->bindValue(':weekday', $weekday, PDO::PARAM_INT);
$query->bindValue(':edit_id', $edit_id, PDO::PARAM_INT);
$query->bindValue(':start_time', $start_time, PDO::PARAM_STR);
$query->bindValue(':end_time', $end_time, PDO::PARAM_STR);
if ($query->execute() == true) {
$row = $query->fetch(PDO::FETCH_ASSOC);
return $row['total'];
} else {
die(json_encode([
"success" => false,
"reason" => $query->errorInfo()
]));
}
It's impossible.
PDO will never get you a different result, given the query sent and the database connected to are the same.

How do I call a SQL Server stored procedure from PHP using PDO_SQLSRV that returns a value?

I have a stored procedure in SQL Server 2014 that takes two integers as input and returns an integer. Below is the code to create the stored procedure:
CREATE PROCEDURE [dbo].[p_MergePerson_AuditLog_CheckLogForDuplicate]
#Person1_ID INT,
#Person2_ID INT,
#RowCount INT OUTPUT
AS
SET NOCOUNT ON
SELECT
#RowCount = COUNT(mpal.Transaction_ID)
FROM
MergePersonAuditLog mpal
WHERE
#Person1_ID = #Person2_ID
AND #Person2_ID = #Person1_ID
RETURN #RowCount
Basically, it just takes two ids and sees if a comparison has been made before, just in a different order. Below is the PHP code:
// Connecting to DB
try {
$conn = new PDO("sqlsrv:server=IP;Database=DB", "user", "pwd");
}
catch(PDOException $e) {
die("Error connecting to server $e");
}
// Arrays that will hold people IDs
$person1Array = array();
$person2Array = array();
// Holds the row count used to see if a comparison has already been performed
$rowcount = 5; // Setting to 5 to make sure the stored procedure is actually setting the value.
// Query to get the people that will be compared
$query = "SELECT p.PersonID
FROM Person p
WHERE (p.StudentNumber IS NULL OR p.StudentNumber = '')
AND (p.StaffNumber IS NULL OR p.StaffNumber = '')
ORDER BY
p.PersonID";
$stmt = $conn->query($query);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
foreach ($row as $key => $value) {
$person1Array[] = $value;
}
}
$person2Array = $person1Array;
// Begin the comparisons
print "Beginning the comparisons <br>";
foreach ($person1Array as $person1id) {
foreach ($person2Array as $person2id) {
print "Checking $person1id and $person2id <br>";
if ($person1id != $person2id) {
print "Not the same. Continuing.<br>";
// Checking to see if the comparison has already been made
$query = "{? = call p_MergePerson_AuditLog_CheckLogForDuplicate(?, ?)}";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $rowcount, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT,4);
$stmt->bindParam(2, $person1id, PDO::PARAM_INT);
$stmt->bindParam(3, $person2id, PDO::PARAM_INT);
$stmt->execute();
print $rowcount . "<br>";
}
}
}
print "FINISHED! <br>";
$stmt = null;
$conn = null;
?>
When I run this code, 5 is still being printed for $rowcount even though it should be set to 0 by the stored procedure. If the value is 0, more code will be executed that I didn't include, but I want to get this part right first. Running the procedure in management studio works fine. Can someone tell me why $rowcount is not getting updated? I am running php 5.6 on Windows 10.
Ok, I found an answer that worked for me. I read https://msdn.microsoft.com/en-us/library/cc626303(v=sql.105).aspx which doesn't have anything to do with PDO_SQLSRV, but with sqlsrv_connect(). In that article, it stated the last parameter was the output parameter. I changed my code to look like this:
// Checking to see if the comparison has already been made
$query = "{call p_MergePerson_AuditLog_CheckLogForDuplicate(?, ?, ?)}";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $person1id, PDO::PARAM_INT);
$stmt->bindParam(2, $person2id, PDO::PARAM_INT);
$stmt->bindParam(3, $rowcount, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT,4);
$stmt->execute();
print $rowcount . "\n";
Basically, I moved the "?" From the beginning of the call statement to the end and moved the bindParam to the end as well. That seems to have done the trick.
You could get the return value via a select statement:
$query = "select p_MergePerson_AuditLog_CheckLogForDuplicate(?, ?)";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $person1id, PDO::PARAM_INT);
$stmt->bindParam(2, $person2id, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchColumn();

Call a stored procedure with the same name using PDO

I have two stored procedures in my database Postgres, both have the same name but the difference are the parameters.
procedure1(::string, ::integer, ::string, ::integer)
procedure1(::string, ::integer, ::integer)
In PDO doing bindParam correct, is coming STR, INT, INT but the prepere always performs procedure1.
How do I get him to understand what I call the procedure2?
Some information for more help? I clear? thanks
EDIT ===
...
$bounds = null; // forced for debug
if(!is_null($bounds)){
$query = "SELECT procedure1(:name, :domain, :geo, :userid)";
$stmt = $db->prepare($query);
$stmt->bindParam('name', $name, PDO::PARAM_STR);
$stmt->bindParam('domain', $idDomain, PDO::PARAM_INT);
$stmt->bindParam('geo', $geoString, PDO::PARAM_STR);
$stmt->bindParam('userid', $userId, PDO::PARAM_INT);
}else{
$query = "SELECT procedure1(:name, :domain, :userid)";
$stmt = $db->prepare($query);
$stmt->bindParam('name', $name, PDO::PARAM_STR);
$stmt->bindParam('domain', $idDomain, PDO::PARAM_INT);
$stmt->bindParam('userid', $userId, PDO::PARAM_INT);
}
$result = $stmt->execute();
...
The error it gives is that he is running a procedure that requires four parameters
Try changing your $query statements to explicitly tell PDO the types, and to avoid extra code switch to bindValue (PDO uses the PARAM flags to format SQL, not to cast data types):
$bounds = null; // forced for debug
if(!is_null($bounds)){
$query = "SELECT procedure1(:name::VARCHAR, :domain::INTEGER, :geo::VARCHAR, :userid::INTEGER)";
$stmt = $db->prepare($query);
$stmt->bindValue('name', $name);
$stmt->bindValue('domain', $idDomain);
$stmt->bindValue('geo', $geoString);
$stmt->bindValue('userid', $userId);
}else{
$query = "SELECT procedure1(:name::VARCHAR, :domain::INTEGER, :userid::INTEGER)";
$stmt = $db->prepare($query);
$stmt->bindValue('name', $name);
$stmt->bindValue('domain', $idDomain);
$stmt->bindValue('userid', $userId);
}
$result = $stmt->execute();

Multiple selects in PHP PDO

How can I run multiple select statements in the same query in PDO? My SQL statement works fine when I run it in phpMyAdmin? Code is below:
$sql = 'SELECT DISTINCT apartment.apartmentName,
apartment.apartmentID
FROM apartment_information apartment,
apartment_ratings ratings,
apartment_floorplans floorplan,
user_user user
WHERE user.preferred_zip = :zip
AND floorplan.apartmentID = apartment.apartmentID
AND floorplan.apartmentID = (SELECT apartmentID
FROM apartment_floorplans
WHERE monthlyPrice < :monthlyPrice
AND apartmentNumBedrooms = :apartmentNumBedrooms
AND apartmentNumBathrooms = :apartmentNumBathrooms)';
try{
echo $sql;
$stmt = $this->_db->prepare($sql);
$stmt->bindParam(":zip", $this->_zip, PDO::PARAM_STR);
$stmt->bindParam(":monthlyPrice", $this->_apartmentFloorPlans['Price'], PDO::PARAM_STR);
$stmt->bindParam(":apartmentNumBedrooms", $this->_apartmentFloorPlans['Bedrooms'], PDO::PARAM_STR);
$stmt->bindParam(":apartmentNumBathrooms", $this->_apartmentFloorPlans['Bathrooms'], PDO::PARAM_STR);
}
$stmt->execute();

Categories