Adding mysql value - php

all im try do do is add variables that are within mysql.
I thought this would be simple but not proving to be and im not really getting anywhere.
Is it even possible to add values from mysql?
I'm sure it probably something simple, as always, any guidance is appreciated.
Thanks
$query = mysql_query("SELECT * FROM users WHERE ID ='$userid'");
$numrows = mysql_num_rows($query);
if($numrows ==1){
$row = mysql_fetch_assoc($query);
$id = $row['uid'];
$name = $row['name'];
$angles = $row['angles'];
$decimals = $row['decimals'];
$multiplication = $row['multiplication'];
$probability = $row['probability'];
$sequences = $row['sequences'];
$symmetry = $row['symmetry'];
}
$sum = $sequences + $symmetry;
print ("$sum");
Solved the issue. the query should read ....WHERE uid ='$userid'");!

You could also do the calculation by the database by a query like this:
SELECT uid, name, angles, (sequences + symmetry) AS mysum FROM users WHERE ID ='$userid'

Related

PHP PDO count and sum value from MySQL table

Well, I'm pretty sure this is just a novice question, so please forgive me for that, but I feel like I'm losing my mind.
I have a simple MySQL rating table and I need to count rows and to sum rates values (int) with PHP PDO
$sql = "SELECT rate FROM rating_table";
$query = $db->query($sql);
$rate_times = count($query->fetchAll()); // it works!
echo '<p>'.$rate_times.'</p>';
$sum_rates = array_sum($query->fetchAll()); // it doesn't work!
echo '<p>'.$sum_rates.'</p>';
Thank you in advance for any suggestion
If I understand you right, all you have to do is to modify your sql request, this will return a single row
sql = "SELECT sum(rate) as rate_sum, count(*) as record_count FROM rating_table";
$query = $db->query($sql);
$row = $query->fetch(PDO::FETCH_ASSOC);
if ($row) {
$sum = $row['rate_sum'];
$count = $row['record_count'];
}

PHP mysql_fetch_array multiple tables

So I have the below code that I'm trying to run partly as a login script, and partly to gather some information for another program. I don't get any errors with the script, I just don't get any information from the second and third mysql_fetch_array which I read is a common problem but that should only apply to the same table. Even so, I followed the recommended advice and used mysql_data_seek to reset the $result. I've also tried using different $result and $row variables but I still don't get any data back from those queries. Any thoughts on how I can do this?
$result = mysql_query("SELECT * FROM user WHERE username = '$username'");
$row = mysql_fetch_array($result);
$salt = $row['salt'];
$id = $row['id'];
$usergroup = $row['usergroupid'];
$mysql_pass = $row['password'];
$md5_pass = md5($password.$salt);
mysql_data_seek ($result, 0);
if($mysql_pass == $md5_pass)
{
$result = mysql_query("SELECT teamid FROM tmnt_members WHERE teamid = '$id'");
$row = mysql_fetch_array($result);
$team = $row['teamid'];
$captain = $row['leader'];
$cocaptain = $row['coleader'];
mysql_data_seek ($result, 0);
$result = mysql_query("SELECT * FROM tmnt_teams WHERE teamid = '$team'");
$row = mysql_fetch_array($result);
$teamname = $row['teamname'];
}
You're missing your coleader and leader fields in your second query. Your three queries can be written as one quite simply.
SELECT *
FROM user u, tmnt_members m, tmnt_teams t
WHERE u.username = '$username'
AND m.teamid = u.id
AND t.teamid = m.teamid
Or if you would like to keep the authentication a separate query, you could do SELECT * FROM user WHERE username = '$username' followed by:
SELECT *
FROM tmnt_members m, tmnt_teams t
WHERE m.teamid = '$id'
AND t.teamid = m.teamid
While writing this, I noticed there probably is an error in your second query. The condition teamid = '$id' seems pretty strange. Currently, you're fetching the team which has an ID that is the one of the user. That can't be correct, or if it is, your database structure is very, very strange. I guess it should be something like memberid = '$id'.
Also notice that without the corrections suggested in my first paragraph, this query is asking the database to fetch the ID of a team which has the ID $id. In other words, you could've just used $id directly if that query was correct.
Moreover, doing a SELECT * isn't the best practice; it's better to enumerate all the fields you want explicitly. If you change your column names or do some other modifications to your database, your query may still work, but may not do what you expect it to do.
I've converted your code to MySQLi at least. I have quoted my comments inside. And did try to clean your code. Try this:
<?php
$con=mysqli_connect("Host","Username","Password","Database"); /* REPLACE NECESSARY DATA INSIDE */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
$username=mysqli_real_escape_string($con,$_POST['username']); /* ASSUMING $username COMES FROM A POST DATA. JUST REPLACE IF NECESSARY */
$result = mysqli_query($con,"SELECT * FROM user WHERE username = '$username'");
while($row = mysqli_fetch_array($result)){
$salt = mysqli_real_escape_string($con,$row['salt']);
$id = mysqli_real_escape_string($con,$row['id']);
$usergroup = mysqli_real_escape_string($con,$row['usergroupid']);
$mysql_pass=mysqli_real_escape_string($con,$row['password']);
$md5_pass = md5($password.$salt); /* MAKE SURE YOU HAVE $password AND $salt VARIABLES DECLARED ABOVE */
if($mysql_pass == $md5_pass)
{
$result2 = mysqli_query($con,"SELECT teamid, leader, coleader FROM tmnt_members WHERE teamid = '$id'"); /* ADDED leader AND coleader */
while($row2 = mysqli_fetch_array($result2)){
$team = mysqli_real_escape_string($con,$row2['teamid']);
$captain = mysqli_real_escape_string($con,$row2['leader']);
$cocaptain = mysqli_real_escape_string($con,$row2['coleader']);
$result3 = mysqli_query($con,"SELECT * FROM tmnt_teams WHERE teamid = '$team'");
while($row3 = mysqli_fetch_array($result3)){
$teamname = mysqli_real_escape_string($con,$row3['teamname']);
} /* END OF THIRD LOOP */
} /* END OF SECOND WHILE LOOP */
} /* END OF IF MYSQL_PASS IS EQUALS TO MD5_PASS */
/* IS THIS WHERE YOU WANT TO PRINT YOUR RESULTS? */
echo $id." ".$usergroup." ".$team." ".$captain." ".$cocaptain. " ".$teamname;
} /* END OF WHILE LOOP */
?>

MySQL - Batch rename all rows in PHP

So in this piece of code, I just deleted a row from the table, and so, the values for img_pos were:
1,2,3,4,5
And now, they are (assuming we deleted the third entry):
1,2,4,5
Of course, I want this to be:
1,2,3,4
So I have to batch rename the rows.
I got this, but doesn't seem to work....
$sql = "SELECT * FROM $tableImg WHERE img_acc = $accid ORDER BY img_pos";
$res = mysql_query($sql);
$num = mysql_num_rows($res);
$i = 0;
$n = 1;
while($i<$num){
$sql = "SELECT * FROM $tableImg WHERE img_acc = $accid ORDER BY img_pos DESC LIMIT $i,1";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
$img_pos = $row['img_pos'];
$sql = "UPDATE $tableImg SET img_pos = '$n' WHERE img_acc = '$accid' AND img_pos = '$img_pos'";
$res = mysql_query($sql);
$i++;
$n++;
}
mysql_close();
$tableImg is just a variable containing the table name, that works just fine.
I guessthe problem is somewhere around "$img_pos = $row['img_pos'];", because all the querys are used somewhere differently, be it slightly different, and they should work...
Thanks in advance!
I ended up simply doing this:
$i = 1;
while($row = mysql_fetch_array($res)){
$old_pos = $row['img_pos'];
$sql = "UPDATE $tableImg SET img_pos = $i WHERE img_acc = $accid AND img_pos = $old_pos";
$res = mysql_query($sql);
$i++;
};
This is quite possible, just totally unnecessary. The nice thing about digital data is that you don't have to look at it so it doesn't matter if it's a bit gappy, does it?
If you REALLY want to do this (say, you are building an application and you are just cleaning up the stuff you deleted whilst working on it) the following example will do in in SQL, as this simple example shows:
CREATE TABLE disorder (id int,stuff CHAR(6));
CREATE TABLE disorder2 (id SERIAL,stuff CHAR(6));
INSERT INTO disorder (id,stuff)
VALUES
('1','ONE'),
('2','TWO'),
('3','THREE'),
('4','FOUR'),
('5','FIVE');
DELETE FROM disorder WHERE id='3';
INSERT INTO disorder2 (stuff) SELECT stuff FROM disorder;
TRUNCATE TABLE disorder;
INSERT INTO disorder SELECT * from disorder2;
DROP TABLE disorder2;
This can be seen in action on sqlfiddle but it's pretty obvious. If you do a SELECT * from disorder, you will see why you probably shouldn't do this sort of thing.
Your tables really do need to have primary keys. This speeds searches/indexing and makes them useful. Look up database normal forms for a thorough discussion of the reasoning.

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);

simple php error but can't see where i'm going wrong?

I have the code below and I just want to count from the table members how many people have a 1 in the column loggedin and echo that back. I'm sure I'm missing something small, I just can't see it.
<?php
include ('functions.php');
connect();
$result = mysql_query("SELECT * FROM members WHERE loggedin = '1'");
$num_rows = mysql_num_rows($result);
$total_mem = $num_rows + (1223);
return $total_mem;
echo $total_mem;
?>
The echo will never be called because it is after the return statement.
Remove the return statement and the value should be shown.
Why not let your database do the counting for you?
$result = mysql_query("SELECT count('id') as logged_in_count FROM members WHERE loggedin = '1'");
$row = mysql_fetch_assoc($result);
$num_rows = $row['logged_in_count'];
$total_mem = $num_rows + (1223);
echo $total_mem;
return $total_mem;
You're never going to hit that echo statement, because you have a return statement right above it.
Why not use SELECT COUNT(1) FROM members WHERE loggedin = 1, and then pull the value directly from that? You'll save time because it will only need to return 1 row instead of all the rows, when all you want is the count.

Categories