I have problem undefined variable. The thing is, I found a tutorial to make a type micro blog Twitter, had some problems, I decided, but this is taking me patience.
Error Message:
Notice: Undefined variable: extra in caminho\do\arquivo\functions.php on line 58
function:
function show_users($user_id=0){
if ($user_id > 0){
$follow = array();
$fsql = "SELECT user_id FROM following WHERE follower_id='$user_id'";
$fresult = mysql_query($fsql);
while($f = mysql_fetch_object($fresult)){
//array_push($follow, $f->user_id);
$follow[] = $f->user_id;
}
if (count($follow)){
$id_string = implode(',', $follow);
$extra = " AND id IN ($id_string)";
}else{
return array();
}
}
$users = array();
$sql = "SELECT id, username FROM users WHERE status='active' $extra ORDER BY username";
$result = mysql_query($sql);
while ($data = mysql_fetch_object($result)){
$users[$data->id] = $data->username;
}
return $users;
}
The line in question is:
$sql = "SELECT id, username FROM users WHERE status='active' $extra ORDER BY username";
Any suggestions?
There are two ways :
1. function show_users($user_id=0){
$extra='';
2. function show_users($user_id=0,$extra=''){
Actually you are declaring $extra only when you have $user_id > 0 BUT you must be having $user_id equals to or less than 0 for the current situation and thus your query couldn't find $extra.
I hope you get an idea.
function show_users($user_id=0){
$extra = ''; //if no extra, you'll get just an empty string
//etc...
}
function show_users(...) {
$extra = ''; // <--just add this line
blah blah blah blah blah
}
In your code, $extra gets defined ONLY if both if() tests succeed. Obviously they're not, so you end up with an undefined $extra in your sql string.
function show_users($user_id=0,extra='') // use this
{
if ($user_id > 0){
$follow = array();
$fsql = "SELECT user_id FROM following WHERE follower_id='$user_id'";
$fresult = mysql_query($fsql);
while($f = mysql_fetch_object($fresult)){
//array_push($follow, $f->user_id);
$follow[] = $f->user_id;
}
if (count($follow)){
$id_string = implode(',', $follow);
$extra = " AND id IN ($id_string)";
}else{
return array();
}
}
Related
I am inserting multiple rows from one submit button by the usage of array. Insertion of records is working smoothly. Now I want to stop insertion of data if record is already existed. My syntax for single record updating is works to prevent multi-insertion of same record. But I am confused and can't get idea while using array. I've tried a lot, but every method display error.
This code is working.
if(isset($_POST['submit'])){
$number = $_POST['number'];
$letter = $_POST['letter'];
$sql = "INSERT INTO class(number, letter) VALUES(:number, :letter)";
$query = $con->prepare($sql);
foreach($number AS $key => $n){
$query->bindParam(':number', $number[$key]);
$query->bindParam(':letter', $letter[$key]);
$query->execute();
}
}
My intention is to stop insertion of data if it is already inserted. So I tried like this. I am sure it is wrong because array variable can't pass to first syntax**(sql1)** and $query is not being accessed to foreach clause. I have no idea, So I used like this. Please provide me any idea to stop already inserted record.
I want to change in this code
<?php
if(isset($_POST['submit'])){
$number = $_POST['number'];
$letter = $_POST['letter'];
$sql1 = 'SELECT COUNT(*) FROM class WHERE number = :number';
$stmt = $con->prepare($sql1);
$stmt->bindParam(':number', $number[$key]);
$stmt->execute();
if($stmt->fetchColumn()){
echo"<script>alert('Class is already existed')</script>";
}
else{
$sql = "INSERT INTO class(number, letter) VALUES(:number, :letter)";
$query = $con->prepare($sql);
}
foreach($number AS $key => $n){
$query->bindParam(':number', $number[$key]);
$query->bindParam(':letter', $letter[$key]);
$query->execute();
}
}
?>
This code displays following error
Notice: Undefined variable: key in C:\xampp\htdocs\marksheet\class.php on line 53
Notice: Undefined variable: query in C:\xampp\htdocs\marksheet\class.php on line 57
Fatal error: Uncaught Error: Call to a member function bindParam() on null in C:\xampp\htdocs\marksheet\class.php:57 Stack trace: #0 {main} thrown in C:\xampp\htdocs\marksheet\class.php on line 57
This should work:
if (isset($_POST['submit'])) {
if(!empty($_POST['number']) && !empty($_POST['letter']) )
{
$number = $_POST['number'];
$letter = $_POST['letter'];
// Assuming both $number and $letter 1 dimensional array with equal number of indexes
$notInsertedKey = [];
foreach ($number AS $key => $item) {
/* Checking Existence*/
$sql1 = 'SELECT COUNT(*) as counted FROM class WHERE number = :number';
$stmt = $con->prepare($sql1);
$stmt->bindParam(':number', $number[$key]);
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC);
if ($data['counted'] < 1) {
// echo "Not Exist";
$sql = "INSERT INTO class(number, letter) VALUES (:number, :letter)";
$query = $con->prepare($sql);
$query->bindParam(':number', $number[$key]);
$query->bindParam(':letter', $letter[$key]);
$query->execute();
} else {
$notInsertedKey[] = $key;
// Incase you want to know the failed indexes.
echo "<script>alert('Class is already existed')</script>";
}
}
}
}
UPDATE
Solution suggested by #AlivetoDie works well as shorthand way to insert unique data and drop the duplicated one. However, it doesn't have any means to track the failed data indexes since the query always returns TRUE.
I would like to recommend following way. First of all you need a dynamic function which should check record in the relevant table
function isExist($columnName, $columnValue, $tableName){
$columnName = (!empty($columnName)) ? $columnName : 'empty';
$columnValue = (!empty($columnValue)) ? $columnValue : 'empty';
$tableName = (!empty($tableName)) ? $tableName : 'empty';
$exist = 0;
if($columnName != 'empty' && $columnValue != 'empty' && $tableName != 'empty'){
$sql = "select * from `".$tableName."` where `".$columnName."` = '".$columnValue."'";
$isExist = mysqli_query($this->connection,$sql);
if(mysqli_num_rows($isExist) > 0){
$exist = 1;
}
}
return $exist;
}
Then use it in your function by following way
if(isset($_POST['submit'])){
$error = 0;
$response = array();
$number = $_POST['number'];
$letter = $_POST['letter'];
$number_name_exist = $this->isExist('number', $number, 'class');
if($number_name_exist == 1){
$error = 1;
$response['error'] = $number . ' is already exists';
}
if($error == 0){
$sql = "INSERT INTO class(number, letter) VALUES(:number, :letter)";
$query = $con->prepare($sql);
foreach($number AS $key => $n){
$query->bindParam(':number', $number[$key]);
$query->bindParam(':letter', $letter[$key]);
$query->execute();
}
}
}
In the above example you can see there $error variable and $response array which will be make your script more dynamic and you can prevent duplicate insertion and also you can check multiple columns.
To explain my issue, here is a simple code at first:
public function sql($data) {
if (is_array($data)) {
$cells = $data['cells'];
$from = $data['from'];
$where = $data['where'];
$joins = $data['joins'];
$order_by = $data['order_by'];
$o_type = $data['order_by_type'];
$limit = $data['limit'];
/*****************************/
if ($cells == '') { $cells = "*"; }
if ($where != '') { $where = "where ".$where; }
if ($oredr_by != '') { $order_by = "order by ".$order_by." ".$o_type; }
if ($limit != '') { $limit = "limit ".$limit; }
//
$sql = "select ".$cells." from ".$from." ".$joins." ".$where." ".$order_by." ".$limit;
$run = mysqli_query($_SESSION['con'], $sql);
}else{
$run = mysqli_query($_SESSION['con'], $data);
}
}
When I start using this method, I pass a multidimensional array as a parameter, like this:
$sql = $class->sql([ "from" => "table", "order_by" => "id", "order_by_type" => "asc" ]);
/* This will generate and run this query: select * from table order by id asc */
// Notice that I've only used 3 keys, not the all above.
In Apache server, it works OK perfectly when I just use some of the keys of array, but in XAMPP it doesn't because it says that I have to pass all the parameters (cells, from, where, joins, ...) even if they are empty.
Please help me to resolve this, and thanks.
You can use isset to check if an array key is present, then get it's value like.
public function sql($data) {
if (is_array($data)) {
$cells = '';
if(isset($data['cells']) {
$cells = $data['cells'];
}
....
/*****************************/
if ($cells == '') { $cells = "*"; }
if ($where != '') { $where = "where ".$where; }
if ($oredrby != '') { $orderby = "order by ".$orderby." ".$od_type; }
if ($limit != '') { $limit = "limit ".$limit; }
$sql = "select ".$cells." from ".$table." ".$joins." ".$where." ".$orderby." ".$limit;
$run = mysqli_query($_SESSION['con'], $sql);
}else{
$run = mysqli_query($_SESSION['con'], $data);
}
}
Or simply just do error_reporting(1) before calling this function or in your index.php.
The problem is this.
$arr = ["a"];
echo $arr["b"];
You will get an error notice.
Notice: Undefined index: b
If you want to avoid this use it in this way.
$arr = ["a"];
$arr = ["b"] = "";
echo $arr["b"];
Change $from to $table, you have not $table variable
$from = $data['from'];
to
$table = $data['from'];
Also you have spelling mistake biggest spelling mistake which is very difficult to find.orderby and oredrby
Edit: I've changed the query to this version but I'm still not getting any
results even when I should be.
if (isset($_POST['schbttn'])) {
$breed1 = $_POST['schbreed1'];
$breed2 = $_POST['schbreed2'];
$sex = $_POST['schsex'];
$colour = $_POST['schcolour'];
$age = $_POST['schage'];
include ('inc/dbconn.php');
// If breed2 NULL, search with this query
if ($breed2 == "NULL") {
$search = mysqli_query($dbconn, "SELECT * FROM `lstfnd` WHERE `doglf_stat` = 'Lost' AND `doglf_breed1` = '$breed1' AND `doglf_breed2` IS NULL AND `doglf_sex` = '$sex' AND `doglf_colour` = '$colour' AND `doglf_age` = '$age'");
// Else search with this query
} else {
$search = mysqli_query($dbconn, "SELECT * FROM `lstfnd` WHERE `doglf_stat` = 'Lost' AND `doglf_breed1` = '$breed1' AND `doglf_breed2` = '$breed2' AND `doglf_sex` = '$sex' AND `doglf_colour` = '$colour' AND `doglf_age` = '$age'");
}
$schrow = mysqli_fetch_assoc($search);
}
I'm trying to create a simple search function where a user can search by multiple fields.
I've taken the entries of each field
$breed1 = $_POST['breed1'];
$breed2 = $_POST['breed2'];
$sex = $_POST['sex'];
$colour = $_POST['colour'];
$age = $_POST['age'];
and built the query through if loops
$query = "SELECT * FROM `table` WHERE `stat` = 'Lost'";
// If breed1 is not ALL, add to search
if ($breed1 != "ALL") {
$query = $query." AND `breed1` = '$breed1'";
}
// If breed2 is not ALL, add to search
if ($breed2 != "ALL") {
if ($breed2 == "NULL") {
$query = $query." AND `breed2` IS NULL";
} else {
$query = $query." AND `breed2` = '$breed2'";
}
}
// If sex is not ALL, add to search
if ($sex != "ALL") {
$query = $query." AND `sex` = '$sex'";
}
// If colour is not ALL, add to search
if ($colour != "ALL") {
$query = $query." AND `colour` = '$colour'";
}
// If age is not ALL, add to search
if ($age != "ALL") {
$query = $query." AND `age` = '$age'";
}
$query = $query.";";
and placed the query in a PHP variable to use when running the query.
include ('inc/dbconn.php');
$search = mysqli_query($dbconn, "'.$query.'");
$schrow = mysqli_fetch_assoc($search);
However, when I try to display the results of the search, I get an error code.
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given...
So is what I am attempting possible to accomplish using this method? And if not, any suggestions for alternative methods?
change this line
$search = mysqli_query($dbconn, "'.$query.'");
to
$search = mysqli_query($dbconn, $query);
$query is variable, do not use that as string.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Display Data From MYSQL; SQL statement error
I have the code below displaying data from a MYSQL database (currently looking into sql injection issue) I need to insert an error message when no results are found...not sure where to position this! I have tried the code if( mysql_num_rows($result) == 0) {
echo "No row found!" but keep on gettin syntax errors, does anyone know the correct position in the code for this?
--
require 'defaults.php';
require 'database.php';
/* get properties from database */
$property = $_GET['bedrooms'] ;
$sleeps_min = $_GET['sleeps_min'] ;
$availability = $_GET['availability'] ;
$query = "SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' AND sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'";
$row=mysql_query($query);
$result = do_query("SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'", $db_connection);
while ($row = mysql_fetch_assoc($result))
{
$r[] = $row;
}
?>
I have found few errors in your code that in line
$query = "SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' AND sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'";
$row=mysql_query($query);
You use bedrooms = '{$bedrooms}' but $bedrooms is not variable in whole cod it must be $preopery. I have made a few changes in your code given below please try it.
<?php
require 'defaults.php';
require 'database.php';
/* get properties from database */
/*if get $_GET['bedrooms'] value else ''*/
if (isset($_GET['bedrooms'])) {
$property = $_GET['bedrooms'];
} else {
$property = '';
}
/*if get $_GET['sleeps_min'] value else ''*/
if (isset($_GET['sleeps_min'])) {
$sleeps_min = $_GET['sleeps_min'];
} else {
$sleeps_min = '';
}
/*if get $_GET['availability'] value else ''*/
if (isset($_GET['availability'])) {
$availability = $_GET['availability'];
} else {
$availability = '';
}
$query = "SELECT * FROM `properties` WHERE bedrooms = '" . $property . "' AND sleeps_min = '" . $sleeps_min . "' AND availability = '" . $availability . "'";
$result = mysql_query($query) or die(mysql_error());
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$r[] = $row;
}
}
?>
Do var_dump($GET_) to debug whether you are getting valid strings. If any of these are blank, the query will try to match blank values instead of NULL. You should prevent this by doing:
if(!$_GET['bedrooms'] || $_GET['bedrooms'] == ''){
$property = 'NULL';
}//repeat for all three
$query = "SELECT * FROM `properties` WHERE 'bedrooms' = '$bedrooms' AND 'sleeps_min' = '$sleeps_min' AND 'availability' = '$availability'";
Instead of:
while ($row = mysql_fetch_assoc($result)) {
$r[] = $row;
}
You can simply do:
$r = mysql_fetch_array($query);
But enclose that in a conditional to see if your query found anything:
if(mysql_affected_rows() > 0){
//your code here will execute when there is at least one result
$r = mysql_fetch_array($query);
}
else{//There was either nothing or an error
if(mysql_affected_rows() == 0){
//There were 0 results
}
if(mysql_affected_rows() == -1) {
//This executes when there is an error
print mysql_error(); //not recommended except to debug
}
}
The first question is how to run a function using the URL, I have the following function:
function do_curl($start_index,$stop_index){
// Do query here to get all pages with ids between start index and stop index
$query = "SELECT * FROM xxx WHERE xxx >= $start_index and xxx <= $stop_index";
Now when I'm trying to do curl.php?start_index=0&stop_index=2 this is not working but when i delete the function and WHERE idnum = 1 it is working.
Now the second question is how 'compile' all the fields from the rows to arrays? I have the current code:
$query = "SELECT * FROM fanpages";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$fanpages_query = '\'http://graph.facebook.com/'.$row['page_id'].'\', ';
echo $fanpages_query;
}
$fanpages = array($fanpages_query);
$fanpages_count = count($fanpages);
echo $fanpages_count;
echo $fanpages_query; returning
'http://graph.facebook.com/AAAAAA', 'http://graph.facebook.com/BBBBBBB', 'http://graph.facebook.com/CCCCCCCC',
(I don't have an idea how to do it in a different way, also when im doing it in such a way i can't delete the final comma which will return PHP-error.)
echo $fanpages_count; returns 1 and like you can see i have 3 there.
Thanks in advance guys!
Do a function call to do the query
function do_curl($start_index, $stop_index){
...
}
$fanpages = do_curl($_GET['start_index'], $_GET['stop_index']);
For your second question, you can use arrays and the implode function to insert commas:
while ($row = mysql_fetch_array($result))
{
$fanpages_query[] = 'http://graph.facebook.com/'.$row['page_id'];
}
return $fanpages_query;
Then use implode to print them out:
echo implode(',', $fanpages);
The whole code:
function do_curl($start_index = 0, $stop_index = null) {
$queryIfThereIsNoStartIndex = '';
$queryIFThereIsNoStopIndex = '';
$queryIfBothStartAndStopIndexAreMissing = '';
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$fanpages_query[] = 'http://graph.facebook.com/'.$row['page_id'];
}
return $fanpages_query;
}
$fanpages = do_curl($_GET['start_index'], $_GET['stop_index']);
$fanpages_count = count($fanpages);
echo implode(',', $fanpages);
And you should totally use mysql_escape_string for escaping the values you add to the query.