Casting Issue with PHP MYSQL Combination - php

I think I have a problem with casting.
$db = mysqli_connect('127.0.0.1','root','password','test');
if (! $db) { die("Can't connect: " . mysqli_connect_error( )); }
$new_table = $_POST["newtablename"];
$old_table = $_POST["oldtablename"];
$numberRows = $_POST["numberrows"];
$startRow = $_POST["startrow"];
$counter = 0;
drop_table($db, $new_table);
create_table($db, $new_table);
for($counter = 0; $counter < $numberRows; $counter += 1)
{
$currentRow = getRow($db, $old_table);
$ID = $currentRow(1);
$Partner = $currentRow(2);
$Merchant = $currentRow(3);
}
function getRow($db, $old_table)
{
$select = "SELECT ID, Partner, Merchant FROM " .$old_table;
$q = mysqli_query($db, $select);
$row = mysqli_fetch_row($q);
return $row;
}
function create_table($db, $new_table){
$create = "CREATE TABLE " .$new_table. "(ID INT, Partner VARCHAR(20), Merchant VARCHAR(30))";
$q = mysqli_query($db, $create);
}
function drop_table($db,$new_table){
$drop = "DROP TABLE IF EXISTS " .$new_table;
$q = mysqli_query($db, $drop);
}
This is the error I get
Fatal error: Function name must be a string in C:\xampp\htdocs\myfiles\mysqli_combined_functions.php on line 26
Line 26 is where I set $ID = $currentRow(1). I am under the impression that the row will be returned as an array of variables, and using the proper number I can access the variable I want. Assuming thats true (let me know if its not) then I think it is reading the ID in the form of an INT which is what it is in the SQL table I have. Can someone help me cast it into string? or perhaps I'm missing the problem completely?

You use square brackets to access elements of arrays.
$currentRow[1]
Remember the first index will be 0 also.

Not casting. These are array indexes, note the square brackets. [ ]
$currentRow = getRow($db, $old_table);
$ID = $currentRow[1];
$Partner = $currentRow[2];
$Merchant = $currentRow[3];

Related

Output multiple values from PHP function

I have created the following function to fetch data from my database, but its capabilities are limited. Currently it can fetch one value at a time, which is fine for fetching the value of one column of one row, but as I progress with my work, I now want to be able to fetch multiple values in one call.
The Function:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data[$value];
}
mysqli_close($connection);
}
How I currently use it to fetch multiple values:
// Define variables
$x1 = retrieve("x1");
$x2 = retrieve("x2");
$x3 = retrieve("x3");
$x4 = retrieve("x4");
$x5 = retrieve("x5");
$x6 = retrieve("x6");
$x7 = retrieve("x7");
$x7 = retrieve("x8");
I have read other questions here on Stack Overflow, but none of them solves my problem as I use an optional parameter, which makes my life hard. For example, I thought of implementing the splat operator to allow unlimited parameters, but as I use the optional parameter $identifier, I can't make it into something like:
function retrieve($identifier = null, ...$value) {}
because it will use the first parameter as the identifier when I omit it.
I'm sure that regarding performance it would be better if I could fetch all the necessary values in one call of the function retrieve() instead of using it as shown above and that's why I would like to know:
How can I edit this function in order to fetch more values at once?
Calling it like so:
$x = retrieve($y);
$x1 = $y["x1"];
$x2 = $y["x2"];
...
EDIT:
Thanks to Manish Jesani for his help! I used his answer and modified to do exactly what I want. For anyone that may be interested in the future, here's the code:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$values = array();
$identifier = (is_null($identifier)) ? "`ID` = '1'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if (is_array($value)) {
foreach($value as $_value) {
$values[$_value] = $data[$_value];
}
return $values;
}
else {
return $data[$value];
}
}
mysqli_close($connection);
}
You can call the function with as many parameters you want. Τo do this you have to use func_num_args() to get all of them, as shown below:
function retrieve() {
$args = func_num_args();
$query = "SELECT '".implode("','", func_get_args())."' FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data;
}
mysqli_close($connection);
}
You can call this function like this: $params = retrieve('x1','x2','x3').
Alternatively, you can retrieve them as variables list($x1, $x2, $x3) = retrieve('x1','x2','x3').
Please try this:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$return = array();
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if(is_array($value))
{
foreach($value as $_value)
{
$return[$_value] = $data[$_value];
}
}
else
{
$return[$value] = $data[$value];
}
return $return;
}
mysqli_close($connection);
}
$x = retrieve(array("x1","x2","x3","x4","x5","x6"));

Exchanging unique strings to integers

Ok, so the issue I am having is I am returning the count of the number of l's and d's from a database as a string, but I need it to be an integer. I tried to cast it as an int after but when i do it just returns each number as 0. I know it is returning a string, and when I echo $count1 (which is the string) it returns the actual number just find, but when I cast it, it doesn't work.
By the way there is a ton of entries and each one is unique, so the basic rundown is like
12
10
9
when I return it as a string but when I return it as an int it is
0
0
0
$db_name = '';
$db_user = '';
$db_pass = '';
$db_host = '';
try{
// database connection
$db = new PDO("mysql:host=$db_host;dbname=$db_name",$db_user,$db_pass);
}
catch(PDOException $pe)
{
die('Connection error, because: ' .$pe->getMessage());
}
$table = 'ratings';
$con = 'data';
$id = (empty($_GET['id'])) ? : $_GET['id'] ;
$sql5 = $db->prepare("SELECT COUNT(rating) FROM $table WHERE id='$id' AND rating = 'l'");
$sql5->execute();
$count = $sql5->fetchColumn();
$sql = $db->prepare("SELECT COUNT(rating) FROM $table WHERE id='$id' AND rating = 'd'");
$sql->execute();
$count1 = $sql->fetchColumn();
$plsWerk = (int)$count1;
var_dump($plsWerk);
var_dump($count1);
$qq = "SELECT * FROM $con";
$stmt1 = $db->prepare($qq);
$stmt1->execute();
$rr = $stmt1->fetch(PDO::FETCH_ASSOC);
$ip = $_SERVER["REMOTE_ADDR"];
echo $count1;
I am not currently echoing plswerk but that is what I want to replace count1.
Thanks!
You should try $foo = intval('33'); rather than $foo = (int)('33');
So:
$plsWerk = intval($count1);

automatically get all sql table values

I have a query which returns a row with over 20 values
TableTest
Country
User
Name
...
...
If I want to create an object in PHP for each value in the table how can I do that?
I currently do like this.
$generalValues = new stdClass();
$IdQuery = $this->m_queryFactory->getIdFromBuild($id, $pc);
$result = odbc_exec($this->m_connection, $IdQuery);
$no_results = odbc_num_rows($result);
for ($i = 0; $i < $no_results; $i++) {
$Id = trim(odbc_result($result, "Id"));
$query = $this->m_queryFactory->getQuery($Id);
$result = odbc_exec($this->m_connection, $query);
if (odbc_num_rows($result) > 0) {
odbc_fetch_row($result);
$generalValues->Country = odbc_result($result, "country");
$generalValues->Name = odbc_result($result, "name");
$generalValues->User = odbc_result($result, "user");
...
...
}
}
But how can I do it for every value in the table row whitout having to specify every table column value?
Thanks in advance.
$result = odbc_exec($this->m_connection, $query);
$generalValues = odbc_fetch_object($result);
http://php.net/manual/en/function.odbc-fetch-object.php

Why won't this loop variable increment?

I'm trying to write code that will count the number of users returned by a sqlite query and then split a 'bill' between those users, but for some reason my counter won't increment and I am getting a division by zero error. My code is here:
<?php
session_start();
require 'database.php';
$db = new Database();
$name = $_POST['name'];
$amount = $_POST['amount'];
$due = $_POST['due'];
$gid = $_GET['gid'];
$uid = $_SESSION['id'];
$count = 0;
$users = $db->query("select * from members where(gid='$gid');");
while($data = $users->fetchArray()) {
$count++;
}
$amount = $amount / $count;
while($data = $users->fetchArray()) {
if($data['uid'] == $uid) {
continue;
} else {
$temp = $data['uid'];
$db->exec("insert into bills values(NULL,'$gid','$uid','$temp','$amount','$due','false','$name');");
}
}
header('Location:grouppage.php?gid='.$gid.'');
?>
Anyone have any ideas on how to fix this?
Regardless of the loop not seeming to work, you can't have two while(... fetchArray()) loops without something resetting the internal pointer.
In this case, however, you don't need that:
$users = $db->query("select * from members where(gid='$gid')");
$count = $users->numRows();
if( $count == 0) die("No users found!");
$amount /= $count;
while($data = $users->fetchArray()) {
...
}
You don't handle case, when select doesn't return any record.
Just look at your code:
$users = $db->query("select * from members where(gid='$gid');");
while($data = $users->fetchArray()) {
$count++;
}
No data selected -- no while-body
executed, $count not incremented and left zero, with "divide by zero" error in following line as consequence.
$amount = $amount / $count;

How to 'append' function variables using the URL and a question about Array's

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.

Categories