php mysql query with multiple params and get individual results per - php

Im trying to think of a way to form a query where I can query for each parameter I need, and get the results back on a per param basis. Ive tried a combination of AND/OR but not getting the expected results.
the basis of the query I wanna do is to the extent of
select fb_wall, fb_checkin, phone
from member_prefs where
memeberid = 21
OR memeberid = 22
OR memeberid = 23
OR memeberid = 24
The catch is, I need to either ignore when one of the memberid's doesnt have data and keep the query going (or catch the id, so if one is found I can add the row for it in another query after the fact but still keep the query going).
Right now my dummy data is 3 out of the 4 memberid's have data and one doesn't if I do AND in the query, the query stops and yields no results. Where as if I do the OR i seem to only be returning one of there sets of data.
What I want to do is after the query build an array to pass around that would look like
array(
[0] array("memberid"=>21, "fb_wall"=>0, "fb_checkin"=>1, "phone"=>0),
[1] array("memberid"=>22, "fb_wall"=>1, "fb_checkin"=>0, "phone"=>1),
[2] array("memberid"=>24, "fb_wall"=>1, "fb_checkin"=>1, "phone"=>1)
)
just seem to be having a little issue forming the initial query, and like I said if I could in this case pass 23 else where so I could run an insert command on that id for the same table that would be awesome but not needed for the over all need here.

How about:
//parameter data
$members = array(
22 => null,
23 => null,
24 => null,
25 => null
);
//make a comma separated list of ids
$ids = implode(',', array_keys($members));
//generate query text
$sql = '
select memberid, fb_wall, fb_checkin, phone
from member_prefs
where memberid in ('.$ids.')
';
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
$members[$row[0]] = $row;
}

Start with an array with the relevant keys, and replace the elements as you read the rows.
$ares = array(21 => null, 22 => null, 23 => null, 24 => null);

Related

Insert 60000 rows Mysql from PHP

I have a MySQL database with a backend: PHP.
In one table I have to insert 60,000 rows.
We made a query into my PHP that returns 1,000 rows. For each rows we have to insert 60 rows. We thought make a loop but we don't know if is the best practices that way.
The part of the code that insert the data is:
$turnos = $db->query("SELECT * FROM turno t
WHERE t.canchaId = :cancha
AND t.fecha BETWEEN :fechaInicio AND :fechaFin
AND t.nombre LIKE :cadena
ORDER BY t.fecha,t.hora ASC",
array("cancha" => $cancha["idCancha"], "fechaInicio" => $fechaInicio, "fechaFin" => $fechaFin, "cadena" => "%turno fijo%"));
foreach($turnos as $turno) {
//turnos have 1000 rows
$fecha = date_create($turno["fecha"]);
date_add($fecha, date_interval_create_from_date_string('7 days'));
$anioAuxiliar = 2017;
while(2017 == $anioAuxiliar){
//60 times
$data1 = turno[data1];
$data2 = turno[data2];
...
$fechaAGuardar = (String) $fecha->format('Y-m-d');
$result = $db->query("INSERT INTO turno(fechaAGuardar, data2, data3, data4, data5, data6, data7, data8) VALUES(:fechaAGuardar, :data2, :data3, :data4, :data5, :data6, :data7, :data8)",
array("fechaAGuardar" => $fechaAGuardar, "data2" => $data2, "data3" => $data3, "data4" => $data4, "data5" => $data5, "data6" => $data6, "data7" => $data7, "data8" => $data8));
date_add($fecha, date_interval_create_from_date_string('7 days'));
$anioAuxiliar = (int) $fecha->format("Y");
}
$cantidad_turnos = $cantidad_turnos + 1;
}
This php is into a hosting with phpmyadmin.
So my questions are:
This is the best way to insert 60,000 rows?
Shall we considerer take into account another constraint? (eg: phpmyadmin don't allow you insert that amount of rows)
Thanks for helping me, Any suggestions are welcome
//EDIT//
The inserts data change, we have to insert datetime, and for each loop we have to add 7 day the last date inserted. So we can't use insert with select
As a bunch of fellows described in the comments, INSERT/SELECT is the way to go if this data is in the same server/database. There's no need to use PHP at all. Your year comment can be handled with DATE_ADD.
Anyway, if there is any other requirement and you can't use PHP, consider using Bulk Data Loading.
Analysing your code, the MOST IMPORTANT TIP would be: don't use multiple INSERT INTO TABLE expressions. Each INSERT INTO will cause a round trip do the database and things will get really slow. Instead of it, concat multiple values with one INSERT INTO (example from the link):
INSERT INTO yourtable VALUES (1,2), (5,5), ...;
Good luck!

How do I select specific value using Php and preg_match using comma delimited?

I am trying to select a certain numerical value that is separated by comma. The values are from a mysql db. I try to use explode the column but am not sure how to catch a certain value.
Any help would be appreciated.
Code
$query = mysql_query("SELECT id_array FROM values WHERE id='$id'");
while($result = mysql_fetch_assoc($query))
{
$get_id = $result['id_array'];
}
$exact = explode(",",$get_id);
Assuming you're storing a comma-separated list of values in column id_array, i.e.
12,17,44,13
After you've exploded the result you've got an array of the form
$exact is an array:
(
[0] => '12'
[1] => '17'
[2] => '44'
[3] => '13'
)
Now you want to know if 17 is an element of this array. Right? You can do it with in_array()
$check = in_array(17, $exact); // true, if found as in my example.
// Please note, that it's important not to search in strict mode.
// Test with 100, not in list
$check = in_array(100, $exact) // returns false
Maybe I misunderstood completely your problem. In this case please state with example data what your problem really is. What you've tried and where you got stuck.
PS: I wouldn't recommend storing comma separated lists in MySQL and it would be a great idea to drop the use of the mysql_* functions because they're deprecated. Use mysqli or PDO instead.

writing a second query based on results of the first - Not working

*MySQL will be upgraded later.
Preface: Authors can register in two languages and, for various additional reasons, that meant 2 databases. We realize that the setup appears odd in the use of multiple databases but it is more this abbreviated explanation that makes it seem so. So please ignore that oddity.
Situation:
My first query produces a recordset of authors who have cancelled their subscription. It finds them in the first database.
require_once('ConnString/FirstAuth.php');
mysql_select_db($xxxxx, $xxxxxx);
$query_Recordset1 = "SELECT auth_email FROM Authors WHERE Cancel = 'Cancel'";
$Recordset1 = mysql_query($query_Recordset1, $xxxxxx) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
In the second db where they are also listed, (table and column names are identical) I want to update them because they cancelled. To select their records for updating, I want to take the first recordset, put it into an array, swap out the connStrings, then search using that array.
These also work.
$results = array();
do {
results[] = $row_Recordset1;
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
print_r($results);
gives me an array. Array ( [0] => Array ( [auth_email] => renault#autxxx.com ) [1] => Array ( [auth_email] => rinaldi#autxxx.com ) [2] => Array ( [auth_email] => hemingway#autxxx.com )) ...so I know it is finding the first set of data.
Here's the problem: The query of the second database looks for the author by auth_email if it is 'IN' the $results array, but it is not finding the authors in the 2nd database as I expected. Please note the different connString
require_once('ConnString/SecondAuth.php');
mysql_select_db($xxxxx, $xxxxxx);
$query_Recordset2 = "SELECT auth_email FROM Authors WHERE auth_email IN('$results')";
$Recordset2 = mysql_query($query_Recordset2, $xxxxxx) or die(mysql_error());
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
The var_dump is 0 but I know that there are two records in there that should be found.
I've tried various combinations of IN like {$results}, but when I got to "'$results'", it was time to ask for help. I've checked all the available posts and none resolve my problem though I am now more familiar with the wild goose population.
I thought that since I swapped out the connection string, maybe $result was made null so I re-set it to the original connString and it still didn't find auth_email in $results in the same database where it certainly should have done.
Further, I've swapped out connStrings before with positive results, so... hmmm...
My goal, when working, is to echo the Recordset2 into a form with a do/while loop that will permit me to update their record in the 2nd db. Since the var_dump is 0, obviously this below isn't giving me a list of authors in the second table whose email addresses appear in the $results array, but I include it as example of what I want use to start the form in the page.
do {
$row_Recordset2['auth_email_addr '];
} while($row_Recordset2 = mysql_fetch_assoc($Recordset2));
As always, any pointer you can give are appreciated and correct answers are Accepted.
If you have a db user that has access to both databases and tables, just use a cross database query to do the update
UPDATE
mydb.Authors,
mydb2.Authors
SET
mydb.Authors.somefield = 'somevalue'
WHERE
mydb.Authors.auth_email = mydb2.Authors.auth_email AND
mydb2.Authors.Cancel= 'Cancel'
The IN clause excepts variables formated like this IN(var1,var2,var3)
You should use function to create a string, containing variables from this array.
//the simplest way to go
$string = '';
foreach($results as $r){
foreach($r as $r){
$string .= $r.",";
}
}
$string = substr($string,0,-1); //remove the ',' from the end of string
Its not tested, and obviously not the best way to go, but to show you the idea of your problem and how to handle it is this code quite relevant.
Now use $string instead of $results in query

having trouble updating value serialized array in MYSQL

Here what I does
- extract my serialize array from databse
- deserialize it
- change the value
- after changing I serialize it
- then write it back to MYSQL database table.
But Im having trouble writing it back to MYSQL database table
$myarray = Array
(
[dogname] => Array
(
[0] => white
[1] => zeon
[2] => imao
)
[visit] => Array
(
[0] => once
[1] => twice
[2] => twice
)
}
I save it database with this way into my table serialize($myarray)
now I extract it and unserialize
$unserializearray = unserialize($myserialarray);
then search for array value to change and back to table
$keys = array_keys($unserializearray['dogname'], 'imao', true);
foreach($keys as $key)
{
// find dogname imao and change its visit to once
$unserializearray['visit'][$key] = "once";
$update = serialize($unserializearray);
//save the update
mysql_query("UPDATE dogdetails SET checkup = '$update'
WHERE dogid = '1'");
}
but it dont save right into mysql do I miss something in code?
First of all this can't work, if something in your array has a single quote in it, so you need to do
$update=mysql_real_escap_string(serialize($unserializearray),$dbhandle);
or friends.
More importantly, your database design seem heavily flawed to me: As has been said many, many times here, you should not store more than one value in a field, if you want to access them seperately. In your case, you store three dogs with their vists, but you want to access them seperately - this is what your code does.
As Eugen said, there are many things wrong with your code.
Except all that, does this code works any better:
$unserializearray = unserialize($myserialarray);
then search for array value to change and back to table
$keys = array_keys($unserializearray['dogname'], 'imao', true);
foreach($keys as $key)
{
// find dogname imao and change its visit to once
$unserializearray['visit'][$key] = "once";
}
$update = mysql_real_escap_string(serialize($unserializearray));
//save the update
mysql_query("UPDATE dogdetails SET checkup = '$update' WHERE dogid = '1'");

return multiple arrays from a query

i have 2 tables
1st table called services has id_service, name, date. description
2nd table called services_images has id_img, img_name,id_service
Let's say now that I have to, with one query (if possible), return 2 arrays
1st array with fields from one specific id from table "services"
2nd array with fields from all the images related to the selected id in "services" from table "services_images"
or better yet, only one array with the same data as said in 1, with an array INSIDE called "images" that has all the images listed from the table "services_images"
I need this to process and show data in a html page and this is the only way.
If I cant do it in mysql how can I arrange this in PHP, the only thing I can think of is 2 queries
Plus I'm always trying to improve my skills since I used to make single queries for everything, are there cases where making 1 query it's just impossible?
Thanks!
EDIT: i see what you mean now - i mis interpreted the first time.
The only way to do this would be to do more than one query. You would have to do something like:
$sql = "SELECT * FROM services WHERE id_service=$id";
$result = mysql_query($sql);
$services = mysql_fetch_array($result);
$new_sql = "SELECT * FROM services_images WHERE id_service=$id";
$new_result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
$serivices_images[] = $row;
}
Acctally I change my mind again.. try this:
SELECT services.*,services_images.* FROM services, services_images WHERE services.id_service=services_images.id_service AND services.id_service=$id
now when you do while($row = mysql_fetch_array($sql_query_result)) you might return ALL the rows... but I dunno. Just a guess.
For eaxmple with PDO:
$db = new PDO($dsn, $user, $pass);
$sql = 'SELECT services.id_service, services.name, services.date, services.description, services_images.id_image, services_images.img_name
FROM services, services_images
WHERE services.id_service = services_images.id_service
ORDER BY services.id_service';
$services = array();
foreach($db->query($sql) as $row)
{
$serviceId = $row['id_service'];
if(!array_key_exists($serviceId, $services))
{
$services[$serviceId] = array(
'name' => $row['name'],
'date' => $row['date'],
'description' => $row['description'],
'services_images' => array()
);
}
$imgId = $row['id_img'];
$services[$serviceId]['services_images'][$imgId] => array(
'id_image' => $imgId,
'img_name' => $row['img_name']
);
}
print_r($services);
Beware though.. if the two tables youre joining (in this case services and services_images) have any columns with the same name you will only get the value for the last one retrieved in the row unless you alias them or exclude them form your select statement.
Additionally, if the size of your results is big you may have to use two queries similar to what Thomas has suggested because you may not have enough memory to hold the complete array structure.

Categories