$ResultLine = $db->query("SELECT customerid FROM mydb WHERE surname= Holmes ORDER BY customerid DESC LIMIT 10")->fetchArray();
$res = $ResultLine[0];
echo json_encode($res);
Let's say there are 3 customers with the same surname in the database and different customerid. How can I structure the code above to return all the pairs customerid/surname as an array to my html page? The code above obviously only returns one customerid.
The call to fetchArray() returns one row at a time. So this snippet gets the first row and sends the first element ([0]) to json_encode. Remove ->fetchArray() from the set statement, then iterate over $ResultLine, something like:
while ($row = $ResultLine->fetchArray()) {
//do something with $row values
}
Doc found here
Related
I'm inserting some values to a table using a sql statement. All the values get inserted, except the 'qty' column. When I do an echo for sql statement, it shows the value has been assigned to the sql statement. Table column data type is INT. Can anyone help me to spot the problem?
$it_code = $_POST['id'];
//Prompt user to enter required qty
echo '<script>';
echo 'var qty = prompt("Enter Qty", "");';
echo '</script>';
//Get the item details from item table
$sqlString = "Select * from items where it_code='".$it_code."'";
$objItem = new Allfunctions;
$result = $objItem->retriveData($sqlString);
//Get the selected qty from java script to php variable
$qty = "<script>document.writeln(qty);</script>";
$user_id =$_SESSION['user_id'];
//Insert to orders table
$sqlStringInsert = "INSERT INTO orders(user_id,it_code,qty,status,tr_timestamp) VALUES ('$user_id','$it_code','$qty','PENDING',CURRENT_TIMESTAMP())";
echo $sqlStringInsert;
$objItem->addToTable($sqlStringInsert,'Succsessfully added.','Error adding'); // This is a custom built method to insert data in to a table by taking the sql statement as the parameter
Following is the sql statement generated,
Following is the table data. Qty is always 0 eventhood the sql statement had a value at qty column.
Obligatory warning
The code as you have shown it should not be used in production as it is vulnerable to SQL-injection attacks. Preventing this is well covered on this site in other answers.
Answer
The issue is that the value of $qty you are injecting into your SQL is the string "<script>document.writeln(qty);</script>". You just can't see it because you are likely echoing it out to the browser to test it.
Wrap your echoing of the SQL statement in a call to htmlentities() (docs) to see what's actually happening.
Depending on the version and settings, MySQL is very forgiving of bad data being injected to a column. In this case, it sees a string of text being inserted to a numeric column, and just truncates it to 0. See this in action here:
CREATE TABLE Foo (
Id INT,
Qty INT
);
INSERT INTO Foo(Id, Qty) VALUES (1, 'a string of text');
SELECT * FROM Foo; -- returns a row (1, 0)
https://www.db-fiddle.com/f/dEoaYGEyXEjs6ocVBwyyyr/1
This is my category table. Basically there's a category and subcategory. The ParentCategoryId is the subcategory under the category. For example I have three of ParentCategoryID 1 which means it's a subcategory under category_id 1 therefore the isSubCategory is set to 1 that is saying yes it's a subcategory and 0 means it's a category that's why the parentCateogryID is null for the first four data since they are categories
I already have an Add Category functioning and now I want to have an Add Subcategory function but very confused on how I will do my usual php query.
<form method="POST">
<?php
if(isset($_POST['submit'])){
include 'testdb.php';
$addcategory = $_POST['categoryname'];
$parentcategory = $_POST['parentcategoryID'];
$query = mysqli_query($con, "SELECT categoryname FROM category WHERE categoryname = '.$addcategory.'");
$insert = mysqli_query($con, "INSERT INTO category (`categoryname`,`ParentCategoryID`,`isSubCategory`) VALUES ('$addcategory','$parentcategory','1')");
if(!$insert){
echo mysqli_error($con);
}
else{
echo 'Category successfully added!';
}
}
?>
structure
whenever im trying to add.
needs to have the same id as(look pic below)
this needs to be the same so the inserted sub category shows in Foods category table
Foreign keys aren't self-referential within the same table. If your subcategories were in a different table (which I'd recommend - the above solution is really messy), then a foreign key would make it much easier for your insert functions.
Anyway, if you just wanted to add a new subcategory;
$addcategory = $_POST['categoryname'];
$parentcategory = $_POST['parentcategory'];
$insert = mysqli_query($con,
"INSERT INTO category
(`categoryname`,
`ParentCategoryID`,
`isSubCategory`)
VALUES
('$addcategory',
'$parentcategory'
'1')");
Also, consider using prepared statements.. or at least run mysqli_escape_string over the POST params you're taking in.. leaving them as they are would allow me to insert a category like '; DROP TABLE users;.
I'm having trouble creating php code that would insert values into MySQL database but only if they don't already exist.
I send array from javascript to PHP file using $.ajax type POST.
Do I need additional 'SELECT' query to check if values already exist?
PHP File(Works, inserts values):
<?php
SESSION_START();
include('config.php');
if(isset($_POST['predictedMatches'])&&$_SESSION['userid']){
$predictedMatches=$_POST['predictedMatches'];
$userid=$_SESSION['userid'];
}else die("ERROR");
$sql="";
foreach($predictedMatches as $predictedMatch){
$sql.="INSERT INTO predictions(result,userFK,matchFK,tournamentFK) VALUES('".$predictedMatch['result']."','".$userid."','".$predictedMatch['id']."','".$predictedMatch['tourid']."');";
}
if($conn->multi_query($sql) === TRUE){
echo "OK";
}else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Use the ON DUPLICATE KEY UPDATE feature. It won't insert, if the primary key exists. But you have to update some value, so use the column which is in no index or in the least indexes () in your case probably result). Your primary key has to be composted out of the three FKs:
ALTER TABLE `predictions` ADD PRIMARY KEY( `userFK`, `matchFK`, `tournamentFK`);
PHP-Code, just the SQL statment (I'm a Java Guy, so i tried my best)
$sql.="INSERT INTO predictions (result, userFK, matchFK, tournamentFK) "
."VALUES('".$predictedMatch['result'] ."','".$userid."','"
.$predictedMatch['id']."','".$predictedMatch['tourid']."') "
."ON DUPLICATE KEY UPDATE result = result ;";
To know if the query was inserted you have to look at the affected row count:
1 Row - Insert
2 Rows - Update
Take a look at $conn->affected_rows after the query.
Performance
INSERT ... ON DUPLICATE KEY UPDATE is definitively faster than a SELECT and INSERT but it's slower than an INSERT of just the needed datasets. The update is done in the database, even if it is the same value. Unfortunately there is no ON DUPLICATE KEY UPDATE INGNORE. If you have a lot of inserts, that will result in updates, than it may be better to use a cache, lookup values in an array and compare with the array before inserting. Only use the ON DUPLICATE KEY UPDATE as fallback.
var hbar = new RGraph.HBar('cvs', [100,700])
The above code is a JavasSript function which generates a bar graph 100 and 700 as parameters. The problem is MySql coloumn values. I need to pass through that function to get a complete graph of values that are been inserted.
database name :fosdb Table name [vedordb] coloumn name [name]under namejackjames are values
Tried few code snippets but was unable to figure out how to detect those mysql coloumn values and fetch them to javascript variables using php.
Ex: say MySql coloumn 'Aname' has values inserted with 100, 300
I need first fetch them to PHP; repeat a loop depending on the length then assign each array to a JavaScript loop which assigns one more array then pass these array variables to the above JavaScript function so that I can see dynamic results every time.
Please help me out friends.
Thanks in advance.
Take a look on this example, its similar to like this:
//$database_data = array(100, 200);
$data_collector = array();
// Your Query here
$stmt = "select Aname from Table_Name";
$query = mysql_query($stmt);
while( $row = mysql_fetch_array($query) ) {
$data_collector[] = $row['Aname'];
}
// Implode it
$collection = implode(", ", $data_collector);
PHP data Example : http://codepad.org/SRvxXjVK
Now pass $collection to JavaScript array like:
var Collection = [<?php echo $collection ?>];
// OR according to your code
var hbar = new RGraph.HBar('cvs', [<?php echo $collection ?>])
Hope this help you.
Let me start by explaining the situation:
I have a MySql table that contains several columns, of which a user id, a race id, a lap time, a lap number and I want to put this information into an array in PHP which I will then send to a java script.
My JavaScript array should end up looking like this :
first row:
[laptime1 user1, laptime2 user1, laptime3 user1,...]
second row:
[laptime1 user2, laptime2 user2, laptime3 user2,...]
Here's my current situation:
I first tried to test this situation for a single user and ran into lots of problems because my lap times in MySql are floats and when using json_encode it turned everything into strings, which did not work for my javascript as it started outputting the wrong values.
For example:
The first value was "8" instead of "84,521", then the second value was "4", etc..)...
Sadly, I found a potential solution with the numeric check option, but cannot use it as my hosting runs a PHP version that doesn't support it.
So I found the following solution, which I fiddled with a bit and that works for a single user (it might look messy to you, I'm really a beginner and punching above my weight, but it works) :
$query = doquery("SELECT racelaptime,userid FROM {{table}} WHERE raceid='1' ORDER BY racelap", "liverace");
while(($result = mysql_fetch_array($query))) {
$data[] = (float)$result['racelaptime'];
}
$script = $script . "\nvar myArray = new Array(";
foreach ($data as $key => $value){
if ($key < (count($data)-1)){
$script = $script . $value . ',';
}
else {
$script = $script . $value . ");\n";
}
}
This outputs an array in JavaScript that looks like this :
myArray=[84.521,83.800,81.900]
Which is great, as this is exactly what my java script requires as input (time in seconds, separated by commas for each lap).
Now I would like to implement the multiple user element but I'm stumped as to how I can work that out...
My MySQL query is still sorted by race lap but I also kind of need to sort the data by user id as I want all the laps of each user sorted in 1 row, Also, the user id is unknown to me and can vary (depends which user posts the time) so I can't really do a "if userid==1 save this here and then go to next one".
Should I use a foreach statement in the while loop that stores the data, but how can I tell him to store all the laps by the same user in the first row (and the next user in the second row, etc...) without using tons of SQL queries ?
If you can offer a more elegant solution than my current one for passing the PHP array to JavaScript, I would be more than happy to make changes but otherwise a simple solution using the current "setup" would be great too (hope it's all clear enough).
Any help would be very much appreciated, thanks in advance !
For multiple user element I would use a multidimensional array >
$query = doquery("SELECT racelaptime,userid FROM {{table}} WHERE raceid='1' ORDER BY racelap", "liverace");
// Loop the DB result
while(($result = mysql_fetch_array($query))) {
// Check if this ID is already in the data array
if(!array_key_exists($result['userid'], $data)){
// Create array for current user
$data[$result['userid']] = array();
}
// Add the current race time to the array (do not need to use the float)
$data[$result['userid']][] = $result['racelaptime'];
}
// Echo json data
echo json_encode($data);
Now what you need to do on the Javascript side when handling this array is to go through each of the user
$.each(data, function(key, value){
// Use parseFloat to keep the decimal value
alert(key + ' Has the following values - ' + value);
// If you want to display the racing values you simply
$.each(value, function(k, parseFloat(v)){
alert(v);
})
})
Is this what you needed or am I completely out of the scope?