I have a question about how I can save different value in order if I GET 1 row in php.
For example, if I have like:
*Feder|100|50|10|5|9|0|0|0|0|0|0 PHP LINE
I need to save this row in the table like:
----------------------------------------------
name | score | status | point | level | bla | bla | bla....
----------------------------------------------
Feder| 100 | 50 | 10 | 5 | 0 | 0......
-------------------------------------------------
Now, I use easy method to get something in the database like:
$sql="INSERT INTO user (name, score, status)
VALUES
('$name','$score','$status')";
mysqli_query($con,$sql);
With this, when I get the value, I use like:
save.php?name=feder&score=100&status=50
But if I have to insert 40 values, will this be very hard? I think is possible to make easy, but I don't have any idea how I can do that... Someone know the best method to do this?
If I can use like: save.php?userdata=(all row)* is better...
What you ask for is not recommended for security reasons. It's one of the biggest no-nos to trust GET contents and put it straight into an SQL query.
But.
Of course you can foreach the variable $_GET like this:
$x="";
foreach($_GET as $key=>$val) {
$x.=" $key = '$val', ";
}
$sql = "insert into myTable set $x";
This is just the principle of it. You should ALWAYS check for the field names and values to avoid injection attacks. So a better approach would be like:
$isValid = array("name"=>1,"score"=>1,"status"=>1);
$x="";
foreach($_GET as $key=>$val) {
if(!$isValid[$key]) continue; // skip unknown fields!
$val = stripslashes($val); // remove magic quote junk
$val = mysql_real_escape_string($val); // protect mysql from attacks
$x.=" $key = '$val', "; // build the query
}
$sql = "insert into myTable set $x";
UPDATE
If you get all the values in one string like "aaa|bbb|ccc", you can use explode() to parse them into one array. But then you rely on the order of fields which is not a good practice. I'd recommend to always prefer "field1=aaa&field2=bbb" style.
Hope this helps.
Think about the risks and find your own way.
You said 40 row. You have to remember that the limitation of length of an URL. So the suitable way is to use POST method through a HTML form. Taking care in multible fields naming by adding [] to the field name:
<form method="post" action="some.php">
<input type="text" name="name[]" />
<input type="text" name="score[]" />
...
</form>
and from your PHP
for ($i = 0; $i < count($_POST['name']); $i++){
$name = $_POST['name'][$i];
$score = $_POST['score'][$i];
$status = $_POST['status'][$i];
$sql="INSERT INTO user (name, score, status)
VALUES
('$name','$score','$status')";
mysqli_query($con,$sql);
}
Notice: This answer is about the concept of inserting multiple records. It does not meant by the security of receiving data.
Related
There's something weird going on.
I have I database which could look something like this:
table name: dm
|id|receiver|sender|msg |
|1 |John |Emma |Hey John! |
|2 |Emma |John |Hey! |
|3 |John |Emma |Whats up |
|4 |Emma |John |Not too much |
|5 |John |Keira |Have you got...|
I have an html page with a on it and for now what I want is for the messages that either
Emma sent to John => receiver = "John", sender = "Emma" or
John sent to Emma => receiver = "Emma", sender = "John"
to be displayed in the console.
I can do that with JQuery using the console.log() function.
My PHP looks like this:
$user1 = "John";
$user2 = "Emma";
$sql = "SELECT * FROM dm WHERE receiver = '$user1' AND sender = '$user2';SELECT * FROM dm WHERE receiver = '$user2' AND sender = '$user1'";
// Execute multi query
if (mysqli_multi_query($link,$sql))
{
do
{
$i = 0;
$msg = array();
if ($result=mysqli_store_result($link)) {
while ($row=mysqli_fetch_row($result))
{
printf("%s\n",$row[0]);
$msg[$i] = $row[0];
$i++;
}
mysqli_free_result($result);
}
}
while (mysqli_next_result($link));
}
echo json_encode($msg);
exit();
mysqli_close($link);
You will notice, that I have "printf" in there, because I wanted to see what the databse would give back to me. It correctly gave back the id's: 1,3,2,4.
However, I normally would like to do the request using JQuery ajax. I know how to do that also. Because of that I want to have an array which holds all the id's of the posts like this:
["1","2","3","4"]
Unfortunately the way I do it as written in the code what it returns to me is this:
["2","4"]
So what's going on is that he only puts what was in the first query into the array.
So what exactly is my question?
I want to fix the array to hold all the id's of the respective messages which would be 1,2,3,4. Preferably in this order as well and not like this 1,3,2,4.
I hope I made the problem clear and thank you for any advice!
You reset $i and $msg inside the outer loop. That means you will only see results from the second query in your array. Move the $i = 0; and $msg = array(); lines outside that loop.
That said, there’s no reason to do 2 queries here. Just use an OR in your WHERE clause to get both results at once. This will be faster and easier.
Also, this is very important: you are wide open to SQL injection. You need to use prepared statements, rather than concatenating variables into your query. See How can I prevent SQL injection in PHP?.
I am struggling a little bit with a tricky PHP array. I am trying to retrieve data from a database (a single row) and I want to plug this data in a bunch of dynamically generated fields on the page (PHP).
My DB is organised as follows
____________________________
| cats | dogs | birds | cows |
_____________________________
| 30 | 40 | 22 | 34 |
______________________________
I would like to build an array like this:
array(
$cats => $cats_value
$dogs => $dogs_value
etc...
)
Importantly: I want the array to ouput variables, where in the above example $cats outputs "cats" and $cats_value outputs "30". I am guessing once this is done that I can use the variable names directly, so I won't have to go nuts trying to pull them out of the array...
I have tried to put various bits of code but have failed miserably (i.e. nothing to show/embarrass myself with on here.)
Any help would be much appreciated.
OK, the code that provides the answer is as follows:
$query = "SELECT * FROM animals";
$result = mysqli_query($dbc, $query);
$data_array = array();
$row = mysqli_fetch_assoc($result);
print_r($row);
foreach($row as $key=>$value){ echo $key; echo $value;
${$key}=$key;
${$key."_value"}=$value;
}
echo "<br><br><br>";
echo $Cats." = ".$Cats_value."<br>";
echo $Dogs." = ".$Dogs_value."<br>";
echo ${"Cows"}." = ".$Cows_value."<br>";
echo ${"Birds"}." = ".$Birds_value."<br>";
I appreciate all the answers that helped me find the answer to this. As an aside, the whole reason I am doing this is because I need to populate a dynamically generated PHP page with a bunch of variables, and that I will likely need to populate these variables dynamically as well.
If you think I am approaching this problem the wrong way, then please let me know (i.e. is it dumb to convert an associative array into a bunch of $variables? Does that make sense, and/or could it really slow down my page?)
I have multiple fields with names that look like name_$i and I am trying to figure out a way to "on submit", send them all to the database. The thing is that the form is looped and the insert has to be able to adapt to the number of fields in the form. Is there a way to do this???
<?php
$fldcnt = $_POST['fldcnt'];
$i = $_POST['i'];
for ($i = 0; $i < $fldcnt; $i++){
$NAME = $_POST['name_$i'];
$AGE = $_POST['age_$i'];
$ADDRESS = $_POST['address_$i'];
$TELEPHONE = $_POST['telephone_$i'];
$EMAIL = $_POST['email_$i'];
$q_register_new_users = "insert into registration set
NAME = '$NAME',
AGE = '$AGE',
ADDRESS = '$ADDRESS',
TELEPHONE = '$TELEPHONE',
EMAIL = '$EMAIL'";
mysql_query($q_new_products,$connection) or die(mysql_error());
};
?>"
HTML and PHP
You can enter input fields into an array by simply calling the field name[]. Like so:
<input name="name[]" />
You can then use PHP to loop through the fields like so:
foreach($_POST['name'] as $key=>$value){
// Insert the value of the form field into a string or query
// i.e. build the query
$query .= $value;
}
// Then execute the query for each set of fields
The logic above is actually incorrect, but it should give you an idea of what I mean.
MySQL
Your SQL syntax is incorrect, the correct syntax for inserting into a MySQL database is:
INSERT INTO `table` (`field_1`, `field_2`)
VALUES ('value_1', 'value_2')
PLEASE NOTE
The use of the mysql_ functions is hugely discouraged due to there impending deprecation. Instead, most PHP programmers are now using the PDO / SQLite Classes. Whilst these might seem complex, they are actually pretty simple and offer a much more secure way of executing SQL statements.
PDO
SQLite
The syntax for INSERT statement should be like this,
INSERT INTO registration (NAME , AGE , ADDRESS, TELEPHONE, EMAIL)
VALUES ('$NAME', '$AGE', '$ADDRESS','$TELEPHONE', '$EMAIL')
but hte query above is vulnerable with SQL INJECTION, please read the article below to learn how to protect from it,
How can I prevent SQL injection in PHP?
If you are going to keep structure of your code, you need to use double quotes instead of apostrophes
$NAME = $_POST["name_$i"];
or put the variable out
$NAME = $_POST['name_'.$i];
Using array is best way to do this. But if you still want to go head with a counter then you could use
for($i = 0;isset($_POST["name_{$i}"]);$i++)
{
// name found
}
Please note that this code may not be optimal if the name_xx fields are coming from checkboxes, where a user selected items and skipped some in between.
PS. I posted this a comment but it is more suitable as an answer.
I have a form with an input box where the user can specify their names, the names may be two or more words, eg John Smith or John Michael Smith.
I have to write a query that returns records containing all words in the name presented. So query will return records that has the name of all those words, but may have different order.
For example, if the search string is John Michael Smith, the query should be able to return records with names like Michael John Smith, Michael Smith John, John Smith Michael or some combination of all these words there. As can be seen only return records that still has all the words in the name field, but may have different order. However, it should return results that do not contain part of the name, for example, John Michael should not be returned because it does not have Smith in there.
I tried query like this:
SELECT id, name FROM users WHERE
name LIKE '%Michael%' &&
name LIKE '%Smith%' &&
name LIKE '%John%'
The same problem happens with:
SELECT * FROM users WHERE MATCH (name)
AGAINST ('+Michael +Smith +John' IN BOOLEAN MODE);
Both queries also returns John Michael instead of records that contain all three words :(
I can not figure out how to write a query to the requirement so that I have. Please help.
Use a fulltext index. That's the easiest/quickest method. Otherwise you're stuck parseing your search string, converting
John Michael Smith
into
SELECT ... WHERE (name LIKE '%John%') OR (name LIKE '%Michael%') OR (name LIKE '%Smith%')
which very quickly gets painful to do, and VERY slow to perform, as LIKE %..% searches cannot use indexes.
Note that Fulltext indexes are currently restricted to MyISAM tables, so if you're on InnoDB, you'll have to use workarounds (parallel tables in MyISAM format to hold the searchable data with triggers to keep the two copies synchronized). Apparently Fulltext for InnoDB is FINALLY in the development pipeline, but it's not here yet.
If you save the name in the field 'name' your sql query should be like this
first explode the string by space
$params = explode(' ', $input_name);
then append this on your query:
$i = 0;
$q= '';
foreach($params as $p){
$p = strtolower($p);
if($i > 0) $q.= " and ";
$q.= "LOWER(name) like '%$p%'";
$i++;
}
$query="select .... where ".$q;
the lower things are needed to make it case insensitive.
Whatever variable you are setting up as the value of this input, you want to use explode on:
http://php.net/manual/en/function.explode.php
$names = explode(' ', $userinput);
with a space as your delimiter. This will give you an array with the 3 different elements (or however many there are).
$names[0] = "John";
$names[1] = "Michael"
$names[2] = "Smith";
Now you need to run them through strtolower so that case is not an issue.
http://us3.php.net/manual/en/function.strtolower.php
foreach ($names as $name)
{
$name = strtolower($name);
}
Now we have
$names[0] = "john";
$names[1] = "michael"
$names[2] = "smith";
Next you need to build a function that reassembles these variables in all possible orders. But because you might have 1,2,3, or 4 elements in your array, you don't know how many queries you will need. So you check:
$numberofnames = count($names);
Then create a function to build your different name combinations:
$namecombo = "";
function createNames($numberofnames)
{
for($i=0; $i <= $Numberofnames; $i++)
{
$namecombos[i] .= $names[i];
}
So. This is an incomplete answer because here we run into a problem. You need a for loop to generate the name combos, but you also need a for loop generating how many for loops you need. Not something I can think of a way to code. But... Hope this gets you closer to an answer.
for($i=0; $i <= $Numberofnames; $i++)
{
$secondnamecombo[i] = $names[$i - 1]
etc...
}
}
What is the best way to get the all values of one multiple select box, and then i want to save those values in one row in the database, then from that row i want to get each value separate. What is the best way to do such a thing ? My goal is to save the values and then get each separate.
You could do it this way
<select name="foo[]" multiple="multiple">
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="fish">Fish</option>
</select>
<?php
$pets = $_POST['foo'];
//sanitize and verify the input here. Escape properly and what not
$query = mysql_query("INSERT INTO `pets` (`pet1`, `pet2`, `pet3`) VALUES ('".$pets[0]."', '".$pets[1]."', '".$pets[2]."')");
?>
But to be honest it's an awful way to go about building a database. It'll be very annoying or difficult to do anything meaningful with.
Why not have the following database setup:
users:
id | name
----------
1 | Tim
pets:
id | user_id | type
-------------------
1 | 1 | Fish
2 | 1 | Cat
3 | 4 | Kakapo
And then you would have a much more easily searchable and manipulatable database that's consistent.
I believe you should receive the value selected as an array in the $_POST variable so say your select has a name="products"
The values selected will be in $_POST["products"] assuming you are submitting the form via POST.
Then you can use the implode function to generate a string. For example:
$myProducts = implode("|", $_POST["products"]); //This will give you a pipeline delimeted string like : computer|laptop|monitor
$myProducts = mysql_real_escape_string($myProducts); //Just to santize before inserting in DB
Then just insert that string into the DB.
When retrieving the data you can reverse the process by using the explode function:
$myProducts = explode("|" , [The value retrieved from the database]); //This will give you an array which you can iterate and thus accessing the values individually.
Hope this helps :)
if i understand your question well...
$dataFromMultipleBox = array('data1', 'data2', 'data3');
$data = implode("||", $dataFromMultipleBox);
/*
After that,
write $data into database
fetch from the database again
*/
$pieces = explode("||", $rowFromDatabase);
foreach($pieces as $value) {
echo $value;
echo '<br>';
}
What is the best way to get the all values of one multiple select box,
Since it is PHP. Give the select element a name ending in [], then you can access them as $_POST['foo'][]
and then i want to save those values in one row in the database, then from that row i want to get each value separate.
Don't do that. Have a second table with two columns. The id (as a foreign key) of the row in the other table (where you were planning to store the data) and the value itself.