automatically get all sql table values - php

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

Related

database query, compare each two rows but getting only first two rows

Hi i am querying my db so that i can compare every two rows. ex 1 and 2, then 2 and 3, then 3 and 4. and so on and so forth. but it only compares the first two rows. any ideas? here is my code:
$result = mysql_query("SELECT *FROM attendance ORDER BY pid ASC") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// $response["nominees"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$prev_sid = $row["sid"];
$prev_pid = $row["pid"];
$row2 = mysql_fetch_array($result);
if($row2["pid"] == $prev_pid){
if(($row2["sid"] - $prev_sid) == 1){
$attended_elec = mysql_query("SELECT pid FROM election_attendance where election_id = '$election_id'");
if(mysql_num_rows($attended_elec) > 0){
$not_officer = mysql_query("SELECT usertype FROM users WHERE pid = '$prev_pid'");
if(mysql_result($not_officer, 0) == "member"){
// echo "PID" . $prev_pid;
// $nominee["pid"] = $row2["pid"];
$user_details = mysql_query("SELECT *FROM users WHERE pid = '$prev_pid'");
if(mysql_num_rows($user_details) > 0){
$response["nominees"] = array();
while ($row3 = mysql_fetch_array($user_details)) {
$nominee = array();
$nominee["pid"] = $row3["pid"];
$nominee["firstname"] = $row3["firstname"];
$nominee["lastname"] = $row3["lastname"];
$nominee["gender"] = $row3["gender"];
$nominee["contact"] = $row3["contact"];
$nominee["email"] = $row3["email"];
$nominee["address"] = $row3["address"];
$nominee["institution"] = $row3["institution"];
$nominee["points"] = $row3["points"];
$nominee["usertype"] = $row3["usertype"];
// push single product into final response array
array_push($response["nominees"], $nominee);
}
}
}
}
}
}
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "There is no candidate yet from the records.";
// echo no users JSON
echo json_encode($response);
}
thanks in advance, have a nice day
Theres a problem right at the while(), you're fetching the 1st row, and is correct.
Then, inside it you fetch the 2nd, which is what you intend, but when the iteration is repeating, the while will fetch the 3rd, and the inner the 4th, so you lost there the comparisson between 2nd and 3rd.
// fetch data from DB
$results = "...";
if (mysql_num_rows($result) < 1)
{
// no products found tell your users
return;
}
// lets make some variables to walk through the list
$previous = mysql_fetch_array($results);
$actual = null;
// and now lets walk through the list
while($actual = mysql_fetch_array($results))
{
// execute your logic here
// than at the end move the actual row to become the previous
$previous = $actual;
}
NOTICE you shouldn't use mysql_ * methods they're are deprecated. you can use the brother mysqli_ * or PDO
I would do something like this? But there is almost certainly a less resource intensive way to do it.
$x = 0;
$y = 1;
$total = mysql_num_rows(mysql_query("SELECT * FROM `the_place`");
while ($x < $total AND $y < total){
$query1 = "SELECT * FROM `the_place` LIMIT $x,1";
$query2 = "SELECT * FROM `the_place` LIMIT $y,1";
$row1 = mysql_fetch_array(mysql_query($query1);
$row2 = mysql_fetch_array(mysql_query($query2);
// Do comparison here
if ($row1 == $row2){
// etc
}
$x = $x++;
$y = $y++;
}

$i not incrementing in while loop

Following is my PHP code which is only giving i =0 though in a loop I am incrementing the $i but it always return i as 0 and while loop is only working one time, though my query SELECT * FROM events WHERE DATE(event_date) < CURDATE() is returning 7 records when exectuing in phpmyadmin. Let me know what i am doing wrong here ?
Code -
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/app/'."config.php";
error_reporting(E_ALL);
if( $_POST['number'] == 'all' ) {
$eventArr = array();
$myarray = array();
$query = "SELECT * FROM events WHERE DATE(`event_date`) < CURDATE()";
$result = mysql_query($query);
$i =0;
while($row = mysql_fetch_assoc($result)) {
$eventArr[$i] = array('event_data'=> $row);
// Get image For an event
$event_id = $row['id'];
$query = "SELECT * FROM event_images WHERE event_id = $event_id ORDER BY `uploaded_date` DESC LIMIT 0,1";
$result = mysql_query($query);
$eventImgArr = array();
while($row = mysql_fetch_assoc($result)) {
$eventImgArr[] = $row;
}
$eventArr[$i]['event_image'] = $eventImgArr;
// Get venue details for the event
$venue_id = $row['venue_id'];
$eventVenArr = array();
$query = "SELECT * FROM `venues` WHERE id = $venue_id";
while($row = mysql_fetch_assoc($result)) {
$eventVenArr[] = $row;
}
$eventArr[$i]['venue_detail'] = $eventVenArr;
echo $i, " -- ";
$i++;
}
$myarray = array('response'=>'1','message'=>'Event data', 'data'=>$eventArr);
echo json_encode($myarray);
return;
}
You are re-using the $result variable for the other queries, which is destroying its value needed for the main loop.
P.S. Also, you're not actually executing the query for the venue details.

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

Dynamic Update MySql Table

I am attempting to Dynamically update a MySql table, the $query looks correct when i echo it, but for some reason it dose not work when i insert the code into the MySql Query.
$b = 1;
$query_a = array();
$vars = array();
$result = mysql_query("SELECT * FROM my_table");
for ($i = 0; $i < mysql_num_fields($result); $i++) {
$vars[] = mysql_field_name($result,$b);
$b++;
}
foreach ($vars as $v)
{
if (isset($_GET[$v]))
{
$isclean = $_GET[$v];
$query[] = $v.' = '.$isclean.'';
}
}
$query = implode(',', $query);
mysql_query("UPDATE my_table SET $query WHERE UIN = '1'");
Without knowing your data types, my guess is it's because you're not adding single quotes around your values. You probably want something like:
$query[] = $v.' = \''.$isclean.'\'';

How do I add data from two tables in mySQL and PHP?

I have a table with two fields, named credithour and gradepoint.
I want to add the data from each row of credithour with gradepoint.
My code :
$totalcredithour = 0;
$GPA = "SELECT * FROM $dept_stu_id WHERE sessionyear = '$sessionyear'" or die (mysql_error());
$resultGPA = mysql_query($GPA);
while($data = mysql_fetch_array($resultGPA))
{
$credithour = "$data[credithour]";
$gradepoint = "$data[gradepoint]";
echo $totalcredithour += $credithour;
}
What am I doing wrong?
It added data, but showing the first credit hour also besides result.
Suppose, here i entered two data 3 and 5. When I run this code it echo 38. Which means "3+5=8" and 1st credithour = "3".
Actually other answer are wrong, you're doing or die(mysql_error()); next to a string, that's not right.
Your code should be like this..
$totalcredithour = 0;
$GPA = "SELECT * FROM `".$dept_stu_id."` WHERE sessionyear = `".$sessionyear."` ";
$resultGPA = mysql_query($GPA) or die(mysql_error());
while($data = mysql_fetch_array($resultGPA, MYSQL_ASSOC))
{
$credithour = $data['credithour'];
$gradepoint = $data['gradepoint'];
echo $totalcredithour += $credithour; //Make sure `$totalcredithot` isn't null/doesn't exist.
}
try something like this in your while loop:
$credithour = $data['credithour'];
$gradepoint = $data['gradepoint'];
Try it like this
I have edited the answer and added the floatval function
$totalcredithour = 0;
$GPA = "SELECT * FROM `".$dept_stu_id."` WHERE sessionyear = '".$sessionyear."'" or die (mysql_error());
$resultGPA = mysql_query($GPA);
while($data = mysql_fetch_array($resultGPA))
{
$credithour = $data['credithour'];
$gradepoint = $data['gradepoint'];
echo $totalcredithour += floatval($credithour);
}

Categories