I have the following in my database when I run SELECT type FROM office;
+--------------------------------------------------------+
| type |
+--------------------------------------------------------+
| a:2:{i:0;s:16:"Shared Workspace";i:1;s:9:"Workshops";} |
+--------------------------------------------------------+
How can I add an extra JSON value for another type of office. Basically I'd like it to add the type "Private Offices". So the value in my DB will then look like:
+-----------------------------------------------------------------------------------+
| type
+-----------------------------------------------------------------------------------+
| a:3:{i:0;s:16:"Shared Workspace";i:1;s:9:"Workshops";i:2;s:15:"Private Offices";} |
+-----------------------------------------------------------------------------------+
That's not JSON format. It looks like the output of PHP's serialize() function.
There's no SQL function to append values to serialized PHP data. You should fetch it into a PHP application, unserialize() it into a PHP array, then add data to the PHP array and update it back into the database.
Something like the following (some details have been omitted, like the WHERE conditions for the specific row you reference).
<?php
$pdo = new PDO(...);
$typeSerialized = $pdo->query("SELECT type FROM office WHERE ...")->fetchColumn();
$typeArray = unserialize($typeSerialized);
$typeArray[] = "Private Offices";
$typeSerialized = serialize($typeArray);
$stmt = $pdo->prepare("UPDATE office SET type = ? WHERE ...");
$stmt->execute([$typeSerialized]);
Related
I'd like to query from the reviewed_by table below where the "company" is "AAA" and "review" is "Need Review"
Here's mysql table :
+-----------+
| DATA_TYPE |
+-----------+
| text |
+-----------+
+-------------------------+
| reviewed_by |
+-------------------------+
|[{"company":"AAA","review":"OK","reviewed_at":"2021-01-26 08:59:26"}]|
|[{"company":"BBB","review":"OK","reviewed_at":"2021-01-26 08:59:26"}]|
|[{"company":"AAA","review":"Need Review","reviewed_at":"N\/A"}]|
+-------------------------+
Here's the #1 query i've tried :
SELECT * FROM `t_transaction`
WHERE `reviewed_by`
LIKE '%`"company":"AAA","review":"Need Review"`%'
Here's the #2 query i've tried :
SELECT * FROM `t_transaction`
WHERE `reviewed_by`
LIKE '%"company":"AAA","review":"Need Review"%'
ci3 query :
$like = ['reviewed_by','"company":"AAA","review":"Need Review"'];
$this->db->select('*')
->from('t_transacion')
->group_by('id')
->like($like[0],$like[1]);
The result i've got from those 2 queries was nothing,
How can i do this type of query (and also if using codeigniter 3) ?
MySql has some functions that allow you to do search over a json field. See documentation.
The reviewed_by column is a json array and you want to seach the first element of that array. Using the function JSON_EXTRACT you can extract data from the json field. In your case to get the json in the first position in the array so we execute JSON_EXTRACT(reviewed_by, '$[0]') which will return {"company":"...","review":"..","reviewed_at":"..."}. From the returned json we can call again the JSON_EXTRACT function to get a value given a key. If we select JSON_EXTRACT(JSON_EXTRACT(reviewed_by, '$[0]'), "$.company") this will return the company value from inside the json.
There are different ways to select what you want. I will give you two option and they have pros and cons. Take a look at this stackoverflow.
First approach using the where clause:
SELECT reviewed_by
FROM t_transaction
WHERE JSON_EXTRACT(JSON_EXTRACT(reviewed_by, '$[0]'), "$.company") = "AAA"
AND JSON_EXTRACT(JSON_EXTRACT(reviewed_by, '$[0]'), "$.review") = "Need Review";
Second approach using the having clause:
SELECT JSON_EXTRACT(reviewed_by, '$[0]') AS json
FROM t_transaction
HAVING json -> "$.company" = "AAA"
AND json -> "$.review" = "Need Review";
I have a two columns in database:- copy (which is array) and bookid. My code is;
$query = mysqli_query($db, "select copy from book_outward WHERE bookid like 'B1'");
while ($row = mysqli_fetch_array($query)) {
$copyid = $row['copy'];
}
Database shows like this
+----------------+
| id copy bookid |
+----------------+
| 1 1 B1 |
| 2 2,3 B1 |
| 3 4 B1 |
| 4 2 B2 |
+----------------+
but it stores only last values which was entered in 'B1'. I also tried
$copyid[] = $row['copy'];
but in this case I have to change array keys manually every time.
My aim is to insert copy into column bookid='B1' and before it has to make sure that only UNIQUE values can be stored in database for B1.
HTML :-
<input type="text" name="bookid" />
<input type="text" name="copies[]" />
PHP code for inserting:-
$book_id = $_POST['bookid'];
$copies = implode(',',$_POST['copies']);
$result = mysqli_query($db, "insert into book_outward(bookid,copy) values ('$book_id','$copies')");
As some of the comments mention it it not the best way to to it but it is possible.
You can obtain all the copyid data by:
$query = mysqli_query($db, "select copy from book_outward WHERE bookid like 'B1'");
$copyid = "";
while ($row = mysqli_fetch_array($query)) {
$copyid .= $row['copy'] . ",";
}
$copyidsFromDB = explode(",",rtrim($copyid , ','));
After that you can check if what you got in the request are in there using array_intersect:
$copies = $_POST['copies']
// if not an array use: $copies = explode(",", $_POST['copies'])
if (count(array_intersect($copies, $copyidsFromDB) == 0)
// insert to DB
Solved by myself by adding one line only
`$copies2 = explode(",",rtrim($copies , ','));`
before array_intersect Thanks code helps greatly.
So, sounds to me like the issue is the original data DB schema has some issues.
A sql-like DB is not a great place to put 'array' style value. It already has a mechanism for doing this: a link table.
That'd save you the trouble of having to manually shuffle around your primary keys in this table. It's way easier to check and validate.
If you HAVE to do this via php code, for example you don't have SQL access, like in a controlled build environment, you should take advantage of 'string keys' to on your $copyid, (hint rename to $copyidmap) to group together like pieces of data and preserve key relationships.
so the following would be unique:
map->{bookId}->{copyid}->{id} // Where id is that primary table id. Obviously, validate and do your undefined array assignments.
This is for a self test for a college job application so I am not necessarily looking for the exact statement I need, instead I am trying to get a hint as to what direction to look, I DO NOT have access to the actual database to view it:
This problem tasks us with getting some info on a user when given a NetID($user) and clear-text password($password). If the md5-hash of $password matches the Passwrd field for the given user, then display the user's UserID.
I am getting hung up using mysql_query, I feel like that is failing because it doesn't return any value that prints on the screen.
I think I have to us mysql_query not mysqli_query because the latter requires a connection, and in the instruction it says the connection all done for me, so I have no info to put into the connect command.
Here's my code:
<?
function checkPass($user, $password)
{
// You will likely want to use mysql_query($query) AND mysql_fetch_assoc($result);
// YOUR CODE HERE
$md5Password = md5($password);
$query = "SELECT interview_user_info.UserID,
FROM interview_user_info
WHERE interview_user_info.Passwd = '$md5Password'";
$escapedQuery = mysql_real_escape_string($query);
$queryResult = mysql_query($escapedQuery);
$rowArray = mysql_fetch_array($queryResult, 'MYSQL_NUM');
$UserID = $rowArray[0];
return $UserID;
}
?>
Here is the text and table info from the page:
int checkPass ( string $user , string $password )
Write a PHP function "checkPass" that takes two arguments: $user and $password and returns the UserID if the password matches the MD5 encoding of the appropriate password in the interview_user_info table below and -1 otherwise.
The $user variable contains the NetID of the individual; the $password variable contains a clear-text version of the password as submitted.
+---------------------------------------------------------------------------------+
| interview_user_info |
+-----------+-------------+-----------+--------+----------------------------------+
| UserID | LastName | FirstName | NetID | Passwd |
+-----------+-------------+-----------+--------+----------------------------------+
| 469562029 | Gonzalez | Shauntee | sgonz | 530b4a0ae65148d112537bc0eafba9c9 |
| 702930431 | Bates | Austin | abates | 9cdfb439c7876e703e307864c9167a15 |
+-----------+-------------+-----------+--------+----------------------------------+
The connection and database selection are taken care of. Write the query to pull data from the table "interview_user_info", and return the result. The connection will be closed for you.
Hint: You will likely need to make use of the following functions and possibly others: md5, mysql_query, mysql_fetch_assoc
I've been messing around with PHP once again. I am trying to retrieve information from a specific Column. So for example I'll do
http://127.0.0.1:8002/api/galaxy/rgalaxy.php?api&Name=Hi
The Column looks like this.
+----------------+-------+
| Name | Data |
+----------------+-------+
--> | Hi | Grab | <--
| Medium product | 9.99 |
| Large product | 15.99 |
+----------------+-------+
And It'll retrieve this info Grab
So since I put in Hi As the Parameter, It'll retrieve Grab
I have no idea how to do that. Would anyone mind helping?
$query = "SELECT column_name FROM table_name WHERE other_column = 'value'";
replace "column_name", "table_name", "other_column" and "value" by desired.
To get your 'Name' value from url use $_GET['Name']
Firstly, open a connection to your database
$connection = mysqli_connect('localhost', 'db_username', 'db_password, 'db_name');
Then, use this connection to perform your query
Edit : to avoid SQL injection
<?php
$name = '';
if(isset($_GET['Name'])){
$name = $_GET['Name'];
}
$connection = mysqli_connect('localhost', 'root', '', 'ett');
$query = 'SELECT name FROM items WHERE name like ?';
$stmt = $connection->prepare($query);
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$names_array = array();
while ($row = $result->fetch_assoc()) {
$names_array[] = $row;
}
Insert this Mysql query if you want only Data value as Grab
$name=$_GET['Name'];
$sql = "SELECT Data FROM YOUR_TABLE_NAME WHERE Name='.$name.' ";
and if you want to fetch more data like
| Hi | Grab |
| Medium product | 9.99 |
| Large product | 15.99 |
all then you need to add one more column who's value is common to all row and pass those column value to your url .
Your MySQL query will look something like this:
"SELECT * FROM your_table_name WHERE Name=$_GET['Name']"
Then you need to run the above query, and fetch it into a PHP variable and do whatever you want with that. I hope this helps you.
I have a PostgreSQL database with some information about projects contained with in it. So each project has a name, description and contact but I'm looking to just pull the name attribute from the table using PHP.
I currently have two projects in my database.
ID | Name |
1 | Fruit project |
2 | Vegetable project |
And I have a PHP script below which generates
$res = pg_query("SELECT * FROM projects");
$assoc = pg_fetch_assoc($res);
$result = $assoc['name'];
/* FETCHES THE RESULT OF THE SQL QUERY WHICH GETS THE NAME OF EACH PROJECT */
while($row = pg_fetch_assoc($res))
{
$output[]=$row['name'];
print (json_encode($output));
} /* CONVERTED ON MOBILE PLATFORM */
But the output of that file is current 'Vegatable project'. Could any provide some help on why the script isn't producing the first result as well?
Because you're stripping it out off the result before your loop:
$res = pg_query("SELECT * FROM projects");
$assoc = pg_fetch_assoc($res); // <-- remove
$result = $assoc['name']; // <-- remove
You call pg_fetch_assoc one time before the clycle - thet is the point where your first record is lost.
Just remove $assoc = pg_fetch_assoc($res);