I have a MySQL table called furniture setup like this:
| id | name | identifier |
===================================
| 1 | "? Block" | "?-block" |
| 2 |"1-Up Block" | "1-up-block" |
| 3 |"Alarm clock"|"alarm-clock" |
When I run this PHP code, the string returned is 1-up-block but with a space at the beginning of the string; the MySQL interface does not show this space. It is screwing up my programming.
$id = 2;
$fier = '';
$prep_stmt = 'SELECT identifier FROM furniture WHERE id = ?';
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($identifier);
while ($stmt->fetch()) {
$fier = $identifier;
}
$stmt->close();
}
echo $fier;
Why would this space appear, and how can I get rid of it?
You could do a LIKE query for this. But Might be worth cleaning the DB and if you can adjust the script that insert this entry into the DB
SELECT name FROM furniture WHERE identifier LIKE "1-up-block"
Related
Im trying to get data from one table based upon the date in a column from another table. I've tried using an inner join but I can't quite figure out how to make it do what I want. Below is an example. Basicly the numbers in the rules column will referance the rule_id in the infraction rules table. Then output the rule long name in readable text.
user_infractions table
+--------+-----------------+------------------+----------------+
|ban_id | name | username | rules |
+--------+-----------------+------------------+----------------+
| 2 | bob | Bob | 2,7, |
| 7 | dave | dave1 | 3,5, |
+--------+-----------------+------------------+----------------+
infraction_rules table
+--------+-----------------+------------------+----------------+
|rule_id | rule number | short_name | long_name |
+--------+-----------------+------------------+----------------+
| 2 | 1.2.2 | Rule 2 | Rule 2 Long Na |
| 7 | 1.2.7 | Rule 7 | Rule 7 Long Na |
+--------+-----------------+------------------+----------------+
Below is the code im using to try to achieve this
$string = $row['rules']; //data from table as a string
$strtrim = rtrim($string,","); //removed trailing comma from string
$violations = explode(",", $strtrim); // string to array conversion
foreach($violations as $violation) {
echo $violation;
$sql3 = "SELECT *
FROM user_infractions
INNER JOIN infraction_rules ON user_infractions.rules = infraction_rules.rule_id
WHERE user_infractions.rules = ?;";
$stmt3 = $conn->prepare($sql3);
//$stmt -> mysqli_stmt_prepare($stmt, $sql);
$stmt3->bind_param("s", $violation);
$stmt3->execute();
$result3 = $stmt3->get_result();
if ($result3->num_rows > 0) {
while ($row3 = $result3->fetch_assoc()) {
echo $row3['rule_long_desc'];
}
}
}
I want to update the products in a cart table. If the user choose an option, the product id will change to the one with the desired option (each products are included in the products table with a different id by variant).
I made a nested request to select the product the user whant to change from the cart table, then find it in the product table, get the reference code, then find the siblings with the same reference code, and keep the good one with the desired variant. Finally, I update the cart table.
Is there a better way to do that? If yes, it will be faster or safer, or just easier to read?
Thank you.
$result = $conn->query("SELECT * FROM tbl_product
WHERE code=(SELECT code FROM tbl_product
WHERE id=(SELECT product_id FROM tbl_cart
WHERE id='".$_POST['cartId']."' AND member_id=$memberId))
AND option_1='".$_POST['option']."'");
$product = $result->fetch_assoc();
$query = "UPDATE tbl_cart SET product_id = ?, quantity = ? WHERE id = ? AND member_id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('iiii', $product['id'], $_POST["newQuantity"], $_POST["cartId"], $memberId);
$stmt->execute();
$stmt->close();
The table product:
+----+------------+--------+----------+--------+
| id | name | code | option_1 | price |
+----+------------+--------+----------+--------+
| 2 | Hard Drive | USB2 | | 199.90 |
| 3 | Watch | Wear | | 150.50 |
| 6 | Camera | 3DcA | L | 109.99 |
| 7 | Camera | 3DcA | XL | 119.99 |
| 8 | Camera | 3DcA | XXL | 129.99 |
| 9 | Camera | 3DcA | M | 99.99 |
+----+------------+--------+----------+--------+
The table cart:
+-----+------------+----------+-----------+
| id | product_id | quantity | member_id |
+-----+------------+----------+-----------+
| 176 | 6 | 1 | 1 |
+-----+------------+----------+-----------+
I added the two tables, to show you how they are made.
Maybe I have made a mistake on the way I built them.
Is this the good way to create parent/child structure?
First thing, that query is vulnerable to SQL injection. You should be using prepared statements for your SELECT in the same way that you are using them for your UPDATE.
From an execution standpoint, it is likely that your SQL engine is optimizing this query using Semi-Joins. That link explains how semi-join optimization works in MySQL. Because of that you probably aren't taking a performance hit.
It also looks like your first subquery is redundant, if product_id is already in tbl_products why do you need to do a subquery for a code in the same table?
That said, from a readability standpoint I would use JOINs from the beginning. Without seeing your schema, I can't be 100% sure but something like this is probably close to the Join version of the query.
$query = "SELECT products.* FROM tbl_cart cart
JOIN tbl_product products ON products.id = cart.product_id
WHERE cart.id = ?
AND cart.member_id = ?
AND products.option_1 = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param($_POST['cartId'], $memberId, $_POST['option']);
$stmt->execute();
$product = $stmt->fetch_assoc();
Note that the above assumes MySQL or MariaDB.
Consider MySQL's UPDATE...JOIN syntax and avoid the first SELECT query call. Below removes the redundant product_id assignment. Also, option_1 is handled in JOIN clause and is assumed to be a string value.
$query = "UPDATE tbl_cart c
INNER JOIN tbl_product p
SET c.product_id = p.id,
c.quantity = ?,
WHERE c.id = ?
AND c.member_id = ?
AND p.option_1 = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('iiis', $_POST["newQuantity"], $_POST["cartId"],
$memberId, $_POST['option']);
$stmt->execute();
$stmt->close();
Db Fiddle
I have a database structure :
WORK | NAME | USER_ID
5 | UL7 | 7
5 | LL5 | 7
6 | UR9 | 7
6 | UL7 | 7
i have wrote a function to fetch the data from db which is :
function fetchRegion($user_id){
global $mysqli;
$stmt = $mysqli->prepare("SELECT name,work from region WHERE user_id =?");
$stmt->bind_param("s",$id);
$stmt->execute();
$stmt->bind_result($work,$name);
while($stmt->fetch()){
$row[] = array('work'=>$work,'name'=>$name);
}
$stmt->close();
return $row;
}
Now the problem what i am facing is i want to represent the data as it should display
5 => UL7,LL5 and 6 =>UR9,UL7
But i am getting an output in an array. Now what can be done to represent the data to display in the above format rather in an array.
Thanks in advance!!
You could use the GROUP_CONCAT() function along with GROUP BY in your sql query like this:
SELECT `work`, GROUP_CONCAT(`name`) FROM `region` WHERE `user_id` =? GROUP BY `name`
Then, the fetched results would be like this:
work | name
------------
5 | UL7,LL5
6 | UR9,UL7
Hope it helps!
<?php
select1($conn);
function select2 ($conn,$id ,$name)
{
$stmt = $conn->prepare("SELECT def FROM define WHERE id = ?");
mysqli_stmt_bind_param($stmt, 'i', $id);
$stmt->execute();
$stmt->bind_result($def);
while($stmt->fetch()) {
echo $def . “<br>”
}
$stmt->close();
}
function select1 ($conn){
$stmt2 = $conn->prepare("SELECT id , name FROM words");
$stmt2->execute();
$stmt2->bind_result($id, $name);
while($stmt2->fetch()) {
select2 ($conn,$id ,$name);
}
}
?>
I have 2 php functions to select data from database. each record in words has multiple records in define table which I need to select. The first function is working correctly. the problem is that the second function is not working.
As #u_mulder mentions, you have improper double quotes in use.
Correct:
$stmt = $conn->prepare("SELECT def FROM define WHERE id = ?");
Incorrect:
$stmt2 = $conn->prepare("SELECT id , name FROM words”);
The ” character is not the same as " character. This will cause an issue in your Query. See more: https://www.cl.cam.ac.uk/~mgk25/ucs/quotes.html
Cleaned up:
<?php
select1($conn);
function select2($conn, $id, $name){
$stmt = $conn->prepare("SELECT def FROM define WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($def);
while($stmt->fetch()) {
echo $def . "<br>"
}
$stmt->close();
}
function select1 ($conn){
$stmt2 = $conn->prepare("SELECT id, name FROM words");
$stmt2->execute();
$stmt2->bind_result($id, $name);
while($stmt2->fetch()) {
select2($conn, $id, $name);
}
}
?>
Upon further inspection, I do not see where you use $id or $name, so I am not sure why you're performing 2 queries. I would advise a Join query.
<?php
function select1 ($conn){
$stmt = $conn->prepare("SELECT w.id, w.name, d.define FROM words AS w INNER JOIN define AS d ON w.id = d.id");
$stmt->execute();
$stmt->bind_result($id, $name, $def);
while($stmt->fetch()) {
echo "($id) $name $def<br />";
}
}
?>
Update
If you have table words:
+----+--------+
| id | name |
+----+--------+
| 1 | 'John' |
| 2 | 'Mary' |
| 3 | 'Bob' |
+----+--------+
And table define:
+----+--------------+
| id | def |
+----+--------------+
| 1 | 'Some stuff' |
| 1 | 'Other stuff'|
| 1 | 'More stuff' |
| 2 | 'Weird stuff'|
| 2 | 'Kind stuff' |
| 3 | 'Just stuff' |
+----+--------------+
We refer to this: What is the difference between "INNER JOIN" and "OUTER JOIN"?
The query could be a Regular Join:
SELECT a.id, a.name, b.def FROM word AS a JOIN define AS b ON a.id = b.id;
The result set should be:
+----+--------+--------------+
| id | name | def |
|----|--------|--------------|
| 1 | 'John' | 'Some stuff' |
| 1 | 'John' | 'Other stuff'|
| 1 | 'John' | 'More stuff' |
| 2 | 'Mary' | 'Weird stuff'|
| 2 | 'Mary' | 'Kind stuff' |
| 3 | 'Bob' | 'Just stuff' |
+----+--------+--------------+
Hope this helps explain your options.
What is the most simple way to fetch a list of elements using PHP PDO? There are so many fetch and fetch parameters that I'm not sure which is the right one.
Table Users
| id | username | age |
-----------------------
| 5 | Joey | 33 |
| 6 | Terry | 44 |
| 7 | Billy | 44 |
Query
$q = "SELECT username FROM Users WHERE age = 44";
$db->prepare($q)->execute();
$res = $db->fetch??(PDO::??);
echo json_encode($res);
// Should return, ideally, {"Terry", "Billy"}
If I use fetchColumn I seem to just get one result. If I use fetchAll with assoc_array, well I don't want to iterate over the array if I can avoid it.
Assuming $db is an instance of \PDO
$q = "SELECT username FROM Users WHERE age = :age";
$stmt = $db->prepare($q);
$stmt->bindParam(':age', 44, PDO::PARAM_INT);
$stmt->execute();
$objects = array();
while ($object = $stmt->fetch(PDO::FETCH_OBJ)) {
$objects[] = $object;
}
echo json_encode($objects);
I ended up using
$res = $stmt->fetchAll(PDO::FETCH_COLUMN);
return implode(",", $res);