PHP Mysql While loop for addition - php

I have this field on my database
email, addition so what i want is that WHERE email='$email' it will look that the data user had for addition. now for addition field we have 100,100,1000
how can i compute this with the echo 1200
my code is NOTE this is just a sample scriptcode i can't copy and paste my code here because it was long. so if you find typo error ignore it.
$sql = mysql_query( "SELECT * FROM user WHERE email = '$email' ") or die(mysql_error());
while ( $row = mysql_fetch_array($sql) ){
echo $row[addition] ++;
}
yes i know its not correct format. what should i change? do i need to use for or foreach? in order to add those computation?
tghanks

with correct (normalized) data structure you can do:
SELECT SUM(addition) AS total FROM users WHERE email = '$email'
if you store it as csv in a column as Ignas says in his commentes,
you can either fix your database structure or use php:
$sum = array_sum(explode(',', $row['addition']));

Somthing like?
$sql = mysql_query( "SELECT * FROM user WHERE email = '$email' ") or die(mysql_error());
while ( $row = mysql_fetch_array($sql) ) {
$iAdditionSum = 0;
$aAddition = explode(',', $row['addition']);
foreach($aAddition as (int) $iAddition) {
$iAdditionSum += $iAddition;
}
echo $iAdditionSum;
}

Related

SQL Query and PHP checking if a user is an Admin

Basically, I have been having some trouble with sending a request to a MySQL server and receiving the data back and checking if a user is an Admin or just a User.
Admin = 1
User = 0
<?php
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`";
$checkAdmin = $checkAdminQuery
mysqli_query = $checkAdmin;
if ($checkAdmin == 1) {
echo '<h1>Working!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
Sorry that this may not be as much info needed, I am currently new to Stack Overflow.
Firstly, your SQL query is wrong
SELECT * FROM `users` WHERE `admin`
It's missing the rest of the WHERE clause
SELECT * FROM `users` WHERE `admin` = 1
Then you're going to need fetch the result from the query results. You're not even running the query
$resultSet = mysqli_query($checkAdminQuery)
Then from there, you'll want to extract the value.
while($row = mysqli_fetch_assoc($resultSet))
{
//do stuff
}
These are the initial problems I see, I'll continue to analyze and find more if needed.
See the documentation here
http://php.net/manual/en/book.mysqli.php
You need to have something like user id if you want to check someone in database. For example if you have user id stored in session
<?php
// 1. start session
session_start();
// 2. connect to db
$link = mysqli_connect('host', 'user', 'pass', 'database');
// 3. get user
$checkAdminQuery = mysqli_query($link, "SELECT * FROM `users` WHERE `id_user` = " . $_SESSION['id_user'] );
// 4. fetch from result
$result = mysqli_fetch_assoc($checkAdminQuery);
// 5. if column in database is called admin test it like this
if ($result['admin'] == 1) {
echo '<h1>Is admin!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
// get all admin users (assumes database already connected)
$rtn = array();
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`=1";
$result = mysqli_query($dbcon,$checkAdminQuery) or die(mysqli_error($dbconn));
while($row = mysqli_fetch_array($result)){
$rtn[] = $row;
}
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`"; !!!!
where what ? you need to specify where job = 'admin' or where name ='admin'
you need to specify the column name where you are adding the admin string

how to get a particular field from a database via php

I am trying to get four different values from my database. The session variable username and usernameto are working, but I want to get 4 different values -- two each from username and usernameto:
<?php
session_start(); // startsession
$Username=$_SESSION['UserID'];
$Usernameto= $_SESSION['UserTO'];
$db = mysql_connect("at-web2.xxxxxx", "yyyyy", "xxxxxxx");
mysql_select_db("db_xxxxxx",$db);
$result1 = mysql_query("SELECT user_lon and user_lat FROM table1 WHERE id = '$Usernameto'");
$result2 = mysql_query("SELECT user_lon and user_lat FROM table1 WHERE id = '$Username'");
$myrow1 = mysql_fetch_row($result1);
$myrow2 = mysql_fetch_row($result2);
while($myrow1)
{
$_Mylon=$myrow1[0];
$_Mylat=$myrow1[1];
}
while($myrow2)
{
$_Mylon2=$myrow2[0];
$_Mylat2=$myrow2[1];
}
?>
Edit - just realized that you didn't tell us what wasn't working about the code you provided. Are you getting an error message or are you not getting the correct data back? You still should fix your query, but we'll need some more information to know what's wrong.
Your query statements shouldn't have "and" between the select parameters, so it should be:
Edit 2 - I just noticed that you had a while loop that you don't need, try this:
$result1 = mysql_query("SELECT user_lon, user_lat FROM table1 WHERE id = '$Usernameto'");
$result2 = mysql_query("SELECT user_lon, user_lat FROM table1 WHERE id = '$Username'");
$myrow1 = mysql_fetch_row($result1);
$myrow2 = mysql_fetch_row($result2);
if (isset($myrow1)) {
$_Mylon=$myrow1[0];
$_Mylat=$myrow1[1];
}
if (isset($myrow2)) {
$_Mylon2=$myrow2[0];
$_Mylat2=$myrow2[1];
}
An example from the php manual echoing an html table
I don't know if you can derive what you need from this?
More specific: You can use:
$line = mysql_fetch_array($result, MYSQL_ASSOC);

Check if a value is already in the table PHP/MYSQL

I'd like to check if a value is already in the table.
The structure of my table is this:
ApplicantId = INT
EventId = INT
StudentId = INT
No need to use unique because these table has dependencies.
Below is what I have tried so far:
include('../connectdb.php');
$ScholarPointId = $_GET["ScholarPointId"];
$Point = $_GET["Point"];
$ScholarId = $_GET["ScholarId"];
$EventId = $_GET["EventId"];
$verifysql = mysql_query("SELECT EventId FROM scholar_attended_events WHERE ScholarId ='$ScholarId' ");
#$resultVerify = mysql_fetch_assoc($verifysql);
$num_rows = mysql_num_rows($verifysql);
if( $num_rows > 0 )
{
$script = "<script>
alert('The user has already attended this event!');
</script>";
header('updatescholarpoints.php');
exit();
}
else{
$result = mysql_query("UPDATE scholar_points
SET scholar_points.Points =
scholar_points.Points + $Point
WHERE scholar_points.ScholarPointId = '$ScholarPointId' ") or die(mysql_error());
mysql_query("INSERT INTO scholar_attended_events (EventId , ScholarId) VALUES( '$EventId' , '$ScholarId' ) ")
or die(mysql_error());
}
?>
What I want is to check if the EventId is already in taken by the Student = StudentId. If so, then system will prompt an alert box. Otherwise, Update and Insert into respective table. How can I do this? It seems I miss something in here. If you could help, I really appreciate it.
just missing an = ?
$verifysql = mysql_query("SELECT EventId FROM scholar_attended_events WHERE ScholarId =$ScholarId ");
(and use PDO or mysqli, your code is really in a deprecated mode)

what is wrong with this code?

I need to read a text file, query the database table with that name, and store that table's data in another table. So far I have written this code but I don't know why it's not working.
foreach ($lindb as $namedb) {
$query = "SELECT * FROM ntable WHERE name =" .$namedb. "";
$result = mysql_query($query);
while ($r = mysql_fetch_array($result)) {
$query = "INSERT INTO ndtable (name,details,address,login,country) VALUES (\"".$r["name"]."\", \"".$r["details"]."\", \"".$r["address"]."\", \"".$r["login"]."\", \"".$r["country"]."\")";
mysql_query($query);
}
}
You don't have quotes around $namedb
ie. SELECT * FROM ntable WHERE name =" .$namedb. ""; should be SELECT * FROM ntable WHERE name ='" .$namedb. "'";
I suggest a SELECT INTO would be the better choice... and please post the error so we are able to help...

PHP Variable in Select Statement

I've written this PHP-Script which is working, and now I want to change the row name into a variable to (not sure if row is correct), I mean the "name" from the select name...
I've tried nearly everything, but nothing gave me the right result.
I know that the normal thing how I can use variables in a statement like ("'. $var .'") won't work.
<?php
require_once 'config.php';
$id = $_GET["id"]; //ID OF THE CURRENT CONTACT
$user = $_GET["user"]; //ID OF THE CURRENT USERS
$query = mysql_query("SELECT name FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
$retval = mysql_fetch_object($query)->name;
$retval = trim($retval);
echo $retval;
?>
This is much easier isn't it?
$sql_insert =
"INSERT INTO customers (
`name`,
`address`,
`email`,
`phone`
)
VALUES (
'$name',
'$address',
'$email',
'$phone'
)";
Is it this you're looking for? Even your question in German isn't that clear to me :
$field = 'name';
$query = mysql_query("SELECT $field FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
$retval = mysql_fetch_object($query)->$field;
You can usi it something like this. Currently i assume you get only one row back and want to use only one field.
<?php
require_once 'config.php';
$id = $_GET["id"]; //ID DES DERZEITIGEN KONTAKTES
$user = $_GET["user"]; //ID DES DERZEITIGEN USERS
//Use variable inside closures `` and just in case escape it, depends how you get variable
$query = mysql_query("SELECT `".mysql_real_escape_string($variable)."` FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
if (!$query) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($query); //Retriev first row, with multiple rows use mysql_fetch_assoc
$retval = $row['0']; //Retriev first field
$retval = trim($retval);
echo $retval;
?>
Please post in English. Everyone else does.
Try using a different fetch method - fetch an associative array, then use the dynamic parameter to retrieve whatever column it is you need.
Have you considered using PDO?
I believe you are confusing matters (unintentionally) due to your use of the word 'row'. Judging by your example you mean field/column. It sounds like you wish to specify the fields to select using a variable which can be done by any of these methods...
$fields = "name, age";
$sql = "SELECT $fields FROM table";
$sql = "SELECT {$fields} FROM table";
$sql = "SELECT ".$fields." FROM table";
NB it is important that you have secure date in the $fields element, I would suggest using a whitelist of allowed values i.e.
// assuming $_POST['fields'] looks something like array('name','age','hack');
$allowed = array('name', 'age');
$fields = array();
foreach ($_POST['fields'] as $field) {
if (in_array($field, $allowed)) {
$fields[] = $field;
}
$fields = implode(', ', $fields);
Wouldn't this work?
$result = mysql_fetch_array($query);
echo trim($result['name']);
You should never put a variable into field list.
If want a variable field name, select *
and then use your variable to fetch particular field
<?php
require_once 'config.php';
$id = mysql_real_escape_string($_GET["id"]); //ID DES DERZEITIGEN KONTAKTES
$user = $_GET["user"]; //ID DES DERZEITIGEN USERS
$query = "SELECT * FROM contacts WHERE contact_id='$id' and user_id='1'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_array($result);
//and finally
$fieldname = "name";
$retval = $row[$fieldname];
echo $retval;
?>

Categories