The new item is added twice at the end of the column - php

I am trying to update the store column by adding new item (string) to the end of the column,
But what happens is the new item is added twice at the end of the column, This is the code:
$query = "SELECT * FROM users";
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
$item = 'item_name';
$store = $row['store'];
$newstore = $store . '|' . $item;
echo 'newstore : ' . $newstore . '<br>'; // It looks normal : store|item
$sql = "UPDATE users SET store='" . $newstore . "' WHERE username='" . $row['username'] . "'";
$conn->query($sql);
}
In in the database I find: store|item|item

Rather than reading the entire table and looping through it with PHP, run just a single UPDATE query to concatenate the extra data onto the column.:
$item = 'item_name';
$query = "UPDATE users SET store=concat(store,'|','$item')";
$result = $conn->query($query);
Note: this form is potentially open to SQL injection if you can't trust the value in $item. You'd do better to use a prepared query if that's the case.

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.

I Have this headache with PHP and MySQL

I have this problem:
function search_by_name($mysql, $name, $lastname)
{
$query = 'SELECT idKlienci FROM Klienci WHERE Imie = "' . $name . '"
AND Nazwisko = "' . $lastnem . '"';
$result = $mysql->query($query);
$row = mysqli_fetch_array($result); // I want to get the ID' of table `Klienci1`
// and here i don't know how many dimentions have this array
echo $row[0][0]; // prints nothing
}
$lastnem != $lastname
So change the query to use the correct variable name
$query = 'SELECT idKlienci
FROM Klienci
WHERE Imie = "' . $name . '"
AND Nazwisko = "' . $lastname . '"';
To make this kind of code easier to read you can also make use of the fact that variables in a double quoted string are automatically expanded. Which make this easier to read and therefore debug.
$query = "SELECT idKlienci
FROM Klienci
WHERE Imie = '$name'
AND Nazwisko = '$lastname'";
$result = $mysql->query($query);
// use mysqli_fetch_assoc() then you get only one assoc array
// so you can use named parameters to the array.
// the names will match the column names in the table
//$row = mysqli_fetch_array($result);
// also mysqli_fetch_assoc() only returns one row at a time
$row = mysqli_fetch_assoc($result);
// a row is always one dimensional so do
echo $row['id'];
So if you have more than one row in the resultset of your query you have to get the results in a loop
$result = $mysql->query($query);
while ( $row = mysqli_fetch_assoc($result)) {
echo $row['id'] . '<br>';
}
Now you should see both rows
MYSQL doesn't use double quotes for strings, it uses simple quotes:
$query = "SELECT idKlienci FROM Klienci WHERE Imie = '$name' AND Nazwisko = '$lastname'";
You can also add the variable directly into PHP strings when you're using double quotes, without the need to concatenate them.
Your Argument name $lastname & used variable $lastnem name are not same.
try this :
$row = mysqli_fetch_array($result);
echo $row[0];

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.

Update a sql table field one time with 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);
}

Query to import from Oracle to MySQL returning null object

I'm inserting data from oracle database to mysql database with php than insert and update, but I have a strange behaviour. The table oracle have 20851 records.
The problem is, in the record x, the query to mysql return me a empty result object, but the same query executed on MySQL returned objects with data.
With the following code I can insert and update data from oracle to mysql.
$stid = oci_parse($conn, 'SELECT * FROM B_PROGRAMA_EVALUACION_BIPS'); //oracle db
oci_execute($stid); //oracle db
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
$sql = "select ID_ITEM, ID_PROGRAMA from B_PROGRAMA_EVALUACION_BIPS WHERE ID_ITEM=".$row['ID_ITEM']." AND ID_PROGRAMA=".$row['ID_PROGRAMA'];
$result = $db->query($sql);
$rows = mysqli_fetch_array($result);
if ($rows['ID_ITEM'] == $row['ID_ITEM'] && $rows['ID_PROGRAMA'] == $row['ID_PROGRAMA']) {
$sql = "UPDATE B_PROGRAMA_EVALUACION_BIPS SET ID_PROGRAMA='".$row['ID_PROGRAMA'] . "', ANO='" . $row['ANO'] . "', COPIA='" . $row['COPIA'] . "', TIPO_PROGRAMA_ER='"
. $row['TIPO_PROGRAMA_ER'] . "', EVALUACION='".mysqli_real_escape_string($db, $row['EVALUACION'])."', ID_CARACTERICACION='".$row['ID_CARACTERICACION']."', NOTA='".$row['NOTA']."' WHERE ID_ITEM=".$row['ID_ITEM'];
} else {
$sql = "INSERT INTO B_PROGRAMA_EVALUACION_BIPS VALUES('".$row['ID_PROGRAMA'] . "','" . $row['ANO'] . "','" . $row['COPIA'] . "','"
. $row['ID_ITEM'] . "','".$row['ID_CARACTERICACION']."','".mysqli_real_escape_string($db, $row['EVALUACION'])."','".$row['TIPO_PROGRAMA_ER']."','".$row['NOTA']."')";
}
$result = $db->query($sql);
if ($result != 1) {
$resultado['B_PROGRAMA_EVALUACION_BIPS'] = $resultado['B_PROGRAMA_EVALUACION_BIPS'] + 1;
}
}
If I delete this line the second execute query, the first query working perfectly.
$result = $db->query($sql);
You should add single quotes around the values:
$sql = "select ID_ITEM, ID_PROGRAMA from B_PROGRAMA_EVALUACION_BIPS WHERE ID_ITEM='".$row['ID_ITEM']."' AND ID_PROGRAMA='".$row['ID_PROGRAMA']"'";

Categories