I Have this headache with PHP and MySQL - php

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

Related

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

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.

How to pass multiple columns to a variable in php

I'm working on a project which requires more than one column contents to be passed to a php variable
I am able to select and pass one column content to the variable but failed on multiple columns
$myEMPNEM = "";
$sqlNEM = "SELECT first_name, middle_name, last_name, job_title FROM
t_employees WHERE user_name = '" . $_SESSION["uname"] . "'";
$resultNEM = mysqli_query( $conn, $sqlNEM );
while($row = mysqli_fetch_array($resultNEM))
{
$myEMPNEM = $row['first_name'];
}
I expect more than one column content to be passed to the php variable
You either need to use the variable as an array:
while($row = mysqli_fetch_array($resultNEM))
{
$myEMPNEM = array($row['first_name'], $row['middle_name'], $row['last_name']);
}
Or concatenate the values together into a single string:
while($row = mysqli_fetch_array($resultNEM))
{
$myEMPNEM = $row['first_name'] . " " . $row['middle_name'] . " " . $row['last_name'];
}

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.

How do I get columns from a joined table in PHP?

For a single table, I normally do something like this:
$length = 42;
$result = mysql_query ('SELECT * FROM table WHERE length = "' . $length . '"', $dbconn);
$rowsfound = mysql_num_rows ($result);
if ($rowsfound == 1) {
$row = mysql_fetch_array ($result);
$tableid = $row ['table_id'];
$tablecloth = $row ['tablecloth'];
$height = $row ['height'];
...
But how to I get the rows from a joined table like this:
$chairid = 123;
$result = mysql_query ('SELECT * FROM table,chair WHERE chair.id = "' . $chairid . '" AND table.table_id = chair.table_id', $dbconn);
$rowsfound = mysql_num_rows ($result);
if ($rowsfound == 1) {
$row = mysql_fetch_array ($result);
$tableid = $row ['table.table_id'];
$tablecloth = $row ['table.tablecloth'];
$height = $row ['table.height'];
...
This doesn't return any values in $table.tablecloth. What am I doing wrong?
do this with JOIN instead
SELECT * FROM table
INNER JOIN chair ON table.table_id = chair.table_id
WHERE chair.id = "' . $chairid . '"
The reason you are not getting any results is because your query is failing. table is a reserved word so you need to add back ticks around it as follows:
$result = mysql_query ('SELECT * FROM `table`,`chair` WHERE `chair`.id = "' . $chairid . '" AND `table`.table_id = `chair`.table_id', $dbconn);
You would had figured this out if you had proper error handling in place like following (note the or die():
$result = mysql_query ('SELECT * FROM `table`,`chair` WHERE `chair`.id = "' . $chairid . '" AND `table`.table_id = `chair`.table_id', $dbconn) or die(mysql_error())
Please refer to the list of reserved words here: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Apart from this, as Kim pointed out you also need to fix the extra closing parenthesis.
You would be better doing a proper JOIN like echo_Me suggested but this is the proper syntax for the way you are coding it.
$result = mysql_query ('SELECT table.*,chair.* FROM table,chair WHERE chair.id = "' . $chairid . '" AND table.table_id = chair.table_id', $dbconn);
Then
if ($rowsfound == 1) {
$row = mysql_fetch_array ($result);
$tableid = $row ['table_id'];
$tablecloth = $row ['tablecloth'];
$height = $row ['height'];
The results do not get returned with the table name in front of the column names. This can cause a problem if you have a column name with the same name in both tables.
I think you have extra closing parenthesis?? )
$tableid = $row ['table.table_id']);
$tablecloth = $row ['table.tablecloth']);
$height = $row ['table.height']);

PHP query does not return result

This query is not returning any result as there seems to be an issue with the sql.
$sql = "select region_description from $DB_Table where region_id='".$region_id."' and region_status =(1)";
$res = mysql_query($sql,$con) or die(mysql_error());
$result = "( ";
$row = mysql_fetch_array($res);
$result .= "\"" . $row["region_description"] . "\"";
while($row = mysql_fetch_array($res))
{
echo "<br /> In!";
$result .= " , \"" . $row["region_description"] . "\"";
}
$result .= " )";
mysql_close($con);
if ($result)
{
return $result;
}
else
{
return 0;
}
region_id is passed as 1.
I do have a record in the DB that fits the query criteria but no rows are returned when executed. I beleive the issue is in this part ,
region_id='".$region_id."'
so on using the gettype function in my php it turns out that the datatype of region_id is string not int and thus the failure of the query to function as my datatype in my tableis int. what would be the way to get parameter passed to be considered as an int in php. url below
GetRegions.php?region_id=1
Thanks
Try it like this:
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"
The region_id column seems to be an integer type, don't compare it by using single quotes.
Try dropping the ; at the end of your query.
First of all - your code is very messy. You mix variables inside string with escaping string, integers should be passed without '. Try with:
$sql = 'SELECT region_description FROM ' . $DB_Table . ' WHERE region_id = ' . $region_id . ' AND region_status = 1';
Also ; should be removed.
try this
$sql = "select region_description from $DB_Table where region_id=$region_id AND region_status = 1";
When you are comparing the field of type integer, you should not use single quote
Good Luck
Update 1
Use this.. It will work
$sql = "select region_description from " .$DB_Table. " where region_id=" .$region_id. " AND region_status = 1";
You do not need the single quotes around the region id i.e.
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"

Categories