passing arguments through to a function - php - php

I have the following code that is supposed to call a function in a loop, and then pass the argument to it and put the selected items in a database. I don't think I am passing the correct arguments through to the function though, so can you have a look?
<?php
function welcome($grill){
$link = mysql_connect('localhost', 'sc2brsting', '1A2');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db('sc2bring1', $link);
$sql = "INSERT INTO `sc2broad_tesing1`.`Persons` (`re`) VALUES ($grill)";
mysql_query($sql);
mysql_close($link);
}
?>
<?php
$grass=0;
while($grass<500){
$file = $DOCUMENT_ROOT . "website.com";
$doc = new DOMDocument();
#$doc->loadHTMLFile($file);
$elements = $doc->getElementsByTagName('a');
for ($i=106; $i<=204; $i=$i+2)
{
$grill = $elements->item($i)->nodeValue . " ";
welcome($grill);
}
$grass=$grass+24;
}
?>
the problem im having is that the variable $grill isn't passing through the function

You are not escaping the variable $grill when inserting it into to database.
This will cause an MySQL error, hence the impression the argument is not passed to the function.
The line should look like this:
$sql = "INSERT INTO `sc2broad_tesing1`.`Persons` (`re`) VALUES ('".$grill."')";

Related

Can't access the mysqli_result Object of an sql query

Hi I have a problem with this method and it's driving me crazy.The query below should return one field from the database, an id where the filename is matched. Only one value should be returned. When I run the query I get an SQL object returned which looks fine:
mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => [num_rows] => 0 [type] => 0 )
However I cannot access the above query object no matter what way I try or at least I'm getting no value out of it. I did the exact same to get the package id and it works perfectly.
I used $row = $result_package_id->fetch_array(MYSQLI_ASSOC);
to get the package_id and I tried that for the module_id but it didn't work. Tried the mysqli_fetch_array and it doesn't work either. At a loss of what to do next can anyone help?
ADDED getPackageId method and if statement where the two methods are called. Every time a query is successful the id and package id are retrieved and a new object is created with the two values.
function getId($fileName){
$con = connect();
if (!$con) {
trigger_error(mysqli_error($con), E_USER_ERROR);
die('Could not connect: ' . mysqli_error($con));
}
$yModuleId = 0;
$sql_filename = mysqli_real_escape_string($con, $fileName);
$query_module_id = "SELECT id FROM y_module WHERE fileName='" . $sql_filename . "'";
$result_module_id = mysqli_query($con, $query_module_id);
while($row_model = mysqli_fetch_array($result_module_id)){
$yModuleId = $row_model['id'];
return $yModuleId;
}
}
function getYPackageId($package_name){
$con = connect();
if (!$con) {
trigger_error(mysqli_error($con), E_USER_ERROR);
die('Could not connect: ' . mysqli_error($con));
}
$sql_packageName = mysqli_real_escape_string($con, $package_name);
$query_package_id = "SELECT id FROM y_package WHERE name='" . $package_name . "'";
$result_package_id = mysqli_query($con, $query_package_id) or die("__LINE__ : " . mysqli_error($con));
while($row_package = mysqli_fetch_array($result_package_id)){
$yPackageId = $row_package['id'];
print_r($yPackageId);
print_r("</br>");
print_r("</br>");
return $yPackageId;
};
}
if($result_model && $result_package && $result_model_package) {
$yModuleId = getId($fileName);
$yPackageId = getYPackageId($package_name);
$yIdObject = new YIds($yModuleId, $yaPackageId);
$yIdObjects [] = $yIdObject;
mysqli_query($con, "COMMIT");
$message = array("success", "[SUCCESS]", "Model published successfully.",$module_id);
}
You can use
while ($row = $result->fetch_assoc()) {
$saved[] = $row;
}
but I think from your code displayed a more important issue is that you seem to be mixing procedural and object orientated SQL querying.
So:
1) Rewrite yourcode to use objects, your usage of mysqli_ functions only returns arrays.
2) or alternatively, use the current code as an array because that's what it is, not an object.
Procedural
function getId($fileName){
//this does nothing. Unless this is a custom function?
//$con = connect();
// should be:
$con = mysqli_connect(details,...);
if (!$con) {
trigger_error(mysqli_error($con), E_USER_ERROR); //?
die('Could not connect: ' . mysqli_error($con));
}
//$yModuleId = 0; //unneeded.
$sql_filename = mysqli_real_escape_string($con, $fileName);
$query_module_id = "SELECT id FROM y_module WHERE fileName='" . $sql_filename . "'";
//add an error feedback for debugging:
$result_module_id = mysqli_query($con, $query_module_id) or die("__LINE__.":".mysqli_error($con));
while($row_model = mysqli_fetch_array($result_module_id)){
$yModuleId = $row_model['id'];
return $yModuleId;
}
}
Object Orientated:
$query_module_id = "SELECT id FROM y_module WHERE fileName='?'";
$con = new mysqli($details,...);
$thisQuery = $con->prepare($query_module_id);
$thisQuery->bind_param("s",$sql_filename);
$thisQuery->execute();
while ($row = $thisQuery->fetch_assoc()) {
$saved[] = $row;
}
$thisQuery->close();
From this the $saved variable will be an array of results.
Additional notes:
You are using MySQL COMMIT near the bottom of your code and this is for transactions but you have not shown you've setup or begun any MySQL transactions.
You have a return inside a while statement in getYPackageId which means that the while wil only ever run once because as soon as it reaches the return it will do just that. Bad format.
Remove the semi-colon after the closing bracket of the while statement. This is bad syntax.
I figured out the problem and I feel like such an idiot! The problem was here
if($result_model && $result_package && $result_model_package) {
$yModuleId = getId($fileName);
$yPackageId = getYPackageId($package_name);
$yIdObject = new YIds($yModuleId, $yaPackageId);
$yIdObjects [] = $yIdObject;
mysqli_query($con, "COMMIT");
$message = array("success", "[SUCCESS]", "Model published successfully.",$module_id);
}
I was running the commit after I was trying to get the id and package_id from the database that's why I wasn't getting any results. I changed it to this:
if($result_model && $result_package && $result_model_package) {
mysqli_query($con, "COMMIT");
$yModuleId = getId($fileName);
$yPackageId = getYPackageId($package_name);
$yIdObject = new YIds($yModuleId, $yaPackageId);
$yIdObjects [] = $yIdObject;
$message = array("success", "[SUCCESS]", "Model published successfully.",$module_id);
}
It worked perfectly. This is how the getId() method looked when I got it working
function getId($moduleName, $moduleRevision){
$con = connect();
if (!$con) {
trigger_error(mysqli_error($con), E_USER_ERROR);
die('Could not connect: ' . mysqli_error($con));
}
$sql_moduleName = mysqli_real_escape_string($con, $moduleName);
$sql_moduleRevision = mysqli_real_escape_string($con, $moduleRevision);
$query_module_id = "SELECT id, module_name, module_revision FROM y_module";
$result_module_id = mysqli_query($con, $query_module_id);
while($row = mysqli_fetch_assoc($result_module_id)){
if($row['module_name'] === $moduleName && $row['module_revision'] == $moduleRevision){
return $row['id'];
}
}
}
Thanks to Martin for all the help and the advice much appreciated! Hope this can help someone by not making the same stupid mistake as me.

Display rows on a webpage from a function that uses mysqli to retrieve data

So I have the following code in PHP that contains a function which uses mysqli to retrieve data from my database:
function displayuser(){
$db = mysqli_connect("localhost", "root", "", "shop") or die("Error");
$query = "SELECT id, username FROM users";
$result = $db->query($query) or die("Error");
while($row = $result->fetch_array()) {
return $row['id'].' '.$row['username'];
}
}
My question is; how would I go about displaying $row['id'] and $row['username'] in a webpage using HTML presuming I would have to use PHP as well?
Should it be like this? Say in a PHP file user.php for instance
<?php
include_once('function.php');
foreach(displayuser() as $display) {
?>
<p><?php echo $display['id'];?></p>
<?php
}
?>
I used the display method above when I was handling mysql rather than mysqli, so I'm trying to familiarize myself with the improved mysql
EDIT (new code):
functions.php
function getuser() {
$db = mysqli_connect("localhost", "root", "", "shop") or die("Error");
$query = "SELECT id, username FROM users";
$result = $db->query($query) or die();
return $result->fetch_all(); }
display.php
<?php
include_once('functions.php');
foreach(getuser() as $user) {
echo $user['id']. ' '.$user['username'];
}
?>
When executing, display.php displays empty results.
I tried using print_r to print in the data behind the arrays but it seems the arrays were empty. I thought maybe we shouldn't use "foreach" or something.
For starters, the keyword return literally kills your script. Return means 'go back to what called me'. That said, the first row from your query will end the displayUser function. Restructure it like this:
$result = $db->query($query);
return $result->fetch_all();
Then the rest should work but I would reword and structure it.
include_once('function.php');
foreach(displayuser() as $user) {
echo "<p>" . $user['id'] . "</p>";
}
You are nearly there, you could go about doing it like this:
function.php
function get_users(){
$db = mysqli_connect("localhost", "root", "", "shop") or die("Error");
$query = "SELECT id, username FROM users";
$result = $db->query($query) or die("Error");
return $result->fetch_all();
}
Display File
<?php
include_once('function.php');
$users = get_users();
foreach($users as $user) {
echo '<p>' . $user['id'] . ' ' . $user['username'] . '</p>';
}
?>
This has a more clear separation of concerns, no HTML in the function call so it can be reused multiple times reducing duplicate code.

While database loop in a foreach array loop. PHP/MYSQL

The below script works fine but only for the first record in the array.
$codes = array(1,2,3,4,5,6,7,8,9,10); // demo for this question, i actually have 1000+
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect1: ' . mysql_error());
}
$con2 = mysql_select_db("db", $con);
if (!$con2)
{
die('Could not connect2: ' . mysql_error());
}
$productsid = "select `products_id` from `coupons_products` where `coupons_id`=58386264";
$productsquery = mysql_query($productsid);
foreach ($codes as $code) {
while ($productid = mysql_fetch_assoc($productsquery)){
$sql = "insert into discount_coupons_to_products values (
'$code',
'{$productid['products_id']}')";
$con4 = mysql_query($sql);
if (!$con4)
{
die('Could not connect4: ' . mysql_error());
}
}
} // end foreach
I have an array of codes from the database that need apply only to specific products(same as 58386264). The codes works but only for the first coupon in the array ($codes).
If I understand what it means, you will need to run mysql_query command every step inside foreach, not just run mysql_fetch_assoc like you're actually doing.

JSONKit - parse JSON String to PHP to MYSQL database

In my database I have the following schema:
Answers:
answerId(PK) auto_inc
answer
questionId
I am passing the following JSON String to my php file:
[{"answer":"bnk","questionId":"1"},{"answer":"1","questionId":"2"},{"answer":"b n","questionId":"3"},{"answer":"3","questionId":"4"},{"answer":"rgb","questionId":"5"},{"answer":"No","questionId":"6"},{"answer":"0","questionId":"7"},{"answer":"0","questionId":"8"},{"answer":"0","questionId":"9"},{"answer":"0","questionId":"10"},{"answer":"0","questionId":"11"},{"answer":"0","questionId":"12"},{"answer":"0","questionId":"13"},{"answer":"0","questionId":"14"},{"answer":"3","questionId":"18"},{"answer":"nko","questionId":"19"},{"answer":"hhkl","questionId":"15"},{"answer":"2","questionId":"16"},{"answer":"vnlf hugg","questionId":"17"}]
This is captured via a post request in $_POST['answers']:
if(isset($_POST['submitanswer'])){
$dbh = connect();
$user = $_POST['user'];
$entry = $_POST['entryId'];
$answers = $_POST['answers'];
$answers = json_decode($answers); //decode JSON answers
//for loop to iterate through answers ans insert new row into database
}
How do I iterate through the answers array and insert a new row into my answers table?
Something like:
foreach($answers as $row){
$query = "INSERT INTO Answers (answer, questionId) VALUES ($row['answer'], $row['questionId'])";
mysql_query($query);
}
If this code didn't work for you, try this:
foreach($answers as $row){
$query = "INSERT INTO Answers (answer, questionId) VALUES (".$row['answer'].", ".$row['questionId'].")";
mysql_query($query);
}
Otherwise, I can't spot anything wrong here.
I gues you know this but make sure your connection string is good.
Actually this is what I do. Probably a bit much info for you, also I do all that concatenation in the SQL so I can easily comment out fields for testing.
$Link = mysql_connect( $Host , $User , $Password , $DBName);
if (!$Link) {
die('Could not connect: ' . mysql_error());
}
$sql = "insert into table "
."("
."hashfirstName".","
."hashfamilyName".","
."hashemailAddress"
.")"
."values ("
."'$firstNameHashed'".","
."'$familyNameHashed'".","
."'$emailAddressHashed'"
.")";
mysql_select_db($DBName , $Link) or die("Database error in insertdata<br>"."Error #" . mysql_errno() . ": " . mysql_error());
if(!mysql_query($sql , $Link))
{
$errors['sql'] = $sql;
$errors['DBName'] = $DBName;
$errors['Link'] = $Link;
$errors['status'] = "false"; //There was a problem saving the data;
echo json_encode($errors);
}
else
{
$errors['status'] = "true";
echo json_encode($errors);
}; // if(!mysql_query( $DBName , $sql , $Link))

Unable to execute MYSQL query inside a PHP function

PHP:
function generate_uid() {
$uid = mt_rand();
$sql = "SELECT user_id
FROM user_registration";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
$result = mysql_query($sql);
$availability = TRUE;
while($row = mysql_fetch_array($result)) {
if($row['user_id'] == $uid) {
$availability = FALSE;
}
}
if($availability == FALSE) {
generate_uid();
}
}
The error
Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in E:\Web Design EC\register2.php on line 8
Error:
But when i execute this function as normal php there is no error and the $uid is generated. What maybe the problem??
$con is not defined in the current variable scope. You can pass the connection to function as a parameter:
function generate_uid($con) {
...
mysql_query($sql, $con);
}
$uid = generate_uid($con);
Or you can use global:
function generate_uid() {
global $con;
...
mysql_query($sql, $con);
}
$uid = generate_uid();
Or, simply leave the connection variable out, and the last opened connection will be used:
function generate_uid() {
...
mysql_query($sql);
}
$uid = generate_uid();
All of those should work.
To learn more about variable scope, check out the PHP manual on the subject at:
http://www.php.net/manual/en/language.variables.scope.php
You are using $con in your function, but $con is not defined in your function scope.
http://php.net/manual/en/language.variables.scope.php
You need to either
a) Pass $con to your function or
b) Set $con as a global
c) Not use $con at all eg.
if (!mysql_query($sql))
however make sure that your app is only connecting to ONE database, otherwise you will run into issues because when you don't specify a connection it will use the last connection opened.
Inside your function, your MySQL connection doesn't exist. You either need to pass it in, or use the global keyword:
$con = mysql_connect('localhost', 'mysql_user', 'mysql_password');
function generate_uid()
{
global $con;
$uid = mt_rand();
$sql="SELECT user_id FROM user_registration";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$result = mysql_query($sql);
$availability=TRUE;
while($row = mysql_fetch_array($result))
{
if($row['user_id']==$uid)
{
$availability=FALSE; }
} if($availability==FALSE) { generate_uid(); }
}
while($row = mysql_fetch_array($result))
You can't use that if you plan to use $row as an associative array. Use:
while($row = mysql_fetch_assoc($result))
instead.
EDIT
MYSQL_BOTH is turned on by default, forgot about that. The problem is pointed out by the other users, regarding the connection not being available in the function scope.

Categories