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

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

Related

PHP/MYSQL:Carry out UPDATE within SELECT query

There are many questions on SO about this but I cannot find one that quite meets my situation.
I want to use the values in some fields/columns of a table to set the value of a third field/column
In other words something like:
table races
athleteid|difficulty|score|adjustedscore
$sqlSelect = "SELECT athleteid,difficulty,score FROM races";
$res = mysql_query($sqlSelect) or die(mysql_error());
while ($row = mysql_fetch_array($res)){
$adjustedscore=difficulty*score;
$sqlupdate = "UPDATE race, set adjustedscore = '$adjustedscore' WHERE athletes = 'athletes'";
$resupdate = mysql_query($sqlupdate);
}
My understanding, however, is that MYSQL does not support update queries nested in select ones.
Note, I have simplified this slightly. I am actually calculating the score based on a lot of other variables as well--and may join some tables to get other inputs--but this is the basic principal.
Thanks for any suggestions
You can run:
UPDATE `races`
SET `adjustedscore` = `difficulty` * `score`
WHERE `athleteid` IN (1, 2, 3, ...)
First of all, as previous commentators said, you should use PDO instead of mysql_* queries.
Read about PDO here.
When you'll get data from DB with your SELECT query, you'll get array. I recommend you to use fetchAll() from PDO documentation.
So, your goal is to save this data in some variable. Like you did with $row.
After that you'll need to loop over each array and get your data:
foreach($row as $r) {
//We do this to access each of ours athlete data
$adjustedscore= $row[$r]["difficulty"]* $row[$r]["score"];
//Next row is not clear for me...
$query = "UPDATE race SET adjustedscore = '$adjustedscore' WHERE athletes = 'athletes'";
And to update we use PDO update prepared statement
$stmt = $dbh->prepare($query);
$stmt->execute();
}

Delete one column from table, Update another with PHP MYSQL

I have two tables. One table is the matches table (e2wedstrijden) and another table is my scoring table with the points earned etc. (e2teams).
Now I have that I can delete a match from the e2wedstrijden table. And this is working fine.
But I want that if I delete a match from that table. It also add or decrease points to the table ("e2teams"). I tried to compare the tables but this is not working.
So I want for example:
If($row['thuisscore'] == $row['uitscore']) what are to row names in my e2wedstrijden table. So if these two are the same (like 0-0 or 1-1 or something) Than it needs to decrease 1 point from the table e2teams. But only by the teams that are the same as the rows "Thuisteam" and "Uitteam" in my e2wedstrijden table. So the Row Thuisteam (in "e2wedstrijden") Needs to find the same result in ("e2teams") row Team. And this needs to be done the same with the Row Uitteam (in "e2wedstrijden") Needs to find the same result in ("e2teams")
Thuisteam and Uitteam = Dutch for hometeam and awayteam. I think my fault is that the system can't link the 'Thuisteam' from e2wedstrijden to the Team in e2teams but don't know how to solve it
This is my deletematches.php, It deletes the match but doesn't decrease or adds points:
<?php
if(!isset($_COOKIE['E2ingelogd'])) {
header("location:../../index.php");
}
include "../../connect.php";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
$result = mysql_query("SELECT * FROM e2wedstrijden WHERE ID = ".$_GET['del']."");
while($row = mysql_fetch_assoc($result)){
if( $row['thuisscore'] == $row['uitscore']){
echo $row['thuisscore'];
mysql_query("UPDATE e2teams SET Punten = Punten-1 WHERE Team ='".$row['Thuisteam']."'");
mysql_query("UPDATE e2teams SET Gespeeld = Gespeeld-1 WHERE Team = ('".$row['Thuisteam']."'");
mysql_query("UPDATE e2teams SET Verloren = Gelijk-1 WHERE Team ='".$row['Uitteam']."'");
echo "Team is deleted";
}else{
echo 'Update Error!';
}
}
$table_1_delete = mysql_query("DELETE FROM e2wedstrijden WHERE ID = ".$_GET['del']."");
?>
This is my e2teams table:
And this is my E2wedstrijden table:
So i need something like:
UPDATE e2teams SET Punten = Punten-1 WHERE Team = Look in table ("e2wedstrijden) deleted Thuisteam and deleted Uitteam
Hope you can help
You've placed an extra parentheses in the 2nd query for "gespeeld" right after the equal sign:
mysql_query("UPDATE e2teams SET Gespeeld = Gespeeld-1
WHERE Team = ('".$row['Thuisteam']."'");
Is this what isn't updating?
Without being 100% sure on how your data model works, it might make sense at refactoring what you have. Something that might be useful would be to create a view of the summary table and just update the data from the child/master table.... aggregating in the view layer. Views in mysql can be seen here.
If you are stuck with the data model you have (legacy application, etc.) you can possibly look at triggers if you have to modify data in two tables you might want to consider stored procedures or triggers, discussed here and here.
The third thing that comes to mind, is around correlated sub-queries and how you could reference the another table in a sort of update-from. However, you're ID's aren't surrogate keys in this situation.
Also, have a look at sql injection; I haven't looked at PHP in a while but those sql statements kind of look like they are created with sting composition
Good luck,

Select multiple rows of one column

In MySQL, how can I select the data of one column, only for the rows where the value of the same row, in another column, is session_id (I want all the values, not only the first one)
I have tried this:
SELECT column_name FROM table_name WHERE ID = $session_id
...but it dosen't work. It only selects the first row.
edit, the code I'm using.
<?php
$dn = mysql_query("SELECT IDcontact FROM contacts WHERE ID = '".$_SESSION['id']."'");
if(mysql_num_rows($dn)>0)
{
$dnn = mysql_fetch_array($dn);
$req = mysql_query("select TitreEvent, DescriptionEvent, MomentEvent, image_small from users_event where Confidentialite = 'Public' and ID = " . $dnn['IDcontact']);
while($dnn = mysql_fetch_array($req))
{
?>
So it takes for exemple, the value of the contact/friend (IDcontact), form the database «contacts», where the ID of the logged user is. What I want is to output the event of all the IDcontact, cause actually, it only output the event of the most recent friend added, witch is... the first row of the «contacts» database.
The mysql_fetch_array() function returns only one row from the query's result set. If you want to get all the rows produced by the query, you have to call it in a loop:
while ($row = mysql_fetch_array($dn)) {
// Do stuff with $row...
}
Also, this function is deprecated. You should instead be using either mysqli or PDO to run your queries. See the PHP documentation on choosing an API for more information.
Since you edited your question to show that you're running a second query based on the results of the first one, note that you can do both the IDcontact lookup and get the users_event info in a single query by joining the two tables:
select TitreEvent, DescriptionEvent, MomentEvent, image_small
from users_event
join contacts
on contacts.IDcontact = users_event.ID
where contacts.ID = $session_id
Last but not least, anytime you insert variables (such as your session_id) into a database query, you need to be mindful of SQL injection. If the session ID comes from a parameter that the user can control (e.g. a browser cookie), an attacker could send a malicious session ID that contains SQL code to run arbitrary queries in your database. For safety, you should first create a prepared statement that has a placeholder where the parameter should go:
... where contacts.ID = ?
and then plug in the session_id variable afterward as a "bind parameter". Both mysqli and PDO provide ways to do this: mysqli_stmt_bind_param and PDOStatement::bindParam.

How to use count in php?

I want to insert data to database. I have a table, named member that has 7 column (ID, User, Password, Address, Phone, Gender, Email). I used count to make auto number like this
$no = "SELECT COUNT(ID)FROM member";
$nors = mysql_query($no);
$nors = $nors + 1;
$query = "INSERT INTO member VALUES (".$nors.",'".$user."','".md5($pass)."','".$name."','".$addr."',".$hp.",'".$gender."','".$email."')";
Why, the result of nors is 6 not 2, although I only have 1 data?
mysql_query returns a result object, not the value. Your query also lacks a needed space between COUNT(ID) and FROM...
$no = "SELECT COUNT(ID) AS count FROM member";
$result = mysql_query($no);
$row = mysql_fetch_object($result);
$nors = $row->count;
You should consider using something more modern like PDO, though, as mysql_* functions have been deprecated and will eventually go away entirely.
edit: #andrewsi noted in the comments that you really should be using MySQL's built-in auto increment functionality for IDs, anyways. Much better than what you're currently doing.
If you're using this to generate the next ID number for a new member, you should look at making ID an auto_increment field instead - as it stands, it's possible that you'll get two members signing up at the same time, and both getting assigned the same ID
Replace this line
$nors = mysql_query($no);
By these lines :
$result_handler = mysql_query($no);
$result = mysql_fetch_array($result_handler);
$nors = $result[0];
If your id field is set to be an auto number you don't need to insert it. MySql will handle that for you. Anytime you add a new row the autonumber is incremented. If you delete a row the autonumber does not decrement.
If you currently only have 1 row but you've added and deleted rows then your insert will produce a row with an ID that is not consecutive.

mySQL fetch column based on another column in PHP

I'm trying to write my first PHP script with mySQL and I desperately need some help. I'm sure this is relatively simple, but if I have one field in my table (username, for example), and I want to fetch another field (name, for example), that is in the same row as the given username, how do I do that?
Again, I'm sure this is easy, but I'm lost, so I'd really appreciate any help. Thanks!
$sql = "SELECT username, name FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
echo "This {$row['username']} has the name {$row['name']}\n";
}
halfdan's answer sort of works, but it fetches all rows and displays them. What you want is a WHERE clause, which lets you filter the contents of the table so the query only returns the row(s) you want:
SELECT username, name
FROM sometable
WHERE (username = 'johndoe');
This will return only the rows where the username field is equal to 'johndoe'. Conceptually, it's equivalent to:
$results = mysql_query("SELECT username, name FROM table");
while($row = mysql_fetch_assoc($results)) {
if ($row['username'] == 'johndoe') {
// do something, this is a row you want
} else {
// not a row you want. ignore it, or deal with it some other way
}
}
the main difference is that for large data sets in the database, doing client-side filtering like this is expensive, as the entire contents of the table has to be transferred over. Using a WHERE clause to limit things to just what you want is far more efficient in the long run.

Categories