I have the following code :
$sql = 'select count(*) from match as count where match_status != :status';
$query = $con->prepare($sql);
$query->bindValue(':status',LOST,PDO::PARAM_INT);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
if(!empty($row))
$row_count = $row['count'];
else
$row_count = 0;
I am getting Notice: Undefined index: count
What's the mistake?
You created the alias for the wrong thing. This should work:
SELECT count(*) as count FROM `match` WHERE match_status != :status
//^^^^^ Alias for 'count(*)' NOT for your table name
Also you have to put ` around keywords/Mysql reserved words e.g. match: http://dev.mysql.com/doc/refman/5.6/en/reserved-words.html
And if you turn on error mode then you also get an error for this, just put it right after your connection:
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'select count(*) from match as count where match_status != :status';
In this query, the as count won't do a thing, because you don't know what column you want to rename.
You need to place it directly after the original column name, so the database knows what column-name it needs to hide:
$sql = 'select count(*) as count from `match` where `match_status` != :status';
Because of this $row['count'] won't work, because you don't have a count-column, only a count(*) column.
N.B.: You're using a MySQL reserved word, being match and requires special attention in MySQL. Either rename it to something else, or use ticks around it, in order to escape it properly.
Related
How is it possible to select the first column in the Where clause. I am trying to make a php function to retrieve table data based on the id, yet since the titles of the id columns are different in various tables, I need to refer to the first column in the Where clause as the first column is always the id column.
The scenario would be something like the following, but it throws errors and says that there is an error in the SQL syntax.
$stmt = $this->conn->prepare("SELECT * FROM $table WHERE column(1) = :id");
Thanks in advance.
I don't think there's a built-in way to do this. But you can query INFORMATION_SCHEMA.COLUMNS to get the column names.
$col_stmt = $this->conn->prepare("
SELECT column_name
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND ordinal_position = 1
AND table_name = :table");
$col_stmt->execute([':table' => $table]);
$first_col = $col_stmt->fetchColumn();
$stmt = $this->conn->prepare("SELECT * FROM `$table` WHERE `$first_col` = :id");
Since there is no built-in way to do this, I came up with the following code block to get the first column and then use it in my SELECT statements.
$stmt = $this->conn->query("SHOW columns FROM $table");
return $stmt->fetch(PDO::FETCH_LAZY)[0];
I think this strategy is a bit shorter than Barmar's, though his is completely right and to the point.
I have a row in my mySQL database called "status". In that row i got three different values, either "S", "R" or "L".
Whats the easiest way to count and output the number of occurrences of each value with php?
Thanks!
You can get the counts as separate rows with:
SELECT status, COUNT(*) as count
FROM yourTable
GROUP BY status
You can get them in a single row with:
SELECT SUM(status = 'S') AS s, SUM(status = 'L') AS l, SUM(status = 'R') as r
FROM yourTable
After this, you can read a single row of results:
$row = $pdo->fetch(PDO::FETCH_ASSOC);
$s_count = $row['s'];
$l_count = $row['l'];
$r_count = $row['r'];
It's hard to tell without a full look at your database, but the basic structure is this (assuming you have another row called id)
Edit: to demonstrate in php
$dbc = new mysqli($host, $username, $password, $dbname);
$query = $dbc->query("select id, count(status) as status_count
where status = 'S'
group by id");
$query->fetch_assoc();
$row = $query->fetch_assoc();
echo $row['status_count'];
OR if you have more than one row do it like this:
while ($row = $query->fetch_assoc()) {
echo $row['status_count'];
}
The better way its to use a mysql query using COUNT
You can count all the raws
SELECT COUNT(*) FROM DATABASE
or one raw
SELECT COUNT(colum_name) FROM DATABASE
To be more easy you can give it a variable name like this:
SELECT COUNT (Colum_name) as name FROM DATABASE
So an example,after you connect to your database
Use this:
$ query = mysql_query ('SELECT COUNT (R) as R FROM status');
$ result = mysql_fetch_array ($ query);
Echo $ result ['R']
Hope this will help you !
In my mySQL database, I insert an entry into the db, and then I need to get the number of that last insertion. I have it set to auto-increment. Using the query "SELECT MAX(ID) FROM TABLE;" works fine in the database, I just need to capture that number to a variable in PHP.
$rowSQL = mysqli_query($con, "SELECT MAX(ID) FROM TABLE");
$row = mysqli_fetch_assoc($rowSQL);
$largestUID = $row['max'];
echo $largestUID;
Thanks for the help!
Use the AS modifier in your query. This modifier gives your selected items an alias.
$rowSQL = mysqli_query($con, "SELECT MAX(ID) AS maxid FROM TABLE");
$row = mysqli_fetch_assoc($rowSQL);
$largestUID = $row['maxid'];
echo $largestUID;
Use an alias name for the calculated column
SELECT MAX(ID) as max_id FROM TABLE
$largestUID = $row['max_id'];
I am trying to do a query in PHP PDO where it will grab a simple result. So like in my query I need it to find the row where the column group is 'Admin' and show what ever is in the group column. I know that we already know what it should be [Should be admin] but just need to get the query to work. Its only grabbing 1 row from my table, so will I need forsearch?
If I change WHERE group = 'Admin' to WHERE id = '1' it works fine. But I need it so it can be where group = 'admin'
$sql2 = "SELECT * FROM groups WHERE group = 'Admin'";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$users2 = $stm2->fetchAll();
foreach ($users2 as $row2) {
print ' '. $row2["group"] .' ';
}
Thanks
group is a reserved word in MySQL, that's why it's not working. In general it's a bad idea to use reserved words for your column and table names.
Try using backticks around group in your query to get around this, so:
$sql2 = "SELECT * FROM groups WHERE `group` = 'Admin'";
Also you should really use placeholders for values, because you're already using prepared statement it's a small change.
Edit: just to clarify my last remark about the placeholders. I mean something like this:
$sql2 = "SELECT * FROM groups WHERE `group` = ?";
$stm2->execute(array('Admin'));
try to use wildcard in your WHERE Clause:
$sql2 = "SELECT * FROM groups WHERE group LIKE '%Admin%'";
Since the value in your table is not really Admin but Administrator then using LIKE and wildcard would search the records which contains admin.
I want to count everything in a Table to make Sites, I'm using this exact code a few times in my php file but now all the sudden is simply doesnt work anymore.. I'm driving crazy
$stmt = $mysqli->query("SELECT COUNT (*) AS Anzahl FROM '$tablename'");
$anzahl = $stmt->fetch_array();
$eintraege = $anzahl["Anzahl"];
$stmt->close();
$max_eintraege = 2;
if($eintraege <=2){
$seiten = 1;
}else{
$seiten = $eintraege / $max_eintraege;
$seiten +=1;
}
$start = $_GET["site"] * $max_eintraege - $max_eintraege;
if(!isset($_GET["site"])){
$start = 0;
}
All I get is:
Fatal error: Call to a member function fetch_array() on a non-object in /home/u144584875/public_html/index.php on line 2377
I just can't find out whats the problem, it works like 5 times in my Script but not now.
Everything is Set and right, whats the problem?
You should add some error handling, but the problem is this:
$stmt = $mysqli->query("SELECT COUNT (*) AS Anzahl FROM '$tablename'");
You are quoting your table name, it should be:
$stmt = $mysqli->query("SELECT COUNT (*) AS Anzahl FROM $tablename");
or
$stmt = $mysqli->query("SELECT COUNT (*) AS Anzahl FROM `$tablename`");
in case the table name is a reserved word in mysql, starts with a number, etc.
Edit: If you add this before you open your database connection (or anywhere above your current code...), mysqli will throw errors and tell you exactly what is wrong:
mysqli_report(MYSQLI_REPORT_STRICT);
// ...
$stmt = $mysqli->query("SELECT COUNT (*) AS Anzahl FROM `$tablename`");
// ...
Your SQL syntax is wrong. Table names should not be wrapped in single-quotes ('). Use backticks to escape them instead.
Update your SQL query as follows:
SELECT COUNT (*) AS Anzahl FROM `$tablename`
The documentation of mysqli::query says:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object.
Obviously, you have an error, and it returns FALSE. Use mysqli::$error to find out what it is.