Exchanging unique strings to integers - php

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);

Related

How do I store the results of the for loop as an array in the res variable?

I want to store the results of the for loop as an array in the variable
$res. How do I do it?
<?php
$servername = "localhost";
$username = "root";
$password = "";
$name = "abc";
$con = new mysqli ($servername, $username, $password, $name);
$sql1 = $con->query("SELECT (status) FROM `seita`");
$i = $sql1->num_rows;
echo $i;
for($x=1; $x<=$i; $x++)
{
echo $x;
$sql = $con->query("SELECT status FROM `seita` WHERE RollNo = '$x'");
$res = mysqli_fetch_row($sql);
}
?>
The answer given by Rohit Mittal gave me array to string conversion error. What do I do next?
You can fetch all in one query with fetch_all() of mysqli
$servername = "localhost";
$username = "root";
$password = "";
$name = "abc";
$con = new mysqli ($servername, $username, $password, $name);
$result = $con->query("SELECT status FROM `seita`")->fetch_all();
You could try to do it all in one line. Maybe something similar to this:
$res = $con->query("SELECT status
FROM `seita`
WHERE RollNo between 1 and (
SELECT count(status)
FROM `seita`
)
")->fetch_all();
You want to append to an array search google php array append which gives array_push($stack, "apple", "raspberry");
// Declare arrray
$res = []
for($x=1; $x<=$i; $x++)
{
echo $x;
$sql = $con->query("SELECT status FROM `seita` WHERE RollNo = '$x'");
// Append result to array
array_push($res, mysqli_fetch_row($sql));
}
You need to make an array and need to get only status value as below:
$res = [];
for($x=1; $x<=$i; $x++)
{
echo $x;
$sql = $con->query("SELECT status FROM `seita` WHERE RollNo = '$x'");
$statusData = mysqli_fetch_row($sql);
$res[] = $statusData['status'];
}

Simplify php code - connect to a database

Here I have a php code that connects to a database, selects a row by id and creates an associative array from this row using a while loop. Do I have to write this code over and over again to create arrays from other rows by id? Maybe there is a chance to simplify this php code somehow? Please look at my code. BTW I am new in php...
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = '_erica';
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db);
$sql1 = "SELECT * FROM pics WHERE id = 1;";
$sql2 = "SELECT * FROM pics WHERE id = 2;";
$sql3 = "SELECT * FROM pics WHERE id = 3;";
$sql4 = "SELECT * FROM pics WHERE id = 4;";
$sql5 = "SELECT * FROM pics WHERE id = 5;";
$sql6 = "SELECT * FROM pics WHERE id = 6;";
$result1 = $conn->query($sql1);
$result2 = $conn->query($sql2);
$result3 = $conn->query($sql3);
$result4 = $conn->query($sql4);
$result5 = $conn->query($sql5);
$result6 = $conn->query($sql6);
while($row1 = $result1->fetch_assoc()) {
$bcgrnd = $row1["link"];
}
while($row2 = $result2->fetch_assoc()) {
$recipes = $row2["link"];
}
while($row3 = $result3->fetch_assoc()) {
$header = $row3["link"];
}
while($row4 = $result4->fetch_assoc()) {
$menu = $row4["link"];
}
while($row5 = $result5->fetch_assoc()) {
$beauty = $row5["link"];
}
while($row6 = $result6->fetch_assoc()) {
$kids = $row6["link"];
}
?>
You can do this in one query:
$sql = "SELECT * FROM pics WHERE id IN (1,2,3,4,5,6);";
$result = $conn->query($sql);
And then you can loop over all results like this:
$data = array();
while ($row = $result->fetch_assoc()) {
$id = $row["id"];
$link = $row["link"];
$data[$id]["link"] = $link;
// add more fields if you want
}
To access for example the link of ID 1, just do:
$data[1]["link"];
You can write one or two simple functions for this. Moreover, please note that your code is vulnerable to SQL Injection. Here is an example how you can achieve this with some simple functions:
<?php
function DB() {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = '_erica';
return new mysqli($dbhost, $dbuser, $dbpass,$db);
}
function query($id) {
$query = "SELECT * FROM `pics` WHERE `id` = $id";
return DB()->query($query);
}
$result = query(1); // will fetch records for ID 1
while($row = $result->fetch_assoc()) {
$bcgrnd = $row["link"];
}
$result = query(2); // will fetch records for ID 2
while($row = $result->fetch_assoc()) {
$bcgrnd = $row["link"];
}
?>
By adapting this approach, you can fetch data for a specific ID. If you don't like this solution, consider using MySQL IN clause.
Try this.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = '_erica';
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db);
$sql = "SELECT * FROM pics WHERE id IN (1,2,3,4,5,6);";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$bcgrnd[$row["id"]][] = $row["link"];
}
?>
Why not try a Query and Limit it to 6 results, it takes up less resources just pulling 6 results:
SELECT * FROM `pics` ORDER BY `[PRIMARY KEY]` LIMIT 6
MySQL in() function finds a match in the given arguments, you can use it
select pics where id IN(1,2,3,4,5,6)

Computing sum of 2 fields in a table using MySQL fetch function in PHP

I have a table having the following fields: id(Autoincrement/Primary Key)/Integer1/Integer2/Sum/Product). I have filled integer1 and integer2 with the following code:
for ($i=1;$i<=1000;$i++)
{
$x2=rand(0,100);
$x3=rand(0,100);
$sql="INSERT INTO data(integer1,integer2) VALUES ($x2,$x3)";
$conn->query($sql);
}
I need help to prepare a function which uses MySQLFetch and computes sum of integer1 and integer2 and assigns the value in sum and product. I know it can be done using a simple loop, but would really like to get an understanding of fetching data.
Assuming you are using mysqli which is how it appears with the use of $conn->query() then this might be of interest.
/* establish db connection */
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$conn = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
/* select records to to perform sum & product upon */
$sql='select * from `data`';
$res=$conn->query( $sql );
if( $res ){
/* prepare a new sql statement to update db records */
$sql='update `data` set `sum`=?, `product`=? where `id`=?;';
$stmt=$conn->prepare( $sql );
while( $rs=$res->fetch_object() ){
/* make some variables with records for each record */
$id=$rs->id;
$int_1=$rs->integer1;
$int_2=$rs->integer2;
/* basic maths operations */
$sum=$int_1+$int_2;
$product=$int_1 * $int_2;
/* bind the variables into declared statement & execute */
$stmt->bind_param( 'iii', $sum, $product, $id );
$stmt->execute();
}
/* tidy up */
$stmt->close();
$conn->close();
}
Kindly try the following example :
$db = new mysqli('localhost', 'root', 123456, 'data');
$query = 'SELCT * FROM tableName';
$objResult = $db->query($query);
while ($resultRow = $objResult->fetch_object()) {
$id = $resultRow->id;
$integer1 = $resultRow->integer1;
$integer2 = $resultRow->integer2;
$result = sumProduct($integer1, $integer2);
$sum = $result[0];
$product = $result[1];
$query = "UPDATE tableName SET
sum = '$sum',
product = '$product'
WHERE
id = $id";
$db->query($query);
$db->close();
}
function sumProduct($int1, $int2) {
$sum = $int1 + $int2;
$product = $int1 * $int2;
return array($sum, $product);
}
Is this way you expected?
$query = "SELECT * FROM data";
$row = mysql_query($query);
while($result = mysql_fetch_assoc($row))
{
$id = $result['id'];
$integer1 = $result['integer1'];
$integer2 = $result['integer2'];
$sum = $integer1 + $integer2;
$prod = $integer1 * $integer2;
mysql_query("UPDATE data SET sum=$sum,product=$prod WHERE id=$id");
}

select value into variable using input from form

Hi i am having an issue selecting a value form my table into a variable in the PHP so that I can calculate the cost of something
here is the code I have so far I want to be able to select a "cost" value from the table C_price where the values of I_type and a_type match
E.g. the table structure looks like this
ID=1,A_type=line,I_type=Head,cost=5
if on the form i enter line and head
i need to be able to get the value 5 in to a venerable i can use in calculations and insert into another table AKA i need to get cost into a variable somehow
the following was my try and i need help im new at all this so please help
$E_C;
$T_cost = "1";
$date = date("d.m.y");
$name = $_POST["from"];
$email = $_POST["email"];
$ref = $_POST["link"];
$i_type = $_POST["i_type"];
$a_type = $_POST["a_type"];
$extra = $_POST["extra"];
$des = $_POST["description"];
$BG = $_POST["BG"];
$bg_type = $_POST["BGtype"];
$msg = $_POST["message"];
$auto_reply = ("thanks for the email we will get back to you as soon as we can about the cost and how you can pay");
$msg = wordwrap($msg, 70);
$host = "localhost";// hostname
$USER = "root";// username
$PASS = "Password";// password
$DBNAME = "andrea";// databace name
$tbl_name = "c_price";// table name
$con = mysqli_connect("localhost", $USER, $PASS, $DBNAME)or die("mySQL server connection failed");
$all = "SELECT cost FROM C_price WHERE a_type=$a_type,i_type=$i_type";
$result = mysqli_query($con,$all) or die("Error getting total storse");
while($row = mysqli_fetch_array($result))
{
echo $row['cost'];
}
if ($a_type = 'waist' && $extra='Y')
{
$E_C = $cost * .3;
}
elseif ($a_type = 'knee' && $extra='Y')
{
$E_C = $cost * .35;
}
elseif ($a_type ='full' && $extra='Y')
{
$E_C = $cost * .4;
}
else
{
$E_C = 0;
}
$T_cost = $cost + $E_C;
if ($BG = 'y')
{
$T_cost = $T_cost + 10;
}
You can't use mysqli and mysql at a same time.. Mysqli is a class... So first change that things...
while($row = mysqli_fetch_array($result))
{
echo $row['cost'];
}
$news1 = mysqli_result($result, 0); // 0 is the index of the field, not the row
echo $news1;
echo $cost;`
Query should be like this...
$all = "SELECT cost FROM C_price WHERE a_type='$a_type'and i_type='$i_type'";
You cant mix mysql and mysqli
change this line In the while loop and add for error mysqli_error
$news1 = mysql_result($result, 0);
$news1 = mysqli_result($result) or die(mysqli_error());
and your query is wrong as well and A_type is not same as A_type and same goes for I_type as well
$all = "SELECT cost FROM C_price WHERE a_type=$a_type,i_type=$i_type";
//Change it to
$all = "SELECT cost FROM C_price WHERE A_type='$a_type'and I_type='$i_type'";
//and A_type is not same as a_type and same goes for I_type as well

Casting Issue with PHP MYSQL Combination

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];

Categories