If I execute the below code i am getting a array value...what i have to do to get a integer value. I need the number given in the dislikes value for that particular image
$sql1="SELECT dislikes FROM photo where imagename=:id";
$q1=array(':id'=>$id);
try
{
$stmt = $pdo->prepare($sql1);
$stmt->execute($q1);
$stmt->setFetchMode(PDO::FETCH_BOTH);
$result= $stmt->fetch();
}
catch (PDOException $e)
{
die("Failed to run query: " . $e->getMessage());
}
print_r($result);
Probably doing a SELECT count(dislikes) is the best option. Or maybe using a for loop in $result to sum the dislikes
If there are more than a single entry in the database, the query will return an array.
Try:
SELECT count(dislikes) FROM photo where imagename=:id
So you'll get an interger, which is the amount of entries in database.
If I use
$result= $stmt->fetcholumn();
instead of
$result= $stmt->fetch();
..THANKS FOR EVERYONE WHO HELPED ME..BUT YOUR SUGGESTIONS ARE NOT PERFECT
Related
So I have a table called Userswhich contains a table structure like this:
Lets say I have a mysql table called 'signups' with the following values:
UID|Name|Regdate
1|Admin|2014-03-04 10:51:01
2|Demo|2014-05-04 09:51:05
I want to create a graph showing how many people signed up in one day. I used this SQL Query:
SELECT DATE(regdate) AS `Date` , COUNT(*) AS Signups FROM `users` GROUP BY DATE(regdate)
It gave me an output of:
Date|Signups
2014-03-04|1
2014-05-04|1
I wanted the output in a PHP File so I made this
<?php include_once("inc/db.php"); ?>
<?php
$query ="
SELECT DATE(regdate) AS `Date`
, COUNT(*) AS Signups
FROM `users`
GROUP BY
DATE(regdate)
";
$query_params = array(
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
echo $result;
?>
When I try to access the page, the result I get should be same thing I got from the SQL Query. However the result I get is 1. As you can see, I am using PDO. I am a beginner please help me please. :)
Do you use mysqli or PDO? Anyway execute does not do the job of returning the eventual result, assuming you use PDO, you have to:
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
foreach($stmt->fetchAll() as $fetch)
{
// do something
}
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
echo $result;
I have a select to a database what should get a number and display it, but display just array
$sth = $conn->prepare("SELECT score FROM people WHERE email='gasd3z#yaho.com'");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
echo $result;
What can I do to display that number?
You don't prepare anything so you don't need to use prepared statements just use query like this:
$result = $conn->query("SELECT score FROM people WHERE email='gasd3z#yaho.com'");
foreach($result as $row)
echo $row['score'];
The previous answer is wrong, but not much.
When you're doing fetchAll(), you're getting all of the rows matching query from the database.
The answer is
$sth = $conn->prepare("SELECT score FROM people WHERE email=:email");
$sth->execute([':email' => 'gasd3z#yaho.com']);
$result = $sth->fetch(PDO::FETCH_ASSOC);
$sth->closeCursor();
echo $result['score'];
And don't forget that prepare() is for preparing statements, so you better want to have user data in query just like in my example. If you don't want to process any values in query, use query() or exec() instead.
You can print out arrays with print_r($result) or var_dump($result). Echoing only prints out the type.
Also, if you only need to print out a specific line, do it like echo $result['score'];
I have been attempting to get the table names from my mysql database with pdo and no matter what I try the only thing I get returned is the word Array for each table instead of the name.
I have tried all of the pdo fetch_* and one of them returned a 1 for each table while the others either return an error or the word Array. It does not matter which example below: $st or $rt
What am I missing?
Here is my code:
$sql = "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_TYPE='BASE TABLE'";
$st = $db->query($sql);
$st->execute();
//$rt = $db->query("show tables");
//$rt->execute();
while($row = $st->fetch(PDO::FETCH_ASSOC)){
echo $row.'<br>';
}
Thanks in advance
Pete
Because this return a multi dimensional array. So you cannot outright echo it. Since you used PDO::FETCH_ASSOC flag, it will return an associative array which in turn you must access its proper index.
while($row = $st->fetch(PDO::FETCH_ASSOC)){
echo $row['TABLE_NAME'] . '<br/>';
}
Sidenote: I don't think $st->execute(); belong in there since this is not using a prepared statement. I think its safe to ditch that part.
I have this code so far
// Starts the transaction
self::$database->startTransaction();
try {
$sql = "SELECT playerId FROM players WHERE name=?";
$stmt = self::getConnection()->prepare($sql);
$stmt->bind_param('s', $playerName);
foreach ($playerNames as $key => $playerName) {
$stmt->execute();
$stmt->bind_result($playerId);
$stmt->fetch();
echo $playerId . "<br>";
}
// commits the transaction
self::$database->commit();
} catch (Exception $e) {
self::$database->rollback();
throw new Exception(__METHOD__." | ".$e->getMessage());
}
The array $playerNames contains the names of the players, e.g.
array('Player1', 'Player2', 'player3')
The code from above should select the playerId of those players from the database. I have some issues:
It just returns the last playerId (in this case the Id of 'player3'). I don't know why.
I use a foreach-loop to execute(). is this bad for the performance, if there were hundreds of names in the array?
In generell: Is this the correct approach for SELECTing or INSERTing stuff from or into a database?
I read this question: How can I prevent SQL injection in PHP?
But it didn't really work because of this:
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
I get an error with the getResult()-method. It says, the method doesn't exist. I think my webspace doesn't support it and I can't install it manually. So I need to stick with fetch().
Or might it have other reasons?
$sql = "SELECT playerId FROM players WHERE name=?";
$stmt = self::getConnection()->prepare($sql);
$stmt->bind_param('s', $playerName);
$stmt->bind_result($playerId);
foreach ($playerNames as $key => $playerName) {
$stmt->execute();
$stmt->fetch();
echo $playerId . "<br>";
}
You are fetching results of only last execute
Running long loops is apparently bad for performance. Try to avoid them.
Yes, in general.
I am trying to create a duplicate username checker and I am thinking this is probably the way to do it correct me if im wrong. Basically I want the username the user input to be stored in a variable called userName and then use that variable to check and see if there are any LIKE rows in the database and if so return a count of 1 or more to a variable named $count I would then have an IF ELSE statement that would either yell at the user or let them continue. I have run into a problem using the LIKE statement. I think my syntax could be wrong since I have been trying several different methods but still no luck.
Main Code
<?php
require 'DB.php';
$userName = "tes";
echo $userName;
try{
$stmt = $conn->prepare('SELECT COUNT(*) FROM `CLL_users` WHERE `user_name` LIKE "% . ":userName" . "');
$stmt->bindValue(':userName', $userName);
$stmt->execute();
$count = $stmt->fetchColumn();
return $count;
echo $count;
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
?>
It appears you're trying to do string concatenation in MySQL using invalid syntax. Try this:
'SELECT COUNT(*) FROM `CLL_users` WHERE `user_name` LIKE CONCAT("%",:userName)'
You can probably use = instead of LIKE. The SQL syntax in itself isn't case-sensitive. I think you might be able to set up your database so that certain tables are case sensitive but I know for a fact through usage that no tables in my own MySQL database are. If you're unsure it's easy to try, just run a select with a username you know is in there but write it with different casing.
Just do a select WHERE 'user_name'=$entered_username, if you get one or more don't add the new user, if not go ahead. You could of course mark the user_field as unique, that way you'd know for sure you won't have duplicates, might be something worth looking at.
Try to use this select:
("SELECT COUNT(*) FROM CLL_users WHERE user_name LIKE "% . "'".$userName."'");