Update a sql table field one time with php - php

Below is my small code for inserting some info into AthleteID. It doesn't actually insert the information to the table though, any help is appreciated. (sorry for asking twice, but I think my first question isn't addressing whatever issue is holding me up here!)
<?php
require_once('resources/connection.php');
echo 'hello noob' . '<br />';
$query = mysql_query('SELECT LName, MyWebSiteUserID FROM tuser WHERE MyWebSiteUserID = MyWebSiteUserID');
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebSiteUserID"];
$update = "UPDATE `tuser` SET `AthleteID`='$athleteId' WHERE `MyWebSiteUserID` = `MyWebSiteUserID`;";
while($row = mysql_fetch_array($query)){
mysql_query( $update);
}

Where to begin..
1) Your using mysql and not mysqli. mysql is now deprecated but you could be on a PHP 4 system so keep that in mind.
2) You are building the $athleteID before you have found out what LName and SkillshowUserID is.
3) Your using a where of 1 = 1. You dont need this as it will return true for every row.
4) So...
// Execute a query
$results = mysql_query('SELECT LName, MyWebsiteID FROM tuser WHERE SkillshowUserID = SkillshowUserID');
// Loop through the result set
while($row = mysql_fetch_array($query))
{
// Generate the athleteId
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebsiteID"];
// Generate an sql update statement
$update = "UPDATE `tuser` SET `AthleteID`='" . $athleteId . "' " .
" WHERE LName = '" . $row['LName'] . "' " .
" AND MyWebsiteID = '" . $row['MyWebsiteID'] . "';";
// Fire off that bad boy
mysql_query($update);
}

Related

Joining two tables based off a condition SQL

I am building an android app that uses geo location. I am trying to improve my overall app to improve its smoothness while running. I am using volly to connect to a php page on my web sever where the php page can then access my phpmyadmin database. My php page for updating locations is a horrible mess and I was hoping it can be fixed with the right sql query.
Lets get down to it.
So I have a table named users
and a table named friends
In this particular example david is friends with mark and jack. Also to clarify mark and jack are friends with david.
What I need to do is Write a query if given a user ID say for example 3 that will produce a table of that person and his friends ID, cordsV1, cordsV2 without any duplicate IDs in the table.
I was able to get this to work with using loops and variables ect but as I said it is a horrible mess.
Here is my current all sql query attempt:
SELECT DISTINCT ID, cordsV1, cordsV2 FROM `friends`,`users` WHERE user_one_ID = 1 AND status = 1;
HOWEVER this just returns all of the user IDs from the user table. I am really bad with sql so if someone could point me in the right direction it would be much appreciated.
Here is my horrible mess of code if you were wondering:
<?php error_reporting(E_ALL | E_STRICT); ?>
<?php
$THIS_USER_ID = $_GET['THIS_USER_ID'];
try {
$one = 1;
$db = new PDO("");
$sql = "SELECT * FROM friends WHERE user_one_ID = '" . $THIS_USER_ID . "' AND status = '" . $one . "' OR user_two_ID = '" . $THIS_USER_ID . "' AND status = '" . $one . "'";
$rows = $db->query($sql)
->fetchAll(PDO::FETCH_ASSOC);
$printMe = [];
foreach($rows as $row){
$printMe[] = $row;
}
$jsonArr = json_encode($printMe);
$characters = json_decode($jsonArr, true);
// Getting the size of the sample array
$size = sizeof($characters);
$neg = -1;
$sql2 = "SELECT * FROM users WHERE ID = '" . $neg . "'";
$sql3 = "";
$sql4 = "";
for ($x = 0; $x < $size; $x++ ){
if ($characters[$x]['user_one_ID'] == $THIS_USER_ID && $characters[$x]['status'] == 1){
$hold = $characters[$x]['user_two_ID'];
$sql3 = $sql3 . " OR ID = '" . $hold . "'";
} else if($characters[$x]['user_two_ID'] == $THIS_USER_ID && $characters[$x]['status'] == 1) {
$hold = $characters[$x]['user_one_ID'];
$sql4 = $sql4 . " OR ID = '" . $hold . "'";
}
}
$sql5 = $sql2 . $sql3 . $sql4;
$sql7 = "SELECT * FROM users WHERE ID = '" . $THIS_USER_ID . "'";
$printMe2 = [];
$rows3 = $db->query($sql7)
->fetchAll(PDO::FETCH_ASSOC);
foreach($rows3 as $row3){
$printMe2[] = $row3;
}
$rows2 = $db->query($sql5)
->fetchAll(PDO::FETCH_ASSOC);
foreach($rows2 as $row2){
$printMe2[] = $row2;
}
$jsonArr2 = json_encode($printMe2);
echo $jsonArr2;
$db = null;
} catch(PDOException $ex) {
die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}
?>
Get the user-data
SELECT
*
FROM
users
WHERE ID = ?
Get the user-data of friends
SELECT
users.*
FROM
friends
JOIN
users ON users.ID = friends.user_two_ID
WHERE
friends.user_one_ID = ?
Better use prepared statements, or your app wont be alive very long due to SQL-Injections.
You also want to have a look at meaningful names.

Retrieving data belonging to a session and user id

I am trying to obtain data from the current session and the field "bidder_id" from tbl_bidder where the field "accept" has the value Accepted, but I get data of all the users in that table which is not I want. This is my code
<?php } else if (($_SESSION['Usertype']) == 'recruiter') { ?>
<table class="table table-hover">
<?php
$u_id = $_SESSION['UserID'];
$notifyR = " SELECT bidid, recbid_id, bidder_id, selected, accept FROM tbl_bides WHERE recbid_id = '" . $u_id . "'";
$ResultR = mysql_query($notifyR, $con);
while ($rowR = mysql_fetch_array($ResultR)) {
if ($rowR['accept'] == "Accepted") {
echo "<h3 style='color:#001F7A;'><b>You Have Updates </b><i class='fa fa-bell-o'></i></h3>";
echo $rowR['bidder_id'];
}
$recR = "SELECT users_id, first_name, last_name FROM tbl_users WHERE users_id = '" . $rowR['bidder_id'] . "'";
$recResultB = mysql_query($recR, $con)or die(mysql_error());
while ($rowre = mysql_fetch_array($recResultB)) {
echo " <tr><td>" . $rowre['first_name'] . " " . $rowre['last_name'] . "</td></tr>";
}
}
?>
Please help!!!
Change From
$notifyR = " SELECT bidid, recbid_id, bidder_id, selected, accept FROM tbl_bides WHERE recbid_id = '" . $u_id . "'";
To
$notifyR = " SELECT bidid, recbid_id, bidder_id, selected, accept FROM tbl_bides WHERE recbid_id = '" . $u_id . "' and accept = 'Accepted' ";
add this on your query and accept = 'Accepted' in $notifyR
I hope you might need to use the following query if you stored the user id in $_SESSION['UserID']. May be logical error: And also use mysqli_query instead of mysql_query which is deprecated in latest php versions. And instead of binding the variable directly in query, use bind param of prepared statement.
$recR = "SELECT users_id, first_name, last_name FROM tbl_users WHERE users_id = '" . $_SESSION['UserID'] . "' LIMIT 1";
If you only want to execute the second query (selecting the user associated with the given bid) when the bid has been "accepted" then you need to move that code into your conditional:
if ($rowR['accept'] == "Accepted") {
echo "<h3 style='color:#001F7A;'><b>You Have Updates </b><i class='fa fa-bell-o'></i></h3>";
echo $rowR['bidder_id'];
$recR = "SELECT users_id, first_name, last_name
FROM tbl_users
WHERE users_id = '" . $rowR['bidder_id'] . "'";
$recResultB = mysql_query($recR, $con)or die(mysql_error());
while ($rowre = mysql_fetch_array($recResultB)) {
echo " <tr><td>" . $rowre['first_name'] . " " . $rowre['last_name'] . "</td></tr>";
// echo $rowre['users_id'];
}
}
You may want to consider using a newer interface to MySQL, such as PDO, and protecting your code from SQL injection attacks by using techniques such as prepared statements or at least input cleansing.

MySQL does not retrieve first item in PHP

I've now been trying for hour and can't figure the problem out. I've made a php file that fetch all items in a table and retrieves that as JSON. But for some reason after I inserted the second mysql-query, it stopped fetching the first item. My code is following:
...
case "LoadEntryList":
$result2 = performquery("SELECT * FROM Entries WHERE Category = '" . $_POST["Category"] .
"' LIMIT " . $_POST["Offset"] . ", " . $_POST["Quantity"] . "");
$row2 = $result2->fetch_assoc();
while($row = $result2->fetch_assoc()) {
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row2["UserID"] . "'");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,
strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
...
Any help is greatly appreciated.
EDIT: Thanks for all those super fast responses.
First you're fetching a row:
$row2 = $result2->fetch_assoc();
Then you start looping at the next row:
while($row = $result2->fetch_assoc()) {
If you want to loop over all of the rows, don't skip the first one. Just loop over all of the rows:
$result2 = // your very SQL-injectable query
while($row2 = $result2->fetch_assoc()) {
$result3 = // your other very SQL-injectable query
$row3 = $result3->fetch_assoc();
// etc.
}
Note that errors like this would be a lot more obvious if you used meaningful variable names. "row2", "result3", etc. are pretty confusing when you have overlapping levels of abstraction.
Important: Your code is wide open to SQL injection attacks. You're basically allowing users to execute any code they want on your database. Please look into using prepared statements and treating user input as values rather than as executable code. This is a good place to start reading, as is this.
No Need of $row2 = $result2->fetch_assoc();
<?
case "LoadEntryList":
$result2 = performquery("SELECT * FROM Entries WHERE Category = '" . $_POST["Category"] .
"' LIMIT " . $_POST["Offset"] . ", " . $_POST["Quantity"] . "");
while($row = $result2->fetch_assoc())
{
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row["UserID"] . "'");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
?>
Or,
<?
...
case "LoadEntryList":
$Category=$_POST["Category"];
$Offset=$_POST["Offset"];
$Quantity=$_POST["Quantity"];
$result3 = performquery("SELECT Entries.*, Users.Username FROM Entries, Users WHERE Entries.Category=$Category AND Entries.UserID=Users.ID LIMIT $Offset, $Quantity");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
...
?>
I have a addition to David answer(can't comment on it yet)
This line of code:
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row2["UserID"] . "'");
will always return with the same result. If you were to change $row2[... into $row[... the code would take the rows that get updated by the while loop.
I am not content with the accepted result. The snippet can be fixed / replaced, and also a bad code must be replaced. Also not to mention is that I don't know if anyone spotted a really big mistake in the output. Here is the fix and I'll explain why.
$JSON = array();
$result2 = performquery( '
SELECT
e.*, u.Username
FROM Entries AS e
LEFT JOIN Users AS u ON u.ID = e.UserID
WHERE
e.Category = ' . $_POST['Category'] . '
LIMIT ' . $_POST['Offset'] . ', ' . $_POST['Quantity'] . '
' );
while( $row2 = $result2->fetch_assoc() ){
$JSON[] = $row2;
}
echo json_encode( $JSON );
Obviously the main issue is the query, so I fixed it with a LEFT JOIN, now the second part is the output. First it's the way you include the username, and the second what if you had multiple results? Than your output will be:
{"ID":1,"Username":"John"}{"ID":2,"Username":"Doe"}
How do you parse it? So the $JSON part comes in place. You add it to an array and will encode that array. Now the result is:
{["ID":1,"Username":"John"],["ID":2,"Username":"Doe"]}
LE: I left out the sql inject part which as stated by the OP, will be done afterwards? I'm not sure why not do it at the point of writing it, because you may forget later on that you need to sanitize it.

Simple PHP / MySQL data results

I grabbed this piece of code off the Internet and modified it slightly to fit my needs but it doesn't work and I don't know why. I'm sure I've overlooked something but I don't know enough about PHP to know what I'm doing wrong. The uid is showing up, but nothing else. I'm just trying to get information from the MySQL data based on the user's session id. I checked the database to make sure that the uid that shows matches the data -- it does.
<?php
include("connect.php");
session_start();
$uid = $_SESSION['user_id'];
$result = mysql_query("SELECT * FROM users WHERE id = ' . $uid . '");
if ($result) {
echo "Connect"; } else
{ die('Invalid query: '.mysql_error()); }
$info = mysql_fetch_array($result);
echo "<br>ID: ", $uid;
echo "<br>Full Name: " .$info['full_name'] ;
echo "<br>User Name: " .$info['user_name'] ;
echo "<br>";
?>
p.s. - Yes, I know that mysql_query (and other syntax like it) has been deprecated.
$result = mysql_query("SELECT * FROM users WHERE id = '" . $uid . "'"); // not ' . $uid . '
NOTE: You were searching for . ID . not actual ID
Query should be as
$result = mysql_query("SELECT * FROM users WHERE id = $uid ");
Assuming id is int in the table
You had
$result = mysql_query("SELECT * FROM users WHERE id = ' . $uid . '");
^.... ^.... was the issue.

Why is this SQL query not working?

this script have to update things on every refresh but not working. lend me a hand
$yp = mysql_query("select id from yyy where twitterid = '$tid'");
$qq = "update yyy set twitterid = '$tid',
twitterkullanici = '$twk',
tweetsayisi = '$tws',
takipettigi = '$tkpettigi',
takipeden = '$tkpeden',
nerden = '$nerden',
bio = '" . mysql_real_escape_string($bio) . "',
profilresmi ='$img',
ismi = '$isim'
where id = '$yp'";
$xx = mysql_query($qq);
Looks like you are not getting the value out of the variable $yp.
You need to do
$row = mysql_fetch_row($yp);
then
id = '.$row[0] .'
in your update query
$yp - is a result of mysql_query (resource). You have to read id from database (mysql_fetch_array or mysql_fetch_row).
$yp = mysql_query("select id from yyy where twitterid = '$tid'");
if ($yp)
{
if ($row = mysql_fetch_array($yp,MYSQL_ASSOC))
$id = $row["id"];
}
Now use $id in WHERE clause.
To make debugging SQL easier in PHP add the following after to your mysql_query(0 call.
mysql_query($qq) or die("A MySQL error has occurred.<br />Your Query: " . $qq. "<br /> Error: (" . mysql_errno() . ") " . mysql_error())
Just make sure you remove it before you go into prod, as it can give useful info away to any hackers attempting Sql Injection.

Categories