I keep thinking on that "error" but can't say why it returns false.
I've already done a SELECT for this but that is in an other file..
$result = $db->dbh->prepare("SELECT thumbs FROM skill WHERE id=? LIMIT 1");
$result->bindParam(1, $id);
// $id == 4 here
$result->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);
// $row == false > why ?
$thumbs = $row['thumbs'];
When i'm trying to run this on PhpMyAdmin, it works well.
I execute this code on an AJAX call, and using the same config.php file for the $db conection.
Another question:
$sql_in = $db->dbh->prepare("INSERT INTO `voted_ip` (id, ip) VALUES (:id, :ip)");
// $id == 4
$sql_in->bindParam(":id", $id);
$sql_in->bindParam(":ip", $ip, PDO::PARAM_STR);
$sql_in->execute();
it inserts "0" and my ip. Why 0 ?
Please help
That is becasue of the $id which is a STRING is converted at 0 by MySQL.
$id = intval($id);
Related
Hi I want to compare two values from two colummns but it doesnt work correctly. Do I need to cast the results and what I am doing wrong?
$query = "SELECT `columm1`, `columm2` FROM `table` WHERE `id` = ? ";
$stmt = $conn->prepare($query);
$stmt->bindParam(1,$eventID);
$stmt->execute();
$currentJoin = (int) $stmt->fetchColumn();
$maxParticipants = (int) $stmt->fetchColumn(1);
if($currentJoin >= $maxParticipants){
return;
}
else{
Warning There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data. - fetchColumn()
You can use fetch() instead
$stmt->execute();
$result = $stmt->fetch();
if($result[0] >= $result[1] ){
// ...
}
I want to check if user already liked the post, if so than delete the user from database likes.
I've tried to do an if statement but it wont get to the else and only add likes even when user_id and post_id are the same.
Like.class.php
private function Addlike(){
$conn = db::getInstance();
$query = "insert into likes (post_id, user_id) values
(:post_id, :user_id)";
$statement = $conn->prepare($query);
$statement->bindValue(':post_id',$this->getPostId());
$statement->bindValue(':user_id',$this->getUserId());
$statement->execute();
}
private function Deletelike(){
$conn = db::getInstance();
$query = "DELETE FROM likes WHERE post_id = :post_id
AND user_id =:user_id";
$statement = $conn->prepare($query);
$statement->bindValue(':post_id',$this->getPostId());
$statement->bindValue(':user_id',$this->getUserId());
$statement->execute();
}
public function CheckLike(){
$conn = db::getInstance();
$query = "SELECT COUNT(*) FROM likes WHERE
post_id=:post_id AND user_id=:user_id";
$statement = $conn->prepare($query);
$statement->bindValue(':post_id',$this->getPostId());
$statement->bindValue(':user_id',$this->getUserId());
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
if($result["COUNT(*)"] == 0){
$this->Addlike();
}else{
$this->Deletelike();
}
return $result;
}
If you press like for the first time you should like the post and it should be stored in the database, if you press again you unlike the post and it gets deleted from the database. But now it only does the Addlike function...
I think PDO::FETCH_ASSOC returns a multidimensional array when used with PDOStatement::fetchAll, according to https://www.php.net/manual/en/pdostatement.fetchall.php#refsect1-pdostatement.fetchall-examples.
Try changing your code to something like this and see if it works. You could also try dumping the $result variable to see what the structure looks like.
if($result[0]["COUNT(*)"] == 0){
$this->Addlike();
}else{
$this->Deletelike();
}
If an array index doesn't exist, PHP considers it false, which would explain why you're always adding likes, since false == 0 in PHP.
If you want to avoid this equivalency of false and 0, use the identical operator to also compare types:
if ($result["COUNT(*)"] === 0) {
...
I am really beginner on PHP and Android and I can't find the problem.
Here is the by return book PHP code.
Firstly it takes two variables Id and id. It selects id from Books database if the id matches it store the Books database variables.
If takenby === Id it should assign true to $success, otherwise it should assign false to $success but every time $success is null.
I don't understand why it is always null.
Thank for your answering...
<?php
$con = mysqli_connect("localHost","name","password","database");
$id = $_POST["id"];
$Id = $_POST["Id"];
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($con, 'utf8');
$statement2 = mysqli_prepare($con, "SELECT * FROM Books WHERE id = ?");
mysqli_stmt_bind_param($statement2,"s" , $id);
mysqli_stmt_execute($statement2);
mysqli_stmt_store_result($statement2);
mysqli_stmt_bind_result($statement2, $name, $author, $ıd, $date, $takenby);
$response = array();
$response["success"] = false;
if($takenby===$Id)
{
$statement = mysqli_prepare($con,"UPDATE Books SET takenby = '' , date = '' WHERE id = ?");
mysqli_stmt_bind_param($statement,"s" , $id);
$success = mysqli_stmt_execute($statement);
}
$response = array();
$response["success"]=$success;
$response["id"] = $id;
//json data formatı
echo json_encode($response);
mysqli_close($con);
?>
Here is the console output,
Value null at success of type org.json.JSONObject$1 cannot be converted to boolean.
The problem is in that script is missing the fetch part. After I realized that fetch is missing, and I fetch statement.
Here is some example from PHP documentation about fetch
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?> [1]
If someone encounters some kind of problem, ı hope that it would help.
[1] http://php.net/manual/en/pdostatement.fetchall.php
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();
I'm having some troubles with the fetch-method. Here's the code:
$stmt = $db->prepare("INSERT INTO x (name) VALUES (:username)");
$stmt->bindParam(':username', $username);
$result = $stmt->execute();
if ($result == '1') {
$id = $stmt->fetch();
return $id;
}
The query is executed and data inserted, and $result is '1'. However, when I try to fetch the result, it's returning false.
Any tips?
You can $db->lastInsertId() in MySQL (apparently it's not dependable, but I've never had a problem with it). Either That or run another query: SELECT LAST_INSERT_ID() and fetch that.
If you're wanting to fetch the number of rows inserted, follow it with this query:
$rows_inserted = $db->query("SELECT FOUND_ROWS()")->fetchColumn();