Loop for taking element if other = 1 (from a row) - php

I would like to have a loop which will go through all elements, and if LoggedIn='1' then it should take country from this row, and then I will connect to the other table, and increment this row, where country=country from 1st table, but I don't know how to start this loop (I mean I don't know how to do if LoggedIn='1', then take this row's country). This is my code:
<?php
require_once("config.php");
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$take = "SELECT * FROM acc WHERE LoggedIn='1'";
$data = mysqli_query($dbc, $take);
while($row = mysqli_fetch_assoc($data))
{
}
?>

just correct your sql
SELECT * FROM acc WHERE LoggedIn = "1"
no need to filter the data in php if you can narrow down your results with sql
now I dont know what you with incerent mean so I wait for an edit or comment to help your further

OK, first off this isn't a great question. A simple Google search should help you to your solution - every tutorial of MySQL will cover SELECT and WHERE query's, every PHP tutorial will cover iterative loops.
You don't want to query the whole database and then loop over it within PHP when you can limit that dataset by simply using
SELECT country FROM table WHERE loggedin = 1

Related

Display somthing different if condition is met I using PHP/MySQL

I have an over time sheet that gets printed when there is over time from an employee. The overtime format goes like "B.Eng." And then the name of the employee. Now I need it to check the name of the employee (or id) to print either "B.Eng." Or "MR.", This because there is an employee (just one) that does not have a degree. I would think the answer would be an IF condition.
Here is my code:
$db = mysql_select_db ("over_time");
$strqry = "SELECT emp_name FROM contr_acces where id_emp='".$vp_idemp."';";
$qry2 = mysql_query ($strqry);
$row2 = mysql_fetch_object ($qry2);
$vl_emp_name= "B.Eng. ".$row2->emp_name;
print $vl_emp_name;
you can do something like this
$db = mysql_select_db ("over_time");
$strqry = "SELECT emp_name FROM contr_acces where id_emp='".$vp_idemp."';";
$qry2 = mysql_query ($strqry);
$row2 = mysql_fetch_object ($qry2);
$vl_emp_name= $row2->emp_name;
if($vl_emp_name == 'name_without_the_degree){
$vl_emp_name= "Mr. ".$vl_emp_name;
}else{
$vl_emp_name= "B.Eng ".$vl_emp_name;
}
print $vl_emp_name;
It is not the best solution since you are hardcoding the condition but without knowing more about the db structure is not possible to give you a better solution. The most efficient one would be to add a field to the db with the degree type for the users and retrieve it together with the name.
See my comment under your question for the api used and the sql injection risk that this soultion doesn't address

Display the amount of Paid items in my database using php

I am using php and mysql to create a page that displays all of the jobs we have in the database. The data is shown is a table and when a row is clicked a modal window triggers with the information of the clicked job inside. At the top of the page I want a simple counter that shows amount of paid jobs, invoiced jobs etc etc. I am using the code below but having no luck...
<?php
$con = mysql_connect("localhost","databaseusername","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("databasename", $con);
$result = mysql_query("select count(1) FROM jobslist");
$row = mysql_fetch_array($result);
$total = $row[0];
mysql_close($con);
?>
This code as far as I am aware is counting the amount of INT columns set to 1 rather than 0. No matter what I try I can't seem to get it to count the amount of 'paid' items in the database or 'invoiced' etc etc.
Once the count function is complete currently I am echoing out the outcome as below:
<?php echo "" . $total;?>
I am sure I am overlooking something simple, but any help is appreciated.
EDIT: TABLE STRUCTURE INCLUDED
http://i.stack.imgur.com/hcMJV.png
Assuming a column called paid you could restructure the query similar to the following. If you needed to sum the amounts involved that requires additional tweaking.
$result = mysql_query("select
( select count(*) from `jobslist` where `paid`=1 ) as 'paid',
( select count(*) from `jobslist` where `paid`=0 ) as 'unpaid'
from jobslist");
$rows = mysql_num_rows( $result );
while( $rs=mysql_fetch_object( $result ) ){
$paid=$rs->paid;
$unpaid=$rs->unpaid;
echo 'Total: '.$rows.'Paid: '. $paid.' Unpaid: '.$unpaid;
}
When I do this I usually name the COUNT result. Try this out:
$result = mysql_query("SELECT COUNT(*) AS total_rows FROM jobslist;");
$row = mysql_fetch_array($result);
$total = $row['total_rows'];
If you do not want to name the COUNT result, then give the following a go:
$result = mysql_query("SELECT COUNT(*) FROM jobslist;");
$row = mysql_fetch_array($result);
$total = $row['COUNT(*)'];
select count(1) FROM jobslist
This code as far as I am aware is counting the amount of INT columns set to 1 rather than 0.
No, this is just counting rows in your table and not filtering. If you want to count something with a specific filter you have to add that filter condition:
SELECT COUNT(*) AS `MyCount`
FROM `joblist`
WHERE `MyColumn` = 1; -- assuming MyColumn contains the INT you're looking for
You should stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.
First you should change deprecated mysql_... to mysqli_... (look here how to). But it's not the reason you fail.
Unlike you seem to suppose, COUNT(1) will not look for an INT column having value 1.
Instead you must use COUNT(*) or COUNT(a_column_name) (same result), with adding a WHERE clause stating which condition is involved.
Here you seem wanting to count records where a given column (say the_column) has value 1. So you should:
SELECT COUNT(*)
FROM jobslist
WHERE the_column = 1
Last point: you don't need echo "" . in <?php echo "" . $total;?>.
Merely write <?php echo $total;?>.

Loop through and Update each row of an sql table in PHP

I'm trying to make a quick lil' script to just add some dummy data to a new column I added to a database table I have, the table has 1000 entries so doing it by hand isn't really an option.
What I have right now it:
<?php
$conn = mysql_connect('localhost', 'root', ''); mysql_select_db('cdb', $conn);
$string = "4050605040302030405060708070304050403040506070605040302010203040506070655545352515756535243515353545"; //50 values
$mpgsplit = str_split($string, 2);
for ($i=0; $i<=20; $i++)
{
for ($x=0; $x<=50; $x++)
{$r = mysql_query ("UPDATE cars SET mpg = '".$mpgsplit[$x]."'", $conn);}
}
?>
Issue being using update doesn't work as it just replaces the value of every row of that column with each number every time it loops. For me it reached number 48 in the array and timed out.
Then using insert just makes all new rows.
So I need a way to cycle through each row and update it.
The nearest I've been to looping through and dealing with singular rows of a table is this:
$result = mysql_query("SELECT * FROM imported_orders");
$orderNo = $_POST['orderNo'];
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if($orderNo>0&&$orderNo<=count($row))
{
$file = fopen('Order.txt', 'w');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
But thats just taking the row as a variable, not sure if I can translate that to what I need.
Theres probably a simple function out there which does this, but I've tried searching and can't find it. Theres also probably an easier way to achieve what I'm trying to do overall as well, so that would be welcome.
All help much appreciated. -Tom
Issue this sql statement directly in mysql command line or from a php script.
SET #r := 0;
UPDATE cars
SET mpg = (#r := #r + 1)
ORDER BY
RAND()
This sql statement will assign number from 0 till Total row count of your db to a random row. I guess it might be helpful

MySQL while loop query inside other while loop query

<?php
include 'config.php';
$conn = mysql_connect("$hostname", "$username", "$password") or die ("Failed to connect to DB.");
mysql_select_db("$dbname",$conn);
$sql="SELECT * FROM opdrachten";
$result=mysql_query($sql,$conn);
while ($row= mysql_fetch_array($result))
{
echo $row['name'];
echo "<br>";
$opdrachtid = $row["id"];
$sql2="SELECT * FROM resultaten WHERE(opdrachtid='".$opdrachtid."')";
$result2=mysql_query($sql2,$conn);
while ($row2= mysql_fetch_array($result2))
{
echo "
<li>
<a href=\"result.php?id=".$row2["id"]."\">
<img src=\"".$row2["img"]." \"width=\"150\" height=\"150\">
<div><span>TEXT HERE</span></div>
</a>
</li>";
}
}
?>
What I want my code to do is (in a loop):
Fetch all rows from the table 'opdrachten' and echo their 'name'.
Grab the 'id' from each of the rows in 'opdrachten' > store in variable $opdrachtid
Fetch rows from table 'resultaten' where 'opdrachtid == $opdrachtid' (which I just stored)
Echo the 'id' and 'img' from the rows fetched from 3.
What I want to see on my page:
The name of the 'opdrachten' (objective) in table 'opdrachten'
with directly underneath
The images (the url's of which are stored in table 'resultaten')that are assigned to these objectives (WHERE opdrachten.id = resultaten.opdrachtid)
I've looked into JOIN since that's the answer to most of the related topic's I've read here, but that doesn't seem to be what I'm looking for since I'm echo'ing in the first while and declare variables that are used for the second query.
Tables used:
'resultaten'
id | opdrachtid | name
'opdrachten'
id | name
Again, resultaten.opdrachtid == opdrachten.id
Thanks in advance, appreciate the help :)
I would certainly suggest using a JOIN here that way you can get all this data in one go. I will add one caveat however - this would take more memory that querying the database in a loop like you are currently doing, so if you have a large number of rows in either table, this might not be a suitable approach.
The query would simply be:
SELECT * FROM opdrachen
INNER JOIN resultaten ON opdrachen.id = resultaten.opdrachenid
You can then set up an array that is keyed on each id very simply like this:
$array = array();
while ($row = mysql_fetch_array($result)) {
$array[$row['id']][] = $row;
}
This give you an easy way to iterate through the results, one id at a time like this:
foreach ($array as $id => $rows_for_id) {
// output stuff for row group
foreach ($rows_for_id as $resultaten_row) {
// output stuff for resultaten rows
}
}
A few other suggestions:
Don't use mysql_* functions as they are deprecated. Learn how to use mysqli or PDO.
Don't use SELECT * queries. Its is lazy and wastes bandwidth, transfer time, and system memory. Only query for the specific fields you are actually interested in. So replace the * in my example with the actual field you need.
SELECT opdrachten.*, resultaten.* FROM opdrachten
INNER JOIN resultaten
ON resultaten.opdrachtid = opdrachten.id;
just use this as the original sql statement and iterate over it.

JSON-PHP/MySQL - Retrieving info from DB

I am using a JSON script ot print out a list of information (later it is sent to my iPhone application, all works fine on that end) with a specific value in a row in my table in my db.
I have managed to do this, however I am looking to expand my search results.
Working Code - obviously i setup
$link = mysql_connect ($host, $uid, $pwd) or die ("Could Not Connect");
mysql_select_db($db) or die("Could Not Connect to Database");
$arr = array();
$rs = mysql_query("SELECT id, story, releasedate, title, youtube, picture FROM movies WHERE category='Action'");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":'.json_encode($arr).'}';
I guess where line #4 is, at the end of that, I would like to to do the following, but cannot find any sample code for it.
Example Code:
......from Movies WHERE category CONTAINS 'Action'");
that obviously does not work and I get an error, pretty much my category row has multiple values for movies, ie DRAMA,Action Sustepnse etc in one row, as some movies are a mix of categories now a days, and would like it filtered out properly without the hassle of adding addition category rows in my db
you can do this
this will select movies that belong to one of these genres
WHERE category IN ('action', 'horror', 'comedy')
but if you want to search if the category contains action or drama or horror you need
WHERE category LIKE '%Action%' OR category LIKE '%Drama%'...

Categories