Below is my pretty simple attempt at trying to count the number of times $name string occurs in the $related_company string row of a table.
I was hoping it would spit out a number, but when i upload it to my webserver, it doesnt spit out anything.
Any ideas?
<?php
$db = new SQLite3('database.sqlite3');
$red = $db->query('SELECT * FROM news');
$name = strtolower("Tesla");
$related_company = $red->fetchArray($row['related_company']);
while ($row = $red->fetchArray()) {
if (in_array($name, $related_company)){
$count+1;
}}
echo $count;
?>
You can do it all in a single query, without having to loop through the results. SQL has a LIKE operator to perform pattern matching in columns.
$db = new SQLite3('database.sqlite3');
$stmt = $db->prepare("SELECT COUNT(*) AS count FROM news WHERE related_company LIKE :name");
$name = '%' . strtolower("Tesla") . '%';
$stmt->bindParam(':name', $name);
$stmt->execute();
$row = $stmt->fetchArray(SQLITE3_ASSOC);
$count = $row['count'];
echo $count;
If the name comes from another table, you can join the tables.
$result = $db->query("
SELECT c.name, COUNT(*) as count
FROM Companies AS c
JOIN news AS n ON n.related_company LIKE '%' || LOWER(c.name) || '%'");
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
echo "{$row['name']}: {$row['count']}<br>";
}
Related
Apologies if I have the terminology wrong.
I have a for loop in php which operates a mysql query...
for ($i = 0; $i <count($user_id_pc); $i++)
{
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '$user_id_pc[$i]'";
$job_data = mysqli_query($dbc, $query2);
$job_results = array();
while ($row = mysqli_fetch_array($job_data))
{
array_push($job_results, $row);
}
}
The results that are given when I insert a...
print_r ($job_results);
On screen -> Array()
If I change the query from $user_id_pc[$i] to $user_id_pc[14] for example I receive one set of results.
If I include this code after the query and inside the for loop
echo $i;
echo $user_id_pc[$i] . "<br>";
I receive the number the counter $i is on followed by the data inside the array for that counter position.
I am not sure why the array $job_results is empty from the query using the counter $i but not if I enter the number manually?
Is it a special character I need to escape?
The full code
<?php
print_r ($user_id_pc);
//Select all columns to see if user has a profile
$query = "SELECT * FROM user_profile WHERE user_id = '" . $_SESSION['user_id'] . "'";
//If the user has an empty profile direct them to the home page
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 0)
{
echo '<br><div class="alert alert-warning" role="alert"><h3>Your appear not to be logged on please visit the home page to log on or register. <em>Thank you.</em></h3></div>';
}
//Select data from user and asign them to variables
else
{
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 1)
{
$row = mysqli_fetch_array($data);
$cw_job_name = $row['job_description'];
$cw_rate = $row['hourly_rate'];
$job_mileage = $row['mileage'];
$job_postcode = $row['postcode'];
$response_id = $row['user_profile_id'];
}
}
for ($i = 0; $i <count($user_id_pc); $i++)
{
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '{$user_id_pc[$i]}'";
$job_data = mysqli_query($dbc, $query2);
$job_results = array();
while ($row = mysqli_fetch_array($job_data))
{
array_push($job_results, $row);
}
echo $i;
?>
<br>
<?php
}
print ($query2);
print $user_id_pc[$i];
?>
This is primarily a syntax error, the correct syntax should be:
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '{$user_id_pc[$i]}'";
Note that this is correct syntax but still wrong!! For two reasons the first is that it's almost always better (faster, more efficient, takes less resources) to do a join or a subquery or a simple IN(array) type query rather than to loop and query multiple times.
The second issue is that passing parameters in this manner leave your vulnerable to sql injection. You should use prepared statements.
The correct way
if(count($user_id_pc)) {
$stmt = mysqli_stmt_prepare(" SELECT job_title, job_info FROM job_description WHERE postcode_ss = ?");
mysqli_stmt_bind_param($stmt, "s", "'" . implode("','",$user_id_pc) . "'");
mysqli_stmt_execute($stmt);
}
Note that the for loop has been replaced by a simple if
You have to check the query variable, instead of:
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '$user_id_pc[$i]'"
have you tried this:
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '" . $user_id_pc[$i] . "' ";
And another thing, try something different like this:
while ($row = mysqli_fetch_array($job_data))
{
$job_results[] = array("job_title" => $row["job_title"], "job_info" => $row["job_info");
}
Then try to print the values.
Sorry but I like foreach(), so your working code is:
<?php
// To store the result
$job_results = [];
foreach($user_id_pc as $id ){
// selecting matching rows
$query2 ="SELECT job_title, job_info FROM job_description WHERE postcode_ss = '".$id."'";
$job_data = mysqli_query($dbc, $query2);
// checking if query fetch any result
if(mysqli_num_rows($job_data)){
// fetching the result
while ($row = mysqli_fetch_array($job_data)){
// storing resulting row
$job_results[] = $row;
}
}
}
// to print the result
var_dump($job_results);
I have a a form which let's the user select what they want to display. Now the results of this looks like that: 9, 10, 11. These are IDs from the table.
These are the IDs of the type they what to show. I have my query already, but I want to add this part at the end of my query.
So in this case:
$query = "type_ID = $result1 or type_ID = $result2 or type_ID = $result3"
if printed out with echo:
type_ID = 9 or type_ID = 10 or type_ID = 11
How can I achieve this?
I tried to loop and it,however this did not work and I am confused how to do add the MySQL code to this.
$result = $result . $_GET['type_ID'][$i]
I'm a tad unsure of what it is you are trying to achieve but from what I understand this should do it:
<?php
$tID = $_GET['type_ID'];
$query = 'SELECT * FROM table WHERE';
$i = 0;
foreach($tID AS $id){
if($i == 0){
$query .= ' type_ID = ' . $id;
$i++;
}else{
$query .= ' OR type_ID = ' . $id;
}
}
Although if you are only looking for the type_ID I'd still recommend using IN() like so:
<?php
$tID = $_GET['type_ID'];
$query = "SELECT * FROM table WHERE type_ID IN (" . implode(',',$tID) . ")";
In works just like OR, just instead of having to write multiple OR you can just use a single IN() :)
Have you try this ?
$sql = "SELECT * FROM table WHERE ".$query;
I am trying to do a row count, I want to count a row (nummer) and if there is more then 1 row with the same number then echo. but no matter how many rows I have in my tabel, it only returs 0
$nummer = $_GET['nummer'];
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $pdo->prepare("select count(*) from rum where nummer=:n");
$result->bindParam(':n', $nummer, PDO::PARAM_INT);
$result->execute();
$rows = $result->fetchAll;
if(count($rows) >1) {
echo "1";}
else {
echo "0";
}
The following statement
$result = $pdo->prepare("select count(*) from rum where nummer=:n");
will always return one row with the count number, so doing
$rows = $result->fetchAll;
will always return one.
You may do as
$result = $pdo->prepare("select count(*) as tot from rum where nummer=:n");
....
....
$rows = $result->fetchAll();
if($rows["tot"] > 0 ){
echo 'something'
}else{
echo 'something else'
}
just use fetch() instead of fetchAll()
$rows = $result->fetch();
if($rows[0]) >1) {
echo "1";
} else {
echo "0";
}
It looks like you're having two mistakes.
First one: If you're querying for COUNT(*) - you are getting a number of rows. For example: You're return will be a field named COUNT(*) with one row containing the number of rows found.
If you replace
$result = $pdo->prepare("select count(*) from rum where nummer=:n");
with
$result = $pdo->prepare("select * from rum where nummer=:n");
Second one:
Replace
$rows = $result->fetchAll;
With
$rows = $result->fetchAll();
fetchAll() is no property but a method.
The other way would be your query but naming the field (MySQL AS keyword) and calling $rows = $result->fetch(); afterwards and checking $rows->fieldName for the number of found rows.
Use PDOStatement::fetchColumn(). It is useful for "one-column" resultsets (which relatively often produced by queries like SELECT COUNT(...) FROM ...). Example:
$nummer = isset($_GET['nummer']) ? $_GET['nummer'] : null;
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT COUNT(*) FROM rum WHERE (nummer = :n)');
$stmt->bindParam(':n', $nummer, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchColumn();
echo $rows > 1 ? "1" : "0";
I am using mysqli to fetch data from the database and put it into an array with a while loop. When i echo out the array i get an empty array however in a function i previously did this code worked but it had a different result from the database. I know that the database is giving out good data because when i echo out the result $idGroup it gives me 2 which is correct.
Ps i know it will keep replacing itself because i don't specify an index
private function Groups()
{
$functionRun = 0;
$i = 0;
$helperArray = array();
$this->grouplist = array();
$query = "SELECT GroupName, Groups.idGroup
FROM Groups
INNER JOIN Members
ON Groups.idGroup = Members.idGroup
WHERE Members.idMember = ? ";
//prepare query and execute
if($stmt = $this->connection->prepare($query))
{
$stmt->bind_param('s', $this->id);
$stmt->execute();
$stmt->bind_result($GroupName, $idGroup);
while ($stmt->fetch())
{
$helperArray[] = $idGroup;
}
echo $helperArray;
}
Use print_r when dealing with arrays. Use echo on strings.
Try this
$query = "SELECT GroupName, Groups.idGroup
FROM Groups
INNER JOIN Members
ON Groups.idGroup = Members.idGroup
WHERE Members.idMember = ? ";
//prepare query and execute
if($stmt = $this->connection->prepare($query))
{
$stmt->bind_param('s', $this->id);
$stmt->execute();
$stmt->bind_result($GroupName, $idGroup);
$helperArray =array();
while ($stmt->fetch())
{
$helperArray[] = $idGroup;
}
print_r($helperArray);
}
Assuming I have a uniqid key in my table and that same key is sent to my site in a get method, how do I pull that specific key out and assign all the data from the table to variables. This is what I have so far but cant seem to figure it out.
$query1 = "SELECT *
FROM todo_item2 as ti INNER JOIN todo_category2 as tc ON ti.todo_id = tc.todo_id'
WHERE todo_id = :todo_id";
$statement1 = $db->prepare($query1);
$statement1 -> execute(array(
'todo_id' =>$id
));
while ($row = $statement1->fetch())
{
$text = $row['todo'];
$cat = $row['category'];
$percent = $row['precent'];
$date = $row['due_date'];
}
You should ready about what execute actually does .. the parameters to execute (and I assume you're using PDO or something similar here) are the tokens of the query. What you want is something like:
$query = " ... WHERE todo_id = ?"
$stmt = $db->prepare($query);
$stmt->execute(array($id));
while ($row = $stmt->fetch()) {
//$row is now an associative array of row values.
}
// Start the Load
$query1 = "SELECT *
FROM todo_item2 as ti INNER JOIN todo_category2 as tc ON ti.todo_id = tc.todo_id
WHERE ti.todo_id = :todo_id";
$statement1 = $db->prepare($query1);
$statement1 -> execute(array(
'todo_id' =>$id
));
// Make Sure the Data Exists
if( $statement1->rowCount() == 0 )
{
die('Please Enter a Valid ID Tag - (id)');
}
while($row = $statement1->fetch())
{
$text = $row['todo'];
$cat = $row['category'];
$percent = $row['percent'];
$date = $row['due_date'];
}