Retrieve data into a variable with php and mysqli [duplicate] - php

This question already has answers here:
mysqli query results to show all rows
(4 answers)
Closed 4 years ago.
i've been trying for quite some time already to get this working, but no success at all
I looked around many places, and by what i understood, the method im using isnt retrieving the data i want, but in fact, ALL the data inside the DB (despite there only 1 value to be returned)
This is my code right now:
$query = "SELECT id from produtos where tipo = 'Tubo' and inteiro_pedaco = '$tipo' and marca = '$marca' and comprimento = '$comprimento' and diaexterno = '$externo' and diainterno = '$interno'";
$result = $conec->query($query);
echo $result;
die;
At the code above im trying to retrieve ID from a table named produtos
And here is the table 'produtos' content:
id: 102 | tipo: Tubo | inteiro_pedaco: Inteiro | marca: Science | comprimento: 1000 | diaexterno: 1 | diainterno: 1 |
id: 103 | tipo: Whatever | inteiro_pedaco: Whatever | marca: Whatever | comprimento: Whatever | diaexterno: Whatever | diainterno: Whatever |
etc...
$result variable was supposed to retrieve "102"
After retrieving 102, i want to echo it just for tests purposes
However, if i can manage to make it work and echo "102", my next step is making an insert into ANOTHER table with $result content, which is "102"
I want to insert at entrada_produtos table some data with the following command:
mysqli_query($conec,"INSERT INTO entrada_produtos (fk_id, usuario, data_inclusao, qtd) VALUES ('$result', '$usuario', now(), '$qtd')");
Any help would be appreciated, plus, i dont want just some code working, i would like to understand how it works
If possible, try to explain any code posted bellow, it would be of great help, also, i want to make it as simple as possible, i dont wanna use like 10 lines of code just to retrieve some data into a variable (if its the only possible way, then there's nothing i can do, but go this way...)
Thanks in advance

You need to fetch the results:
$row = $result->fetch_assoc();
$id = $row['id'];
echo $id;
fetch_assoc() returns the next row of results as an associative array.
You can then use the $id variable in your INSERT query.
There's no need to use two queries to insert this into another table, you can do that with one query.
$stmt = $conec->prepare("
INSERT INTO entrada_produtos (fk_id, usuario, data_inclusao, qtd)
SELECT id, ?, now(), ?
FROM produtos
where tipo = 'Tubo'
and inteiro_pedaco = ?
and marca = ?
and comprimento = ?
and diaexterno = ?
and diainterno = ?");
$stmt->bind_param("sssssss", $usuario, $qtd, $tipo, $marca, $comprimento, $externo, $interno);
$stmt->execute();
I've rewritten this as a prepared statement to prevent SQL injection. The ? in the query are placeholders, which are filled in with the variable values given in the call to bind_param().
BTW, if you're selecting the row that you just inserted into produtos, you can use the MySQL function LAST_INSERT_ID() or the PHP variable $conec->insert_id to get the auto-increment ID that was assigned, you don't need a query for that.

Related

Adding new column with static value to a select query result [duplicate]

This question already has answers here:
add extra column to sql query result with constant value
(2 answers)
Closed 5 months ago.
I want to know what is the best approach if I want to perform select query to MySQL database and then add a new column to the result array which will be exported to a file at later time?
To clarify the process, assume the table have the following data:
id name lastname email
1 john doe example#example.com
2 jane doe example2#example2.com
if I perform the following select query :
$query = "SELECT * from table_name";
$result = mysqli_query($conn, $query);
I get the previous result , and then I want to add a new column to it with static value for all the rows like the following:
Important note: I want to add the column to the returned result not to the database ,because this result is written into a file at a later time.
const_value id name lastname email
samevalue 1 john doe example#example.com
samevalue 2 jane doe example2#example2.com
currently I'm doing this using PHP:
while($row = mysqli_fetch_assoc($result))
{
array_unshift($row , 'samevalue');
}
So is there an easy method of doing this in php or in MySQL during the query ?
You can do that in the original query if that makes sense to your process like this
SELECT 'SameValue' as const_value, id, lastname, email from table_name;
If you really want to do it in PHP then something like this
while($row = mysqli_fetch_assoc($result))
{
$row['const_value'] = 'SameValue';
. . . your other code
}
Or if you want to keep all the rows for later processing
$rows = [];
while($row = mysqli_fetch_assoc($result))
{
$row['const_value'] = 'SameValue';
$rows[] = $row
}

How to seach a database column, and return matching rows [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 1 year ago.
I have the following database (Named "Account_info"):
|id (All Unique)|domain_name (All unique)| account_name |account_key|
|---------------|------------------------|----------------|-----------|
| 1 |example.com |account_23657612|889977 |
| 2 |example.net |account_53357945|889977 |
| 3 |example.edu |account_53357945|889977 |
| 4 |example.xyz |account_93713441|998822 |
I wish to search this database for the domain "example.net" and have the "Account Key" column for that domain be returned as a variable.
Example:
SEARCH TERM: example.net
RESPONSE: 889977
My code so far:
$domainSearch = "example.net";
$sql = mysqli_query($connect,"SELECT `account_name` FROM `Account_info` WHERE `domain_name`='$domainSearch'");
if($sql){
//Some code here that sets the variable "result" to "889977"
}
To get the Account Key as return, just fetch the data from the result set and returns it as an associative array
On the other hand, please use parametized parpared statement to avoid SQL injection attack.
Hence change
$sql = mysqli_query($connect,"SELECT `account_name` FROM `Account_info` WHERE `domain_name`='$domainSearch'");
to
$sql = "SELECT * FROM Account_info WHERE domain_name=?"; // SQL with parameters
$stmt = $connect->prepare($sql);
$stmt->bind_param("s", $domainSearch);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$user = $result->fetch_assoc(); // fetch data
echo $user["account_key"];
// to assign as a variable -- $var1=$user["account_key"];

SQL Use array and use result in select(sum) statement

I am trying to use the selected id's as an array a other statement. It seems it is not counting all the result as it is much lower that it is.. I have tried to find my answer on google but none of the options are working for me or i do not know how to use them in my case. There are no errors and i have error log on!
Here is my code, what am i doing wrong?
$counttheid = array();
$stmt3 = $mysqli->prepare("SELECT
id
FROM account
WHERE level <= '5' AND door = ? AND `group_name` = ? AND betaald = 'Yes'");
$stmt3->bind_param("ss",$usernamesession,$groupname);
$stmt3->execute();
$result3 = $stmt3->get_result(); //only works when nd_mysli is set on the server!
while ($rowid = $result3->fetch_assoc())
{
$counttheid[] = $rowid['id'];
$countid = implode(',', $counttheid);
}
$sql = "SELECT SUM(mobcash) AS totalcash FROM account WHERE id IN (?)
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$countid);
$stmt->execute();
$stmt->bind_result($row['totalcash']);
while($stmt->fetch()) $sumcash = $row['totalcash'];
//echo print_r($counttheid);
//echo implode(',', $counttheid);
echo $sumcash;
I am no profesional developer just started learning this, any help is welcome!
Since you have edited the question, my original answer is no longer relevant.
I suggest for you to simplify your two queries into a single query. In your first query you select a bunch of ids and in the second query you sum a different value from the same table using the ids. You can just to that in one query:
SELECT SUM(mobcash) AS totalcash
FROM account
WHERE level <= '5'
AND door = ?
AND `group_name` = ?
AND betaald = 'Yes';
Original answer
You use $result->fetch_all(MYSQLI_ASSOC), meaning each row from the result set will be an associative array with the column names as the keys and the cell values as values. That is also the case, if you only select one column.
That means for this example table
id | name | balance
----+------+---------
1 | acc1 | 12.34
2 | acc2 | 1.23
your variable $dataid will have the following value (for the simplified query SELECT id FROM account):
$dataid = [
[
"id": 1
],
[
"id": 2
]
];
To get more familiar with PHP, you could write some foreach loops yourself, but you can also use the built-in PHP function array_column (php.net: array_column):
$ids = array_column($dataids, "id");
From an SQL perspective I would also suggest for you to learn about nested queries, since you could avoid this PHP logic altogether.

Select mysql column (which is array) where other column is defined,:- and insert it into php variable

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.

Get row values as column names using Codeigniter and mysql

im using codeigniter and mysql as db. i know might can be solved with mysql query, but if anyone can solve with codeigniter query it will be awesome, otherwise normal PHP mysql query can work also.
I have Table with 3 columns, Well it have many feilds but i have shown here 4 enteries, i didnt wanted to make a table with many columns but only 1 row of data. so instead i went for this style of table as someone suggested me on this website.
Problem is i never worked with this kind of table.
SettingsID SettingsKey SettingsValue
----------------------------------------------------------------------
1 | facebookLink | facebook.com
2 | twitterLink | twitter.com
3 | youtubeLink | youtube.com
4 | googlePlusLink | googleplus.com
Now i want to run a query that should return me rows in to columns. i searched over net and found some solutions but i am not good with this new queries.
I suppose this guy had same kind of problem like i have but in his case he has same value repeated in column, where my SettingsKey has all the values unique.
Here is the link to similar kind of question :
mysql select dynamic row values as column names, another column as value
i cant understand his query and that query i am not sure if is any use of me.
Please can anyone help me build a query to return row values of SettingsKey as columns.
This should work:
<?php
$db = new PDO('mysql:host=localhost;dbname=DBNAME;charset=utf8', USERNAME, PASSWORD);
$stmt = $db->query("SELECT SettingsKey, SettingsValue FROM Settings");
$links = array();
while($row = $stmt->fetch()) {
$links[$row['SettingsKey']] = $row['SettingsValue'];
}
$db = null;
This code queries this table and for each row the SettingsKey and the SettingsValue will be shown.
Now you can get the facebookLink like this:
echo $links['facebookLink'];
Hope this helps.
$sql = "
SELECT SettingsKey, SettingsValue
FROM Settings
";
$q = $this->db->query($sql);
return $q->result_array();
Go to your controller
$data['settings'] = $this->model_selection->your_function();
$this->load->view('example', $data);
And lasty on your view
<?php if(!empty($settings)): ?>
<?php foreach($settings as $k => $v): ?>
//print your staff in here mix with html and go crazy
<?php endforeach; ?>
<?php endif ?>

Categories