I have a table in mysql called site_settings that looks like this
Table in PHPMyAdmin
I am trying to store all of my website settings in mysql and want to pull them into PHP as variables.
I want to pull all values from the variable_name column as the $variable names in PHP and have their values set to whats in the variable_type column.
$site_name = Vexed
$registration_enabled = False
here is my code:
$sql = connect($database_address, $database_username, $database_password, $database);
$query = "SELECT * FROM site_settings";
$result = $sql->query($query);
//$row = $result->fetch_all(MYSQLI_ASSOC);
while($row = $result->fetch_assoc())
{
$$row['variable_name'] = $row["variable_type"];
}
$arr = get_defined_vars();
print_r($arr);
the last two lines i am using to see if the variable have been created but i cant get it to work. the best result i have got so far is
[Array] => Array
(
[variable_name] => Vexed
)
Can anyone tell me where i am going wrong?
Thanks in advance to anyone who can help.
What you're trying to duplicate is PHP's extract() builtin function.
It's generally considered a bad practice, because it will make your code harder for readers to understand or debug.
What is so wrong with extract()?
How to demonstrate an exploit of extract($_POST)?
https://dzone.com/articles/php-bad-practice-use-extract
https://blog.josephscott.org/2009/02/05/i-dont-like-phps-extract-function/
What I think is happening is that when you call $$arr['variable_name'] it's actually doing $$arr first (which evaluates to $Array after the string conversion), and then trying to assign into assign the ['variable_name'] key into $Array.
I would expect this minor modification to work:
$sql = connect($database_address, $database_username, $database_password, $database);
$query = "SELECT * FROM site_settings";
$result = $sql->query($query);
//$row = $result->fetch_all(MYSQLI_ASSOC);
while($row = $result->fetch_assoc())
{
$name = $row['variable_name'];
$$name = $row["variable_type"];
}
$arr = get_defined_vars();
print_r($arr);
Edit: I'll also echo, that it's a little bit weird to dynamically create variables in this way and it will make your code hard to follow.
So I'm trying to build an image uploading website and wish to access a mysql table using a query ..now I wish to store all the arrays obtained from these queries into one single array. I then wish to access all the elements of this array. How should I do it?
This is what I tried:
$allimages = array();
$sql="SELECT uploaderId FROM foostable WHERE foo='bar'";//a query which fetches the image uploader's id from the foostable ..you don't need to worry about this part just know that this query returns more than one uploaderIds
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result)){
$uploaderId=$row['uploaderId'];
$sql1="SELECT uploader FROM imagestable WHERE uploaderId='$uploaderId' ORDER BY datetime DESC";
$result1=mysqli_query($conn, $sql1);
$row1=mysqli_fetch_assoc($result1);
$allimages=$allimages+$row1;
}
foreach ($allimages as $ai) {
echo $ai['uploader'];
}
When I run this code, I get the following error:
Warning: Illegal string offset 'uploader' in...
I'm definitely doing something wrong but am not able to figure out what that is.
I've been looking everywhere for this but am not able to find it therefore I posted this question! I'm really new to this and any help would be really really appreciated! Thank you! :)
You're adding new elements to your array the wrong way.
Change
$allimages=$allimages+$row1;
to
$allimages[] = $row1; // Short for array_push($allimages, $row1)
Read more about array_push() in the manual
SELECT i.uploader
FROM foostable f
JOIN imagestable i
ON i.uploaderid = f.uploaderId
WHERE f.foo = 'bar'
ORDER
BY i.datetime DESC
You could write a single query to obtain the desired results. Please try the following code:
$allimages = array();
$sql = "SELECT i.uploader, i.datetime
FROM imagestable i INNER JOIN foostable f
ON i.uploaderId = f.uploaderId
AND f.foo = 'bar'
ORDER BY i.datetime DESC";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result)){
$allimages[] = $row['uploader'];
}
print_r($allimages);
You should just be able to do:
$allImages[] = $row1;
This should just push the new array to the end of allImages array everytime the loop runs.
The intention with the below code is to extract messages from a mysql table, and put each of them inside ONE array with {} around each output. Each output consists of various parameters as you can see, and is an array in itself.
What the code does is that each time the loop is processed, in the JSON array that this later is converted into, it wraps the output in []´s, hence it´s now a new array which is created.
What I get is:
[{"sender":"ll","message":"blah","timestamp":"2016-12-21 14:43:04","username":"","msgtype":"","threadid":"32629016712222016034323"},{"sender":"kk","message":"blahblah","timestamp":"2016-12-21 14:43:23","username":"","msgtype":"","threadid":"32629016712222016034323"},{"sender":"ll","message":"blahblahblah","timestamp":"2016-12-21 14:43:47","username":"","msgtype":"","threadid":"32629016712222016034323"}],[{"sender":"ll","message":"blahblahblahblah","timestamp":"2016-12-21 14:43:04","username":"","msgtype":"","threadid":"92337321312222016034304"},{"sender":"kk","message":"blahblahblahblahblah","timestamp":"2016-12-21 14:44:05","username":"","msgtype":"","threadid":"92337321312222016034304"}]]
And what I want is:
[{"sender":"ll","message":"blah","timestamp":"2016-12-21 14:43:04","username":"","msgtype":"","threadid":"32629016712222016034323"},{"sender":"kk","message":"blahblah","timestamp":"2016-12-21 14:43:23","username":"","msgtype":"","threadid":"32629016712222016034323"},{"sender":"ll","message":"blahblahblah","timestamp":"2016-12-21 14:43:47","username":"","msgtype":"","threadid":"32629016712222016034323"}],{"sender":"ll","message":"blahblahblahblah","timestamp":"2016-12-21 14:43:04","username":"","msgtype":"","threadid":"92337321312222016034304"},{"sender":"kk","message":"blahblahblahblahblah","timestamp":"2016-12-21 14:44:05","username":"","msgtype":"","threadid":"92337321312222016034304"}]
How do I proceed to get the right result here?
$data = array ();
foreach($threads as $threadid){
$sql = ("SELECT sender,message,timestamp,username,msgtype,threadid FROM Messages WHERE threadid = '$threadid' AND subject = '' AND timestamp > '$newtimestamp' ORDER BY timestamp");
$arrayOfObjects = $conn->query($sql)->fetchAll(PDO::FETCH_OBJ);
$data[] = $$arrayOfObjects;
}
And FYI, $threadid is another array containing... threadids, and the loop correctly fetches these one by one, that´s not where the problem is.
Thanks in advance!!
You are doing O(N) database queries, consider doing just O(1) using an IN expression in your where clause. No need for a foreach loop and you'll get all your data in one array.
SELECT ... FROM Messages WHERE threadid IN (1, 2, 3, ...) AND ...
You might have to use a prepared statement for that.
I think you are searching for PDO::FETCH_OBJ.
You had FETCH_ASSOC, which will return an array of associative arrays.
FETCH_OBJwill return an array ob stdObjects.
Also you reassigned $array to itself when doing $array[] = $array;..
$data = array();
foreach($threads as $threadid){
$sql = ("SELECT sender,message,timestamp,username,msgtype,threadid FROM Messages WHERE threadid = '$threadid' AND subject = '' AND timestamp > '$newtimestamp' ORDER BY timestamp");
// here it is:
$arrayOfObjects = $conn->query($sql)->fetchAll(PDO::FETCH_OBJ);
$data[] = $arrayOfObjects;
}
// now you can encode that as json and show it:
echo json_encode($data);
#akuhn
Well, I decided to give your suggestion one more try, and managed to do it in a none prepared way. I´m aware that this is supposed to be risky, but so far this project just needs to work, then have the php codes updated to safer versions, and then go live. It works, so thanks a bunch!
$sql = ("SELECT sender,message,timestamp,username,msgtype,threadid FROM Messages WHERE threadid IN ('" . implode("','",$threadid) . "') AND subject = '' AND timestamp > '$newtimestamp' ORDER BY timestamp");
$data = $conn->query($sql)->fetchAll(PDO::FETCH_OBJ);
I want retrieve data from mysql database and store in an array. Later I would display the data in html.
Below is my code snippet:
select co_no from faculty_co where course_code='$course1_code';
The output will display a total 5 co_no values. I want to store this values in an array and display as dropdown menu in html using select tag.
I am new to php. Please tell me how do I retrieve and store it.
I'm 'old school', and not much of a programmer, so I tend to do things procedurally.
I do it something like this:
include('path/to/connection/stateme.nts'); // the connection is a variable '$db'
$query = "my query";
$result = mysqli_query($db,$query);
$rows = array(); //initialise array
while($row = mysqli_fetch_assoc($result)){
$rows[] = $row;
}
Now you can store that as a json_encoded string or just retain it as an array for later use.
First off, php.net has a lot of documentation on mysql and other things and is pretty easy to understand.
Check out the documentation and examples here.
I have a rather complex situation that I need to get working, for some reason I am almost there but still not quite.
In PHP I create arrays and send to it javascript through json, I am quite sure that my problem is in this part of the code.
$insertIDs = array();
foreach($recipients as $userID)
{
//MySQL insert removed from question
$insertID = mysql_insert_id();
array_push($insertIDs, $array[$userID] = $insertID);
}
$json = array();
$json['fromID'] = $session;
$json['insertIDs'] = $insertIDs;
$json['recipients'] = $recipients;
echo json_encode($json);
when I console.log the results of this in javascript, I get:
{ messageID: 40,
fromID: '1',
insertIDs: [ 44 ],
recipients: [ '3' ] }
Now in javascript when I try to access the insertIDs by the userID which I set it to be in the php above, I just get undefined as a result. How can I do this so I can access each insertID by the userID?
for example: json.insertIDs[userID]
if I simply call it by: json.insertIDs[0] it does return the first insertID, however when there are multiple I need to be able to have an easy way to access each usersID insertID.
I'm not quite sure what you are trying to do, since in the forloop $insertID is always the same value but:
It seems like json.InsertIDs is an array of the form json.InsertIds = Array(44);
Where as you want it to be Array(3 => 44)
try changing your forloop from
foreach($recipients as $userID){
$insertID = mysql_insert_id();
array_push($insertIDs, $array[$userID] = $insertID);
}
to
foreach($recipients as $userID){
$insertID = mysql_insert_id();
$insertIDs[$userID] = $insertID;
}
It seems like the value returned by mysql_insert_id() would be the same every time, unless there was an INSERT query inside that foreach() loop. Is part of the code missing?