im using this script through $_GET to add user name to my db beside it to my twitter list the script function well
for examlpe when i call it at url domain.com/add.php?user=username
the function of adding executed 100% fine
My doubt is about adjust the code to add multi users at once through array or get list of user from file
any tips to adjust the code or modify it ?
<?php
session_start();
require_once('dbconnect.php');
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,TOKEN_KEY, TOKEN_SECRET);
$user = $_GET['user'];
if( !isset( $_GET['user'] ) )
die('You must enter a username');
$info = $connection->get( 'users/show', array("screen_name"=> $user
));
$var = $_GET['user'];
$individual = 1;
$protected = ($info->protected == "true")?1:0;
$query = sprintf("INSERT INTO tweeps VALUES('%s', '%s', %s, %s, '%s', '%s', '%s', %s ) ",
mysql_real_escape_string($info->screen_name),
mysql_real_escape_string($info->name),
$info->followers_count,
$info->statuses_count,
mysql_real_escape_string($info->location),
$info->created_at,
$info->profile_image_url,
$protected) ;
echo $query;
$result = mysql_query($query);
if(false)
echo "s";
else {
$list_id = get_latest_list();
$list = "Tweeps-" . $list_id;
echo "list $list";
mysql_free_result($result);
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, TOKEN_KEY, TOKEN_SECRET);
$result = $connection->post( 'friendships/create/' . $info->screen_name );
//var_dump($result); die();
$result = $connection->post( 'lists/members/create', array("screen_name"=> $info->screen_name,
"slug"=> $list,
"owner_screen_name"=> "Tweeps") );
if( !isset($result->error) ) {
$userid = $info->id;
$result = mysql_query("INSERT INTO followed_tweeps(screenname, userid, individual, list_id) VALUES('" . $info->screen_name . "', '" . $userid . "', $individual, $list_id)");
}
}
echo "SUCCESS";
function get_latest_list() {
$query = "SELECT count(*) cnt, list_id FROM followed_tweeps group by list_id order by list_id desc";
$result = mysql_query($query);
if(! $result ) {
die("Error: query is $query error is: " . mysql_error() );
}
$row = mysql_fetch_row($result);
$cnt = $row[0];
$free_slots = 500 - $cnt;
$list_id = ($freeslots > 0) ? $row[1]++ : $row[1];
return $list_id;
}
?>
PHP supports an array notation for multiple same-name query parameters:
<input type="text" name="name[]" />
^^--- tells PHP to treat 'name' as an array
You can then process this as:
if (isset($_GET['name']) && isarray($_GET['name'])) {
foreach ($_GET['name'] as $name) {
...
}
}
This works regardless for both POST and GET - you just have to include the [] on the field name.
Related
I have use a lot of answers here to solve almost everything, but i can't figure out how to accomplish this;
I use PHP to get data from my MySQL, and encode to json with url request, so wen I go to miweb. com /_js/ajax/load_content.php?f=1
I get a perfect response from my databesa and echo to json encode, 1 means user with id number 1
my response looks like this:
[{"i":"1","n":"Azul","p":"_imgs\/site\/iconos\/0-100\/22\/activo\/ico_00022_138.jpg"}]
and if i go to miweb. com/_js/ajax/load_content.php?f=2 i will get
[{"i":"2","n":"Lety","p":"_imgs\/site\/iconos\/0-100\/87\/activo\/ico_00087_138.jpg"}]
what i need to accomplish is to go to ?f=1,2
miweb.com /_js/ajax/load_content.php?f=1,2 and get the response in same json like this
[{"i":"1","n":"Azul","p":"_imgs\/site\/iconos\/0-100\/22\/activo\/ico_00022_138.jpg"},
{"i":"2","n":"Lety","p":"_imgs\/site\/iconos\/0-100\/87\/activo\/ico_00087_138.jpg"}]
this is my php scrip:
require '../../system/config.php';
if( isset($_GET['h']) ) {
get_ficha($_GET['h']);
} else {
die("Solicitud no vĂ¡lida.");
}
function get_ficha( $id) {
// CONECCION DATABASE//
$database = new mysqli(HOST, USER, PASS, DBNAME);
if($database->connect_errno) {
die("No se pudo conectar a la base de datos");
}
mysqli_set_charset($database, "utf8");
//Sanitize ipnut y preparar query
if( is_array($id) ) {
$id = array_map('intval', $id);
$promo = "WHERE `ID` IN (" . implode( ',', $id ) . ")";
} else {
$id = intval($id);
$promo = "WHERE `ID` = " . $id;
}
if ( $result = $database->query( "SELECT * FROM (ficha)" . $promo) ) {
if( $result->num_rows > 0 ) {
$promo = array();
while( $row = mysqli_fetch_array($result))
{
$id=$row['id'];
$nombre=$row['nombre'];
$icono=$row['ico_138'];
$promo[] = array(
'i'=> $id,
'n'=> $nombre,
'p'=> $icono
);
}
} else {
$promo = array(
);
}
$result->close();
} else {
$promo["success"] = false;
$promo["data"] = array(
'message' => $database->error
);
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($promo, JSON_UNESCAPED_UNICODE);
$database->close();
}
exit();
You need to explode the get variable
get_ficha(explode(',', $_GET['h']));
Then in your function
if( is_array($id) && count($id) > 1) {
$id = array_map('intval', $id);
$promo = "WHERE `ID` IN (" . implode( ',', $id ) . ")";
} else {
$id = intval($id);
$promo = "WHERE `ID` = " . $id;
}
MySql query returns me a multi-dimensional array :
function d4g_get_contributions_info($profile_id)
{
$query = "select * from contributions where `project_id` = $profile_id";
$row = mysql_query($query) or die("Error getting profile information , Reason : " . mysql_error());
$contributions = array();
if(!mysql_num_rows($row)) echo "No Contributors";
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[$cnt]['user_id'] = $fetched['user_id'];
$contributions[$cnt]['ammount'] = $fetched['ammount'];
$contributions[$cnt]['date'] = $fetched['date'];
$cnt++;
}
return $contributions;
}
Now I need to print the values in the page where I had called this function. How do I do that ?
change the function like this:
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[] = array('user_id' => $fetched['user_id'],
'ammount' => $fetched['ammount'],
'date' => $fetched['date']);
}
return $contributions;
Then try below:
$profile_id = 1; // sample id
$result = d4g_get_contributions_info($profile_id);
foreach($result as $row){
$user_id = $row['user_id']
// Continue like this
}
I am passing a number of values to a function and then want to create a SQL query to search for these values in a database.
The input for this is drop down boxes which means that the input could be ALL or * which I want to create as a wildcard.
The problem is that you cannot do:
$result = mysql_query("SELECT * FROM table WHERE something1='$something1' AND something2='*'") or die(mysql_error());
I have made a start but cannot figure out the logic loop to make it work. This is what I have so far:
public function search($something1, $something2, $something3, $something4, $something5) {
//create query
$query = "SELECT * FROM users";
if ($something1== null and $something2== null and $something3== null and $something4== null and $something5== null) {
//search all users
break
} else {
//append where
$query = $query . " WHERE ";
if ($something1!= null) {
$query = $query . "something1='$something1'"
}
if ($something2!= null) {
$query = $query . "something2='$something2'"
}
if ($something3!= null) {
$query = $query . "something3='$something3'"
}
if ($something4!= null) {
$query = $query . "something4='$something4'"
}
if ($something5!= null) {
$query = $query . "something5='$something5'"
}
$uuid = uniqid('', true);
$result = mysql_query($query) or die(mysql_error());
}
The problem with this is that it only works in sequence. If someone enters for example something3 first then it wont add the AND in the correct place.
Any help greatly appreciated.
I would do something like this
criteria = null
if ($something1!= null) {
if($criteria != null)
{
$criteria = $criteria . " AND something1='$something1'"
}
else
{
$criteria = $criteria . " something1='$something1'"
}
}
... other criteria
$query = $query . $criteria
try with array.
function search($somethings){
$query = "SELECT * FROM users";
$filters = '';
if(is_array($somethings)){
$i = 0;
foreach($somethings as $key => $value){
$filters .= ($i > 0) ? " AND $key = '$value' " : " $key = '$value'";
$i++;
}
}
$uuid = uniqid('', true);
$query .= $filters;
$result = mysql_query($query) or die(mysql_error());
}
// demo
$som = array(
"something1" => "value1",
"something2" => "value2"
);
search( $som );
Here's an example of dynamically building a WHERE clause. I'm also showing using PDO and query parameters. You should stop using the deprecated mysql API and start using PDO.
public function search($something1, $something2, $something3, $something4, $something5)
{
$terms = array();
$values = array();
if (isset($something1)) {
$terms[] = "something1 = ?";
$values[] = $something1;
}
if (isset($something2)) {
$terms[] = "something2 = ?";
$values[] = $something2;
}
if (isset($something3)) {
$terms[] = "something3 = ?";
$values[] = $something3;
}
if (isset($something4)) {
$terms[] = "something4 = ?";
$values[] = $something4;
}
if (isset($something5)) {
$terms[] = "something5 = ?";
$values[] = $something5;
}
$query = "SELECT * FROM users ";
if ($terms) {
$query .= " WHERE " . join(" AND ", $terms);
}
if (defined('DEBUG') && DEBUG==1) {
print $query . "\n";
print_r($values);
exit();
}
$stmt = $pdo->prepare($query);
if ($stmt === false) { die(print_r($pdo->errorInfo(), true)); }
$status = $stmt->execute($values);
if ($status === false) { die(print_r($stmt->errorInfo(), true)); }
}
I've tested the above and it works. If I pass any non-null value for any of the five function arguments, it creates a WHERE clause for only the terms that are non-null.
Test with:
define('DEBUG', 1);
search('one', 'two', null, null, 'five');
Output of this test is:
SELECT * FROM users WHERE something1 = ? AND something2 = ? AND something5 = ?
Array
(
[0] => one
[1] => two
[2] => five
)
If you need this to be more dynamic, pass an array to the function instead of individual arguments.
I'm having trouble getting this function work. This is my database design
I'm working in an application wherein when a user deletes a parent category, all the subcategory would also be deleted, and so on and so fort..
For example:
When the user clicks on the "Test1" category in my application, the "Test1.1" and "Test1.1.1" would be deleted since it is under the "Test1" category.
This is my database design(above).
This is the code that I wrote:
function DeleteProjectPhotos( $cat_id ) {
$sql = "SELECT * FROM project_category WHERE category_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
if( mysql_num_rows( $query ) > 0 ) {
$sql = "SELECT * FROM project_category WHERE parent_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
if( mysql_num_rows( $query ) > 0 ) {
while( $row = mysql_fetch_assoc( $query ) ) {
$this->DeleteProjectPhotos( $row['category_id'] );
}
} else {
$sql = "DELETE FROM project_category WHERE category_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
}
}
}
But I think the whole logic here is wrong because when I try to delete the category_id 33, everything won't be deleted. Kindly teach me how to do this one.
Your help would be greatly appreciated and rewarded!
Thanks! :)
<?php
$catID = $_GET['catID'];
deleteCategory($catID);
function connect(){
$host = 'localhost';
$dbName = 'sony';
$userName = 'root';
$password = '';
$conn = new PDO("mysql:host=$host;dbname=$dbName",$userName,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $conn;
}
$stmt = '';
function deleteCategory($catID){
$conn = connect();
$tableName = 'childparent';
$sql = "select catID from $tableName where parentID = :catID";
global $stmt;
$stmt = $conn->prepare($sql);
$idsToDelete = getChilds($catID);
$idsToDelete[] = $catID;
//print_r($idsToDelete);
$delExp = '';
foreach($idsToDelete as $id)
$delExp .= " catID=$id or";
$delExp = preg_replace('/or$/','',$delExp);
if($delExp != ''){
$delSql = "delete from $tableName where $delExp";
//echo $delSql;
$delStmt = $conn->prepare($delSql);
$delStmt->execute();
}
}
$collectedIDs = array();
function getChilds($catID){
global $stmt,$collectedIDs;
$stmt->bindValue(':catID',$catID);
$stmt->execute();
$childCatIDs = array();
while($row = $stmt->fetch(pdo::FETCH_ASSOC)){
$childCatIDs[] = $row['catID'];
$collectedIDs[] = $row['catID'];
}
//print_r($childCatIDs);
//die();
if(!empty($childCatIDs)){
foreach($childCatIDs as $cid)
getChilds($cid);
}
return $collectedIDs;
}
?>
If you don't want triggers you can try http://php.net/manual/en/function.mysql-affected-rows.php on delete category you get it`s id and while there is a return you try to delete by cathegory or by parent
I am trying to pass multiple variables in a URL in PHP to GET some info, but I don't think it's working.
$allowedFunctions = array(
'returnAllProducts',
'refreshCurrentProduct'
);
$IDNUM = $_GET[ 'idNum' ];
$functionName = $_GET[ 'func' ];
if( in_array( $functionName, $allowedFunctions ) && function_exists( $functionName ) )
{
$functionName();
}
Then I have the refreshCurrentProduct function:
function refreshCurrentProduct() {
$dbh=mysql_connect ("DATABASE","USER", "PASS") or die('I cannot connect to the database because:'. mysql_error());
mysql_select_db("TABLE");
$query = "SELECT `ID` FROM `PRODUCTS`";
$result = mysql_query($query) or die('Query failed:'.mysql_error());
$DB_STOCK = mysql_query("SELECT `STOCK` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_SHORT = mysql_query("SELECT `MYNAME` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_LONG = mysql_query("SELECT `DESCRIPTION` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_PRICE = mysql_query("SELECT `PRICE` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_SHIP = mysql_query("SELECT `SHIPPING` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$ID = mysql_result($result,$IDNUM,"ID");
$STOCK = mysql_result($DB_STOCK,$IDNUM,"STOCK");
$SHORT = mysql_result($DB_SHORT,$IDNUM,"MYNAME");
$LONG = mysql_result($DB_LONG,$IDNUM,"DESCRIPTION");
$PRICE = mysql_result($DB_PRICE,$IDNUM,"PRICE");
$SHIP = mysql_result($DB_SHIP,$IDNUM,"SHIPPING");
echo '
//echo $STOCK, $SHORT, etc....
';
}
The URL I am using is products.php?func=refreshCurrentProduct&idNum=4
In theory, that should display from the row with 4 in it, however, it only displays the info from the first row. If I do a $IDNUM=5 within the function, it will display the 5th row, so something is wrong with how I pass the information.
Also, how do I create (for instance) $STOCK without having to have so much code in $DB_STOCK? Seems like there has to be a better way...
Why don't you do (as others already mentioned , $IDNUM is not in the scope of the function):
function refreshCurrentProduct() {
$dbh=mysql_connect ("DATABASE","USER", "PASS") or die('I cannot connect to the database because:'. mysql_error());
mysql_select_db("TABLE");
// If $_GET['idNum'] is not a number use 0
$rowNumber = is_numeric($_GET['idNum']) ? $_GET['idNum'] : 0;
$query = "SELECT ID, STOCK, MYNAME, DESCRIPTION, PRICE, SHIPPING FROM `PRODUCTS`";
$result = mysql_query($query);
if(mysql_data_seek($result, $rowNumber)) {
// The result set has indeed at least $rowNumber rows
$row = mysql_fetch_assoc($result);
echo $row['ID'];
echo $row['STOCK'];
// ... etc ....
}
else {
echo "No such row!";
}
}
No need to hit the database six times! Of course you need to add error handling.
Btw. is the parameter idNum the same as the ID of the record in the database? If so, you can even further simplify:
function refreshCurrentProduct() {
$dbh=mysql_connect ("DATABASE","USER", "PASS") or die('I cannot connect to the database because:'. mysql_error());
mysql_select_db("TABLE");
// If $_GET['idNum'] is not a number use 0
$id = is_numeric($_GET['idNum']) ? $_GET['idNum'] : 0;
$query = "SELECT ID, STOCK, MYNAME, DESCRIPTION, PRICE, SHIPPING FROM `PRODUCTS` WHERE ID = $id";
$result = mysql_query($query);
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print";
return;
}
$row = mysql_fetch_assoc($result);
echo $row['ID'];
echo $row['STOCK'];
// ... etc ....
}
Take a look at call_user_func.
$functionName = $_GET[ 'func' ];
if( in_array( $functionName, $allowedFunctions ) && function_exists( $functionName ) )
{
call_user_func($functionName);
}
Also, if I'm reading your code right, you could get all of the info in a single query:
$query = "SELECT `ID`,`STOCK`,`MYNAME`,`DESCRIPTION`,`PRICE`,`SHIPPING` FROM `PRODUCTS`";
$result = mysql_query($query) or die('Query failed:'.mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$ID=$row['ID'];
//etc.
}
Your $IDNUM variable is outside the scope of your function. You either need to pass that into your function as a variable or you should be able to set it within the function by setting it inside.
function refreshCurrentProduct() {
$IDNUM = $_GET[ 'idNum' ];
...
}