I have a script that inserts a company id, user id and a datetime of the transaction when someone enters their email. Now I have to add a dropdown select box that allows for the user to select the number of donations they want to make so the only have to enter their email address once. What is the best way to go about this? I was thinking something like this:
$coid = $row['companyid'];
$userid = $_SESSION['userid'];
$selectbox = $_POST['select']; // number value 1-10
// old query
mysql_query = ("INSERT INTO donations(company, user)");
// new query
$i=1
while($i<=$selectbox) {
mysql_query = ("INSERT INTO donations(company, user)");
$i++
}
or something along those lines. Is that the best way to go about it? Better ways?
First, stop using mysql_ functions as they are being deprecated. Use mysqli_ or PDO functions instead.
You should use prepared statements or sanitize your variables to prevent against SQL injection.
Regarding a better approach, you can put them into an array then implode when executing. This is a good starting point. It uses PDO to insert an array.
With your current code, I'm not clear how you're tracking the number of users wishing to do donations, but you can do something like:
$i = 1;
while($i <= $selectbox) {
$insertArray[] = "$coid, $userid";
$i++;
}
mysql_query("INSERT INTO donations (company, user) VALUES (" . implode('), (', $insertArray) . ")");
You should make a database table with 3 columns (for this question).
I will give you the code to make the required table, just copy and paste this into PHPmyAdmin:
Create Table donations(
company_id int,
user_id int,
donate_num int,
datetime DATETIME
)
Then use the INSERT INTO function to update the database using the new mysqli functions (Replace the server/username etc with your database details):
$mysqli= new mysqli('SERVER','USERNAME','PASSWORD','DATABASE NAME')
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
function escapeStringSlash($value) {
global $mysqli;
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = $mysqli->real_escape_string($value);
}
return $value;
}
$coid=escapeStringSlash($row['companyid']);
$userid = escapeStringSlash($_SESSION['userid']);
$selectbox = escapeStringSlash($_POST['select']);
$date = new DateTime();
$currentTime = $date->format("Y-m-d H:i:s");
if($insertDonations=$mysqli->query("INSERT INTO donations(company_id,user_id,donate_num,datetime) VALUES(".$coid.",".$userid.",".$selectbox.",'".$currentTime."')"){
echo "Number of donations received";
}else{
echo "There was a problem inserting this.";
}
$mysqli->close();
Related
Im working with sql database (phpMyadmin) and with programming language PHP.
I've got a table with data e.g:
T1:
145
138.8
110.6
1759.4
1400.9
1891.4
1755.4
1760.4
T2:
141.9
110.6
1400.9
1891.4
1758.4
My question >
Is there existing sql syntax, that is able to average values which are lying in ONE THRESHOLD (like > 1755.4,1760.4,1759.4 OR 145,138.8) and INSERT THEM AS UNIQUE VALUES to another table ?
What I need is create T2(contain UNIQUE values) from T1, and INSERTING them only if they didn't exist in T2.
I was trying, to looping throw 2 arrays (1starray = T1 and 2ndarray = T2 ) too. And compare data in array1 and array2, and trying to insert values which can be unique.
for($z = 0; $z<$numberApp; $z++) {
while($j<$numberAbs-1){
$Abs=$arrayabs[$j];
$state_change = (abs($Abs - abs($previous_Abs)));
if ($state_change>100){
$instantChange = True;
echo "<br>"." better than tolerance: " . $instantChange;
}
else {
$instantChange = False;
echo "<br>"." lower than tolerance" . $instantChange;
}
//if($state_change = (abs($some_item - $previous_item)<= $tolerance)){
if($Abs != $previous_Abs){
echo "<br>" ." some_item : " .$Abs." previous_item : " .$previous_Abs;
}
//$lastAbs=$arrayabs[$j];
//echo " next_item : " .$lastAbs;
if ($instantChange == True and $onChange == False){
$Abs2 [] = $podiel;
$finalPower = $podiel;
}
if ($instantChange){
$D=0;
echo "ABSOLUT >>> " .$lastAbs;
$percentual1 = ($power_app[$z] * 0.9);
$percentual2 = ($power_app[$z] * 1.1);
if(($lastAbs<$percentual1 || $lastAbs>$percentual2)){
$user = 'root';
$pass = 'password';
$db = 'vypis';
//if($N>0){
$db = new mysqli('localhost', $user, $pass, $db) or die();
$sql = "INSERT INTO vypis.nilm_app2(power) VALUES ('$lastAbs')";
if(mysqli_query($db, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
}
//$power_app[$z++];
}
Thank you for everyone, who going to help, and sorry for my bad english.
The math here sounds complex enough that you're probably better off doing the complex stuff (averaging the values and determining whether a value is unique) in PHP, then finishing off with a couple simple MySQL statements.
This can probably be done in pure MySQL with a bit of trickery, but frequently it isn't worth the time and complexity it creates. (Imagine you'll have to debug that monster SQL query six months from now!)
By contrast, it's trivial to take a handful of values in PHP and average them; it's also trivial to run a quick MySQL query to determine whether a value is unique. So if you're unsure how to mash these together into one big SQL statement, start out by just handling them in the PHP code as separate steps! Then later on, if performance issues come up, you can think about how to combine them (but at least by that point you already have something that works).
So I am trying to echo out how many rows there are in a table with a COUNT command, but I purposely have no rows in the table right now to test the if statement, and it is not working, but worst, it makes the rest of the site not work(the page pops up but no text or numbers show up on it), when I added a row to the table, it worked fine, no rows = no work. Here is the piece of the code that doesn't work. Any and all help is highly appreciated.
$query1 = mysql_query("
SELECT *, COUNT(1) AS `numberofrows` FROM
`table1` WHERE `user`='$username' GROUP BY `firstname`,`lastname`
");
$numberofrowsbase = 0;
while($row = mysql_fetch_assoc($query1))
{
if(isset($row['numberofrows']))
{
$enteries1 = $enteries1;
}else{
$enteries1 = $numberofrowsbase;
}
echo enteries1;
}
Seems you have over complicated everything. Some good advise from worldofjr you should take onboard but simplest way to get total rows from a table is:
SELECT COUNT(*) as numberofrows FROM table1;
There are several other unnecessary lines here and the logic is all bonkers. There is really no need to do
$enteries1 = $enteries1;
This achieved nothing.
Do this instead:
while($row = mysql_fetch_assoc($query1))
{
if(isset($row['numberofrows']))
{
echo $row['numberofrows'];
}
}
Maybe against my better judgement, I'm going to try and give you an answer. There's so many problems with this code ...
Do Not Use mysql_
The mysql_ extension is depreciated. You should use either mysqli_ or PDO instead. I'm going to use mysqli_ here.
SQL Injection
Your code is wide open to SQL injection where others can really mess up your database. Read How can I prevent SQL injection in PHP? for more information.
The Code
You don't need to count the rows with a SQL function, especially if you want to do something else with the data you're getting with the query (which I assume you are since you're getting a count on top of all the columns.
In PHP, you can get how many rows are in a result set using a built in function.
So all those things together. You should use something like this;
// Connect to the database
$mysqli = new mysqli($host,$user,$pass,$database); // fill in your connection details
if ($mysqli->connect_errno) echo "Error - Failed to connect to database: " . $mysqli->connect_error;
if($query = $mysqli->prepare("SELECT * FROM `table1` WHERE `user`=?")) {
$query->bind_param('s',$username);
$query->execute();
$result = $query->get_result();
echo $result->num_rows;
}
else {
echo "Could not prepare query: ". $mysqli->error;
}
The number of rows in the result is now saved to the variable $result->num_rows, so you can use just echo this if you want, like I have in the code above. You can then go onto using any rows you got from the database. For example;
while($row = $result->fetch_assoc()) {
$firstname = $row['firstname'];
$lastname = $row['lastname'];
echo "$firstname $lastname";
}
Hope this helps.
I am really trying to wrap my head around this and failing miserably. What I want to do it build a MySQL query based on the URL parameters passed by the URL. I am trying to create a re usable dynamic script that can do what it needs to do based on the URL parameter.
This is what I have come up with, and it appears that it does what it is supposed to do (no errors or anything) but nothing actually gets inserted in the database. I know somewhere I have made a dumb mistake (or thought something out wrong) so hopefully one of you guys can point me in the right direction.
Thanks!
//List all possible variables you can expect the script to receive.
$expectedVars = array('name', 'email', 'score', 'age', 'date');
// This is used for the second part of the query (WHERE, VALUES, ETC)
$fields = array('uName','uEmail','uScore','uAge','uDate');
// Make sure some fields are actually populated....
foreach ($expectedVars as $Var)
{
if (!empty($_GET[$Var]))
{
$fields[] = sprintf("'%s' = '%s'", $Var, mysql_real_escape_string($_GET[$Var]));
}
}
if (count($fields) > 0)
{
// Construct the WHERE Clause
$whereClause = "VALUES " . implode(",",$fields);
//Create the SQL query itself
$sql = ("INSERT INTO $mysql_table ($fields) . $whereClause ");
echo "1"; //It worked
mysql_close($con);
}
else
{
// Return 0 if query failed.
echo "0";
}
?>
You missed mysql_query($sql):
if(!mysql_query($sql)){
//die(mysql_error());
}
Please consider to use PDO or My SQLi using parametrize query because mysl_* function depreciated.
Your SQL is all wrong. You're using the field = value syntax for an INSERT, then you're concatenating an array as if it were a string ($fields), and you're missing a couple of parentheses around the values.
a couple of things: i've found for php <-> mysql its important to see what's going into mysql and experiement directly with those queries in phpmyadmin when i get stuck.
1 - in my code I output mysql_error() when the query fails or when a debug flag is set. this usually explains the sql issue in a way that can point me to a misspelled field name etc...
2 - this way i can feed that mysql query directly into phpmyadmin and tweak it until it gives me the results i want. (while i'm there i can also use explain to see if i need to optimize the table)
specifics in your code. unlike C languages sprintf is implied. here's how i'd write your code:
// List all possible variables you can expect the script to receive.
$expectedvars = array('name', 'email', 'score', 'age', 'date');
// This is used for the second part of the query (WHERE, VALUES, ETC)
// $fields = array('uName','uEmail','uScore','uAge','uDate');
$fields = array();
// Set only the variables that were populated ...
foreach ($expectedvars as $var) {
if (!empty($_GET[$var])) {
$name = "u" + ucwords($var); // convert var into mysql field names
$fields[] = "{$name} = " . mysql_real_escape_string($_GET[$var]);
}
}
// only set those fields which are passed in, let the rest use the mysql default
if (count($fields) > 0) {
// Create the SQL query itself
$sql = "INSERT INTO {$mysql_table} SET " . implode("," , $fields);
$ret = mysql_query($sql);
if (!$ret) {
var_dump('query_failed: ', $sql, $ret);
echo "0"; // Query failed
} else {
echo "1"; // It worked
}
} else {
// Return 0 if nothing to do
echo "0";
}
mysql_close($con);
I did make a post previously but was not able to properly explain my issue nor was I able to get it resolved. This is what I have.
$shoutlines = file($shout_file);
$aTemp = array();
foreach($matches['user'] as $user) {
$aTemp[] = "'" . $user . "'";
}
$user = implode(",", $aTemp);
$rara = "SELECT * FROM accounts WHERE username IN ( $user )"; // Tried this statment both as a query and prepared statement
$getlevel = $db->query("SELECT * FROM accounts WHERE username IN '( ".$user." )'"); // Tried this both as a query and prepared statement
//$getlevel->bind_param('s', $user);
//$getlevel->execute();
//$level = $getlevel->get_result();
//$getlevel->store_result();
while($getdb = $getlevel->fetch_assoc()){
//output the html
for($i = 0; $i < (1000); $i++)
{
if(isset($shoutlines[$i]))
{
$shoutline = preg_replace('/<\/div>\n/', ' ', $shoutlines[$i], 1);
echo showSmileys($shoutline) . "<div class='delete'><a href='javascript: delete_shoutline({$i});' title='Delele'>delete</a></div></div>";
}
}
}
I have a for loop within the while loop that will not run within it, if I move the for loop outside of the while it works fine, but I need it in the while loop to make checks of the users for post titles, abilities etc., that are saved in my database. I have shown what I have tried so far when to comes to identifying the problem, I have tried dieing out errors if the query, binds, or executes weren't showing true, but got now hits. The code for this is pulled out so there isn't too much clutter for your reading abilities, any help with this would be greatly appreciated.
When "exploding" the username, you need ot wrap each username in quotes, not the whole thing. Also make the names safe for data entry.
$aTemp = array();
foreach($matches['user'] as $user) {
$aTemp[] = '"' . mysql_real_escape_string($user) . '"';
}
$user = implode(",", $aTemp);
Then use the first query:
"SELECT * FROM accounts WHERE username IN ( $user )";
Edit: adding error checking:
$getlevel = $db->query("SELECT * FROM accounts WHERE username IN ( $user )");
if ($getlevel == false) {
// Normally you'll build into a function or class, but this is the simple example
// Never output SQL errors on a live site, but log to file or (if you can do it safely) the database.
echo 'Whoopsie<br />';
var_dump($db->errorInfo());
exit();
}
Using data binding with IN clauses is not that nice, so if you really need IN and don't care about using the old, deprecated mysql_* function, try this:
$user="'".implode("','",array_map(function($s){
return mysql_real_escape_string($s);
},$matches["user"])."'";
$rara="SELECT * FROM accounts WHERE username IN ($user)";
I have entered the following query in MySQL:
insert into hospital (name,age) values ('william', 'select * from department where age = $agegrp');
Now I have fetched this value (the sql), and trying to execute it. How can i do this?
I have fetched the select statement into a variable called $var.
$agegrp = "10";
$value = mysql_query ($var) or die ('error');
I only get error so something is wrong with my query that I inserted. How can I solve this?
first question for me: why do you store sql code in your hospital table?
it would make more sense if all your sql code would be embedded in your php program code.
if you later change your table design, you won't have to change the content of the database table.
but to answer your question, the content of your $var is a simple string. what you want is to evaluate it or to replace the string '$agegrp' with the actual value of the variable $agegrp.
so you could do:
$agegrp = "10";
$var = str_replace('$agegrp',$agegrp,$var;
$value = mysql_query ($var) or die ('error');
this would be a simple solution.
age is a property that will probably be an integer. You can't insert a query into that field. What you need to do is execute query;
"SELECT * FROM Department WHERE age = {$agegrp}"
Then, get the result of that and then execute your insert. Also, look at bind parameters for your queries early on. You don't want to allow sql injection.
Try this one.
<?php
$con = mysqli_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
$var= mysqli_select_db("my_db", $con);
$var="select * from department where age = $agegrp");
$result=mysqli_query($var);
while($row = mysqli_fetch_array($result))
{
echo $row['age'] ;
echo "<br />";
}
mysqli_close($con);
?>