Quantcast
Channel: PHP Freaks: PHP Help
Viewing all 13200 articles
Browse latest View live

Variable Passing Dynamically To Series of Pages

$
0
0

Hii,

 

I created a view with few selected data from table. I provided link to title to have redirection on editing page. I am passing variables to dynamic editing page. In editing page, I created a form which is filled automatically using id. Now on submission of updated form I redirected it to another php page for back-end processing. But now I am not getting data of inputs from editing page. POST and GET both are not working. I don't understand why is it not passing values.

 

Login ► View Data ► Select Data To Update ► Update Is not working here 


Query table and return sub-arrays

$
0
0

Given the following query,

SELECT t1.a, t1.b, t2.c FROM t1 INNER JOIN t2 ON t2.id=t1.t2_id WHERE t1.pk=123;

I get the following three records:

array(
  array('a'=>1,'b'=>2,'c'=>4),
  array('a'=>1,'b'=>2,'c'=>5),
  array('a'=>1,'b'=>2,'c'=>8)
)

What would be the best way to get just one record such as the following?

array('a'=>1,'b'=>2, 'c'=>array(4,5,8))

My thoughts were to use MySQL's GROUP_CONCAT, and then use implode() to turn it into an array, but didn't know if there was a better way.

 

Thanks

Needles, haystacks, and arrays

$
0
0

I have the following mapping array:

 

array(
  array('name'=>'nothing','options'=>array()),
  array('name'=>'aaa','options'=>array('a')),

  array('name'=>'bbb','options'=>array('b')),

  array('name'=>'ccc','options'=>array('c')),

  array('name'=>'aaa and bbb','options'=>array('a','b')),

  array('name'=>'aaa and ccc','options'=>array('a','c')),

  array('name'=>'bbb and ccc','options'=>array('b','c')),

  array('name'=>'aaa, bbb, and ccc','options'=>array('a','b','c'))
)

 

 

Given array(), I would like to return 'nothing', given array('c'), I would like to return 'ccc', given array('b','c'), I would like to return 'bbb and ccc', given array('a','b','c'), I would like to return 'aaa, bbb, and ccc', etc.  How is this best accomplished?

 

As an alternate solution, instead of being given the above arrays, I could be given the following strings "", "c", "b~c", "a~b~c" and I can change the above mapping array to include these strings instead of the arrays I show.   Please reference http://forums.phpfreaks.com/topic/292921-query-table-and-return-sub-arrays/ for history.  Would this be a better approach?  How would I ensure the order of the JOINed values were always in the correct order for my mapping array?

Set Password Script is not working

$
0
0

here is my change password script (This is being done by the admin) 

<?php

error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');

require 'connect.php';

if(isset($_POST['change'])) {

	$newp = trim($_POST['npass']);
	$confp = trim($_POST['cpass']);

	if(empty(trim($newp))) {

		echo "<h3><center>You did not enter a new password!</center></h3>";

		exit();

	} if(empty(trim($confp))) {

		echo "<h3><center>You must confirm the password!</center></h3>";

		exit();

	} if($confp !== $newp) {

		echo "Passwords do not match!, try again.";
	} else {

		$sql = "UPDATE $db_name SET cpass='$password' WHERE id=' ".$row['id']." '";

		echo " ".$row['username']."\s password has been reset! ";
	}
}

?>

<html><title>  Change password  </title><head><style>#form {border-radius: 20px;font-family: sans-serif; margin-top: 60px; padding: 30px;background-color: #aaa;margin-left: auto; margin-right: auto; width: 500px; clear: both;} #form input {width: 100%; clear: both;} #form input:hover {border: 1px solid #ff0000;}</style></head>
<body>
<div id="form">
	<form action='' method='POST'>
	<h2><b><center>Change Password</center></b></h2><br>
	<tr>
	<td><b>New password:</b><input type="password" name="npass" placeholder="Enter new password" /></td><br><br>
	<td><b>Confirm password:</b><input type="password" name="cpass" placeholder="Confirm password" /></td><br><br>
	<td><input type="submit" name="change" value="Change!" /></td>
</tr>
</form>
</div><!-- end of form div -->
</body>
</html>

I'm getting 

Notice: Undefined variable: row in C:\xampp\htdocs\Login\web_dir\changepassword.php on line 30

Notice: Undefined variable: row in C:\xampp\htdocs\Login\web_dir\changepassword.php on line 32

And it say's 

\s password has been reset!

It's saying that the variable row is undefined, it's defined in my edit user / select user page 

<?php

error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');

session_start();

require 'connect.php';

echo "<title>  Edit a user  </title>";

$sql = "SELECT id, username FROM $tbl_name ORDER BY username";
$result = $con->query($sql);
while ($row = $result->fetch_assoc())
{
   	echo "<div id='l'><tr><td>{$row['username']}</td> |
        <td><a href='editUser.php?id={$row['id']}'>Edit User</a> |</td>
        <td><a href='changepassword.php?id={$row['id']}'>Change Password</a> |</td>
        <td><a href='banUser.php?id={$row['id']}'>Ban User</a></td><br><br>
        </tr></div>\n";
}


?>

Also it doesn't actually UPDATE the password.

How to specify the size of entry fields ?

$
0
0

I'm not sure if the window often seen being filled out, such as this one that I am writing into is php. 

 

I'm looking for a window that will auto-size or has the ability to be expanded on demand like this window with the three lines on the bottom right corner.

 

Or to specify a size based on page properties like proportions or what is supposed to be typed into the field eg. character limit. 

 

Is that php? 

 

I'd be happy with a link of documentation or anything

Otherwise, currently I only have the basic fields that come up when using POST and GET

Thank you

Data is not inserted to database after submit

$
0
0

Hello everyone.

 

It seems like my code is not working properly. 

 

i have tried both mysqli and PDO to insert data into database,but it only takes me back to same page again,without doing nothing in the database (been checking this a few times to be sure).

 

both php and html code are on the same page.

 

Could anyone point me to the missing link in my code?

 

here's my code (HTML & PHP) :

<form action="" id="SignUpForm" autocomplete="on" style="display:none" method="post"> <!-- Form is Hidden until the user is clicking the "Sign Up" button. -->
<input type="hidden" name="Language" value="English">
Fill up the following fields:<br><br>
First name:<input type="text" name="fname" required><br><br>
Last name: <input type="text" name="lname" required><br><br>
Age: <input type="number" name="UserAge" min="1" max="120" required><br><br>
Gender: <input type="radio" name="Gender" value="male">Male<br>
<input type="radio" name="Gender" value="Female">Female<br>
E-mail Address: <input type="email" name="email" autocomplete="off" required><br><br>
Pick your new password: <input type="password"  maxlength=”40” name="Password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"> Add password strength checker here.<br><br> <!-- Uses regular expression. -->
Confirm Password:  <input type="password" maxlength=”40” name="ConfirmPassword" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"><br><br> <!-- A better way is to use onblur to check user's type match. -->
 <hr>
 <script>
 (function(){
        $("#submit").click(function(){
        $(".error").hide(); //Bind an event handler to the "error" JavaScript event.
        var hasError = false;
        var passwordVal = $("#Password").val();
        var checkVal = $("#ConfirmPassword").val();
        if (passwordVal == '') {
            $("#Password").after('<span class="error">Please enter a password.</span>');
            hasError = true;
        } else if (checkVal == '') {
            $("#ConfirmPassword").after('<span class="error">Please re-enter your password.</span>');
            hasError = true;
        } else if (passwordVal != checkVal ) {
            $("#ConfirmPassword").after('<span class="error">Passwords do not match.</span>');
            hasError = true;
        }
        if(hasError == true) {return false;}
    });
});
 </script>
 
<script>
//The validationMessage property of a DOM node contains the message the browser displays to the user when a node's validity is checked and fails.
document.getElementById("name").validationMessage;
document.getElementById("lname").validationMessage;
document.getElementById("UserAge").validationMessage;
document.getElementById("Gender").validationMessage;
document.getElementById("email").validationMessage;
document.getElementById("Password").validationMessage;
document.getElementById("ConfirmPassword").validationMessage;
</script>

Now let's go through your prefered food. Check the appropriate boxed beyond.<br><br>
This will help us to better understand your food discipline:<br>

<p style="text-align:center"><b> Meat And Poultry:</b></p>
<div id="MeatCheckBox">
<input type="checkbox" name="FoodTypes[]" value="Hamburger">Hamburger<br>
<input type="checkbox" name="FoodTypes[]" value="Steak">Steak<br>
<input type="checkbox" name="FoodTypes[]" value="GroundBeef">Ground Beef<br>
<input type="checkbox" name="FoodTypes[]" value="Bacon">Bacon<br>
<input type="checkbox" name="FoodTypes[]" value="Beef">Beef<br>
<input type="checkbox" name="FoodTypes[]" value="Salami">Salami<br>
<input type="checkbox" name="FoodTypes[]" value="Chicken">Chicken (In all its forms)<br>
<input type="checkbox" name="FoodTypes[]" value="NoMeat">I don't eat meat at all (Vegeterian/Vegan)<br>

</div>
 <p style="text-align:center"><b> Fish And Seafood:</b></p>
 <div id="FishAndSeaFood">
 <input type="checkbox" name="FoodTypes[]" value="Fish">Fish<br>
 <input type="checkbox" name="FoodTypes[]" value="Sushi">Sushi<br>
  <input type="checkbox" name="FoodTypes[]" value="CannedFish">Canned Fish<br>
  <input type="checkbox" name="FoodTypes[]" value="Oysters">Seafood<br>
    <input type="checkbox" name="FoodTypes[]" value="SmokedSalmon">Smoked Salmon<br>
  </div>
 
 <div id="Vegetables">
 <p style="text-align:center"><b> Do you eat vegtables?</b></p><br>
 <input type="radio" name="YesOrNo" value="Yes">Yes <!-- Give both options the same name,Because they are related. -->
<input type="radio" name="YesOrNo" value="No">No<br>
 </div>
 <hr>
 

<p>Do you workout as part of your lifestyle?</p><br>
<input type="radio" name='workout_options' value='valuable' data-id="DoWorkout" class="workout_options" /> I do workout occasionally
<input type="radio" name='workout_options' value='valuable' data-id="DoNotWorkout" class="workout_options" /> I am not working out<br><br><br>
<section>
    <div id=DoWorkout class="workout_options"><p>We see you're not having any exercise at the moment.<br><br>Did you know that doing some kind of activity like running or cardio 3 times a week improve your life quality?<br><br>We'll help you go straight from zero to hero!</p></div>
    <div id=DoNotWorkout class="workout_options">What type of workout you're working on at the moment? Please choose from the options beyond:<br><br><br>
    
    <input type="checkbox" name="Cardio" value="Cardio" data-id="Cardio"/>Cardio/Aerobics<br><br> 
    <input type="checkbox" name=" Weight_Lifting" value=" Weight_Lifting" data-id="Weight_Lifting"/>Weight Lifting/ Anaerobics</div><br>
</section>

<input type="submit" value="Sign Up!" id="submit">

</div>
</form>

PHP/PDO:

<?php
// connnecting to MYSQL with PDO.

// Connection data (server_address, database, username, password)
$hostdb = 'localhost';
$namedb = 'caf_users';
$userdb = 'root';
$passdb = 'mypassword';

if (isset($_POST['SignUpButton'])) {

$yesOrNo=$_POST["YesOrNo"];
$firstName=$_POST["fname"];
$lastName=$_POST["lname"];
$userGender=$_POST["Gender"];
$emailAddress=$_POST["email"];
//check if user entered the exact password twice.
if ($_POST["password"] === $_POST["confirm_password"]) {
	$password=$_POST["password"];
	$hash = password_hash($passwod, PASSWORD_DEFAULT);}
	// The first parameter is the password string that needs to be hashed,
	//and the second parameter specifies the algorithm that should be used for generating the hash.
	//encrypted by bcrypt algorithm.
	else {
		echo "Passwords are mismatched. Please try again.";
	};
	$userAge=$_POST["UserAge"];
// Display message if successfully connect, otherwise retains and outputs the potential error
try {
	$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb); //Initiate connection witht the PDO object instance.
	$conn->exec("SET CHARACTER SET utf8");  // Sets encoding UTF-8
	echo 'Connected to database';

	// Define an insert query
	$sql = "INSERT INTO `users` ('Workout','first_name','last_name','gender','Email_Address','Password','User_Age')
	VALUES
	($YesOrno,$fname,$lname,$Gender,$email,$password,$UserAge)";
	$count = $conn->exec($sql);

	$conn = null;        // Disconnect
	if($count !== false) echo 'Number of rows added: '. $count;
}
catch(PDOException $e) {
	echo $e->getMessage();
}
}
	?>

Thank you in advance,

 

Osher.

What happens if two people submit at the same time?

$
0
0

I don't even know if this is physically possible due to latency, mechanical, etc... 

 

But, the way my website is planned at the moment, a person submits basic info, hits "Create account" and then is taken to a new page with that basic information and an incremented unique id, based on last unique id entry read from database. 

 

My concern is that if two people or more were making accounts within the same time frame and one person hits "Create account" before another person does, what if the wrong data is pulled? 

The unique ID I guess is the only thing being pulled, if 0, start at 1, whatever 

 

But I wonder if I can temporarily hold data between two webpages before it is stored in the database finally when all fields have been filled. 

 

Thanks for any help / ideas 

Problems with mysql and phpmyadmin

$
0
0

I have a db.php and inside it I filled out all the info needed:

<?php
define('DB_HOST', 'example.com');
define('DB_NAME', 'database_name');
define('DB_USERNAME', 'user_name');
define('DB_PASSWORD', '*******');

$odb = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME, DB_PASSWORD);
?>

My problem is with the DB_HOST, is that my direct URL to the site? for example, google.com or is it like an IP?

 


Counting rows Mysqli

$
0
0

Hi I'm using php file to retrieve the amount of records in my database, but all of a sudden I get 0 results. It worked fine a few days ago. I got PHP 5.2.* on my host. Here is the current script that I use.

Did I made a mistake somewhere?

<?php
$con=mysqli_connect("******","*****","*****","****");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT * FROM mxit";

if ($result=mysqli_query($con,$sql))
  {
 

$rowcount=mysqli_num_rows($result);
  //printf("Result set has %d rows.\n",$rowcount);

    
  // Free result set
  mysqli_free_result($result);
}

mysqli_close($con);
?>

php forum name help

$
0
0

I need to figure out how to give this input a name so when i submit it i can get the data from it.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/ui-lightness/jquery-ui.css" type="text/css" rel="stylesheet"/>
<style>
input{font-size:1.3em;}
#log{position: absolute; top: 10px; right: 10px;}
span{color:blue; text-decoration: underline; cursor: pointer;}
</style>
</head>
<body>
<div id="inputs"></div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js" type="text/javascript"></script>
<script src="jquery.googleSuggest.js" type="text/javascript"></script>
<script>
$.each("web".split(" "), function(i, v){
  var div = $("<div>").appendTo("#inputs")
    , input = $("<input>").appendTo(div)
    , span = $("<label>").text(v).appendTo(div);
  input.googleSuggest({ service: v });
});
</script>
</body>
</html>

Validation form

$
0
0

I'm trying to get validation messages to display on the same page as my login form without any PHP within my login page, is that possible? 

Object of class mysqli_result could not be converted to int

$
0
0

Hi all

 

i am using the code below, but am getting the error

 

Object of class mysqli_result could not be converted to int

 

<?php
  $sql="SELECT lng,lng_prefix FROM tbl_languages where active = 1";
  $result=mysqli_query($dbConn, $sql)or die(mysqli_error($dbConn)); //problem line
  if(mysqli_num_rows($result==1)){
      ?>

 

The code continues with what I want to happen based on the result.

 

What does the error mean and how do I fix it?

Get a value from another website?

$
0
0

This would be an example of a  page I'm referring to: http://www.curse.com/mc-mods/minecraft/railcraft#t1:other-downloads

 

I want to get the file name and compare it to another name (to see if they are the same or not). I have no idea how to access that page from my website. I'm guessing PHP would be best although if you don't think so tell me what you think would be better  (I was thinking javascript but don't think that's cross-site compatible). Is there a  PHP function to get the value of the href which is in this case (as of this posting) "Railcraft 9.4.0.0".

 

I used inspect element to see the code of the page but have no idea if this is possible or if I'm even going about this the right way. The code would have to work on this entire website (all pages have the smae layout as this one though! Any help is greatly appreciated!

 

 

Stopping an Invalid Selection

$
0
0

I am trying to stop an invalid selection (validate selection) from happening if a user modifies the source code. However,  I am unsure of how to do so. Here is my code below:

<form action="index.php" method="POST">
<?php
if (isset($_POST['course'])) {
    $course = htmlentities($course);
    //Prints if the student has been successfully enrolled into the course
    if ($success == 1) {
        echo '<font color="#12df12">You have successfully enrolled in ' . htmlspecialchars($course_name) . ' (' . htmlspecialchars($course) . ')!</font>';
    }
    //Prints if the person registering has entered data incorrectly into the form
    if ($found == 0) {
        echo '<font color="#ff0000">The credentials you have entered are incorrect, please try again.</font>';
    } else {
        //Prints if the student has already enrolled in the course
        if ($findregistered == 1) {
            $option = mysqli_query($link, "SELECT * FROM courses WHERE course_code = '$course'") or die(mysql_error());
            while ($row = mysqli_fetch_assoc($option)) {
                foreach ($row as $key1 => $value1) {
                    $$key1 = $value1;
                }
                echo '<font color="#ff0000">You have already enrolled in ' . htmlspecialchars($course_name) . ' (' . htmlspecialchars($course) . ')!</font>';
            }
        } else {
            //Prints if the course the student has selected is full
            if ($number_max == 1) {
                echo '<font color="#ff0000">Sorry ' . htmlspecialchars($course_name) . ' (' . htmlspecialchars($course) . ')  is full, please select another course.</font>';
            }
        }
    }
}
?>
<p>
	<input name="name" placeholder="Student Name" type="text">
	<input name="number" placeholder="Student Number" type="text">
</p>
<p>
	<select name="course" size="1">
		<option id="select">-- Select Course --</option>
<?php
$lf = "\n";
$ht = "\t\t";
$option = mysqli_query($link, "SELECT * FROM courses ORDER BY course_name") or die(mysql_error());
while ($row = mysqli_fetch_assoc($option)) {
    foreach ($row as $key1 => $value1) {
        $$key1 = $value1;
    }
    /**
     * Dynamically creates the option values for the select box based on course info from course_array
     * Added Currently Enrolled to the course list so the end-user would have an idea of how many were currently enrolled in the course.
     **/
     $a = $ht . '<option value="' . $course_code . '">' . $course_name . ' (Enrolled: ' . $enrollment . ')</option>' . $lf;
     echo $a;
}
mysqli_close($link);
?>
	</select>
</p>
<p>
	<input type="submit" value="Send"><input type="reset" value="Clear">
</p>
</form>

Padding around dynamic generated rectangles

$
0
0

Here is my code:

for($i = 1; $i <= 30; $i++){
 
$pos1 = mt_rand(1,900);
$pos2 = mt_rand(1,100);
 
echo '<div class="itemLootBox Unique fadeIn" onclick="lootItem(this)" style="position:absolute;left:'.$pos1.'px;top:'.$pos2.'px">Lunar Rock</div>';
 
}

ffc89e21188adb41666bcf5be405e364.png

 

 

The dimensions of that container is:

Width: 980px

Height: 130px.

 

These correspond with $pos1 and $pos2 respectively.  I reduced 980 to 900 for the mt_rand because the boxes look weird when they get positioned to the edge. 

 

And my problem is, the divs are being randomly generated, but sometimes overlap others. Is there a way to add a function / if statement so I can check against $pos1, and $pos2 to add spacing so the boxes will never overlap? (They don't have to never overlap, but some type of padding would be way better).

 

Edit: Try to think of it as a grid like system, and each rectangle has it's own box of it's 'own' if you will. Wheres there is a padding around each grid. Not sure how to do this


Variable calculations

$
0
0

Hello, I am trying to take the calculations of two variables to create a new data for a new variable. For example.....

 

LRH_calcLevel($LRH_current, $LRH_bankfull); +/- $LRH_totalDepth = $newVar 

 

Which should translate to -10.43 Ft +/- 40 = $newVar (-29.57) <----- What I want

 

Instead it is showing up as 10.43 Ft +/- 40 = $newVar (-50.43) <----- How it is displaying which is incorrect

 

Here is the code I am using. The second function is what I am trying to use to create the new variable data based on the calculations above from the data provide via XML. How can I get this to display correctly?

 

-Thanks

//Parse Lake Ray Hubbard XML Data
$site = simplexml_load_file($LRH_data);{

        $LRH_bankfull   = '435.5';
        $LRH_totalDepth = '40';
        $LRH_current    = $site->observed->datum[0]->primary;
        $LRH_vaild      = $site->observed->datum[0]->valid;
        $LRH_updated    = DATE("D, M d, g:i a", STRTOTIME($LRH_vaild));

}

//Lets calculate the lake depatures from full pool for Lake Ray Hubbard
function LRH_calcLevel($LRH_current, $LRH_bankfull)
{
    //Get float values from strings
    $LRH_current = floatval($LRH_current);
    $LRH_bankfull = floatval($LRH_bankfull);
    //Calculate the difference
    $LRH_calcLevel = $LRH_current - $LRH_bankfull;
    //Format difference to two decimal places and add 'Ft'
    $LRH_calcLevelStr = (string) number_format($LRH_calcLevel, 2) . ' Ft';
    //If vlaue is positive add a + to beginning
    if($LRH_calcLevel>0) { $LRH_calcLevelStr = '+'.$LRH_calcLevelStr; }
    //Return the calculated formatted value
    return $LRH_calcLevelStr;
}

////Lets calculate the lake percentage from full pool for Lake Ray Hubbard
$val1 = $LRH_current;
$val2 = $LRH_bankfull;

$LRH_prec = ( $val1 / $val2) * 100;

// 1 digit after the decimal point
$LRH_prec = round($LRH_prec, 1);

//Lets convert the depature from full pool for Lake Ray Hubbard
function LRH_calcDepth($LRH_calcLevelStr, $LRH_totalDepth)
{
    //Get float values from strings
    $LRH_calcDepthStr = floatval($LRH_calcLevelStr);
    $LRH_totalDepth = floatval($LRH_totalDepth);
    //Calculate the difference
    $LRH_calcDepth = $LRH_calcDepthStr - $LRH_totalDepth;
    //Format difference to two decimal places and add 'Ft'
    $LRH_calcDepthStr = (string) number_format($LRH_calcDepth, 2) . ' Ft';
    //If vlaue is positive add a + to beginning
    if($LRH_calcDepth>0) { $LRH_calcDepthStr = '+'.$LRH_calcDepthStr; }
    //Return the calculated formatted value
    return $LRH_calcDepthStr;
}

////Lets calculate the lake percentage from full pool for Lake Ray Hubbard
$val1 = LRH_calcLevel($LRH_current, $LRH_bankfull);
$val2 = $LRH_totalDepth;

PHP Associate array outputs only last index key and value in another file

$
0
0
I am just trying to use Associate array in another php file through session.

file1.php

<?php
$age
= array();
$_SESSION["age"] = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($_SESSION["age"] as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>\n";
}
?>

OUTPUT:

Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43

file2.php

<?php
session_start
();
foreach( $_SESSION["age"] as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>\n";
}
?>

OUTPUT:

PHP Notice: Undefined index: age in session.php on line 3

PHP Warning: Invalid argument supplied for foreach() in session.php on line 3

 

Why am I getting this error?

 

Above is just example I tried to demonstrate for asking question for other issue, unfortunately I got new error in this example.

But actual issue was, I was trying to plot graph  using library which requires only Associate array, where the data is formed in file1.php. But I get only last index value displayed in file2.php even in graph or in echo.

I don't understand why other values are not displayed in file2.php

Please point me what is going wrong, Thanks.

Targeting an element inside a PHP loop using jQuery

$
0
0

I want to fetch items from a database and be able to update their quantity by selecting a number from a drop down selection and press the button "Update quantity" to perform the action.

I have the following php code:

echo    '<table border="4">
            <tr>
                <th>ID</th>
                <th>Item Name</th>
                <th>Current Quantity</th>
                <th>New Quantity</th>
                <th>Update</th>
            </tr>';

for($i=0 ;$i<$k; $i++)

$z = $i+1;

//fetch data from database
$id = the id of the row that the entry/item is at
$item_name = the name of the item
$current_quantity = the current quantity of the item

//create a table of entries


         echo   '<tr'>
                    <td>'.$z.'</td>
                    <td>'.$item_name.'</td>
                    <td>'.$current_quantity.'</td>
                    <td>

                        <select id="quantity" name="quantity">
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                               .
                                               .
                                               .
                        </select>

                    </td>';

            echo    '<td>

                          <button type="button" value="'.$id.'" name="updatebtn" id="updatebtn">Update Quantity</button>

                    </td>';

      echo    '</tr>';

Where k = number or matches in database

The result is something like this:

////////////////////////////////////////////////////////////////////////////
///ID // Item Name // Current Quantity // New Quantity //    Update      ///
////////////////////////////////////////////////////////////////////////////
// 1 //   Shoes   //       10          //      12      // Update Quantity //
////////////////////////////////////////////////////////////////////////////
// 2 //  T-shirts //        5          //       8      // Update Quantity //
////////////////////////////////////////////////////////////////////////////
// 3 //  Watches //         4          //       2      // Update Quantity //
////////////////////////////////////////////////////////////////////////////

The first 3 columns are populated by the database and New Quantity by the user. As soon as the user is done with the new quantity he/she presses "Update Quantity" to update the database.

Below is the jQuery code i use:

$(document).ready(function(){

 $('#updatebtn').click(function(){

    //i use this value to find the exact entry in the database
    var id = $('#updatebtn').attr('value');

    var quantity_selected = $('select#quantity option:selected').attr('value');

    $.ajax({

                type: "POST",
                url: "js/ajax/updatequantity.php",
                data: {id: id, new_quantity: quantity_selected}

            });


   //this is for testing        
   alert('ok');

 });
});

The updatequantity.php script just takes the new quantity and the row of the entry and updates the value.

My problem is:

If i press the "Update Quantity" of the item "Shoes", i see the pop-up "ok" and the quantity is updated. But when i try to do the same for the 2 other items (T-shirts and watches), i get nothing.

Does my js script has trouble to differentiate between the "Update Quantity" buttons? Is there another approach?

ps: i am doing this using wamp on my localhost

Thanks in advance.

sql is works in phpmyadmin but not working in php with special case

$
0
0

Hi all, 

 

I'v table called vehicles with
id (int auto_increment) and
plate_number (varchar 150).

 

the plate_number have records like (a a a 1 1 1 1) (b b b 2 2 2 2), three chars and four numbers spliced by spaces.

 

I'v php search page with url like this:

http://localhost/vehicles/show.php?plate_number=f%20f%20f%205%205%205%205

search about plate_numbet = f f f 5 5 5 5

my php code:

// pdo connection.

// first sql test 
$sql = "SELECT * FROM vehicles WHERE plate_number LIKE '%".$_GET['plate_number']."%'"; 

// second sql test
// $sql = "SELECT * FROM vehicles WHERE plate_number = '".$_GET['plate_number']."'";

$db->query($sql); 
if($db->rowcount() > 0){ 
// print all results... 
}else{
echo "There are no results.";
}

The query result is: There are no results..

 

But, when I copy the sql statements into phpmyadmin it is works fine. (there is a result). like this:

SELECT * FROM vehicles WHERE plate_number LIKE '%f f f 5 5 5 5%';

OR 

SELECT * FROM vehicles WHERE plate_number = 'f f f 5 5 5 5';

Also i used string functions (htmlspecialchars, rawurldecode, ... ), still not work.

 

any suggestion to solve this issue?

 

Thanks to all

 

Need some directions creating a multi-user site

$
0
0

Hi all,

 

I'm working on a hobby project to improve my skills and learn PHP and MySQL. Don't know if this is the right place to ask this question, so please let me know if it isn't.

 

I already created a single user site. It has a simple PHP login and after login information (like personal information and messages) is pulled from the database and shown. The personal information is stored in a table called settings and the messages are stored in a table called messages.

 

I like to go to the next level and create a multi-user login, but I have no idea were to start. I think I have to switch to another login type were both PHP and MySQL are used. How has the database be designed? Can I use the same structure as in the single user site I created? How can the right (belonging to the user) information be retrieved from the database?

 

Thanks in advance !

 

 

Viewing all 13200 articles
Browse latest View live