everytime i try and add one to the second column of a certain name, it changes the value to 5, if i echo my event it says it is equal to resource id #4. Anyone have any fixes?
<form action="new.php" method="POST">
<input type="text" name="input_value">
<br />
<input name="new_User" type="submit" value="Add to Users">
<input type="submit" name="event_Up" value="Attended Event">
<?php
//Connect to Database
mysql_connect("localhost", "root", "");
//If Add New user butten is clicked execute
if (isset($_POST['new_User']))
{
$username = $_POST['input_value'];
$make = "INSERT INTO `my_db`.`profile` (`Name`, `Events`) VALUES ('$username', '1')";
mysql_query($make);
}
//If Event up is pushed then add one
if (isset($_POST['event_Up']))
{
$username = $_POST['input_value'];
$event = mysql_query("SELECT 'Events' FROM `my_db`.`profile` WHERE Name ='$username'");
$newEvent = $event +1;
$update = "UPDATE `my_db`.`profile` SET Events = '$newEvent' WHERE Name = '$username'";
mysql_query($update);
}
//Print Table
$data = mysql_query("SELECT * FROM `my_db`.`profile`");
Print "<table border cellpadding=4>";
while($info = mysql_fetch_array($data))
{
Print "<tr>";
Print "<th>Name:</th> <td> ".$info['Name'] . "</td>";
Print "<th>Events:</th> <td>".$info['Events'] . " </td>";
}
Print "</table>";
?>
I've cleaned up your code a little bit.
It's still a mess, but should at least work (un-tested though).
<form action="new.php" method="post">
<input type="text" name="input_value">
<br />
<input name="new_User" type="submit" value="Add to Users">
<input type="submit" name="event_Up" value="Attended Event">
</form>
<?php
//Connect to Database
mysql_connect("localhost", "root", "");
//If Add New user butten is clicked execute
if (isset($_POST['new_User']))
{
$username = empty($_POST['input_value']) ? NULL : $_POST['input_value'];
if ( ! empty($username))
{
mysql_query("
INSERT INTO `my_db`.`profile`
(`Name`, `Events`)
VALUES
('". mysql_real_escape_string($username) ."', 1)
");
}
}
//If Event up is pushed then add one
if (isset($_POST['event_Up']))
{
$username = empty($_POST['input_value']) ? NULL : $_POST['input_value'];
if ( ! empty($username))
{
$event = mysql_query("
SELECT
Events
FROM
`my_db`.`profile`
WHERE
Name = '". mysql_real_escape_string($username) ."'
");
$newEvent = (int) (mysql_result($event, 0, 'Events') + 1);
mysql_query("
UPDATE
`my_db`.`profile`
SET
Events = $newEvent
WHERE
Name = '". mysql_real_escape_string($username) ."'
");
}
}
//Print Table
$data = mysql_query("SELECT * FROM `my_db`.`profile`");
Print "<table border cellpadding=4>";
while($info = mysql_fetch_assoc($data))
{
Print "<tr>";
Print "<th>Name:</th> <td> ". htmlentities($info['Name'], ENT_COMPAT, 'UTF-8') . "</td>";
Print "<th>Events:</th> <td>". htmlentities($info['Events'], ENT_COMPAT, 'UTF-8') . " </td>";
}
Print "</table>";
?>
Edit:
Just so you are aware... your issue was $newEvent = $event +1;.
$event is a MySQL resource, not the query's result. You have to use one of the mysql_* functions to get the data (see my code above.)
It seems you are just learning PHP, and I would highly recommend you stop using the mysql_* functions right now and start using PDO.
use mysql_fetch_assoc not mysql_fetch_array
any time you get a resource id rather than data it means you have just a pointer to something and most likely need a function call to get the data out.
You need to fetch the array and then define $event based on the results. You're assigning $events on the mysql query itself.
$result = mysql_query("SELECT 'Events' FROM `my_db`.`profile` WHERE Name ='$username'");
while($row = mysql_fetch_array( $result )) {
$event = $row['Events'];
}
Related
Well i got this script
while($row = $result->fetch_assoc()) {
$_SESSION["sup"] = $row['id'];
if ($hi < $row['buytime']) {
} else {
echo " <form action='Action1.php' method='get'>
Thanks for buying from our shop , if the item with id <input type='submit' value='" . $row['id'] ."' class='btn-link'/> </form>";
echo "<form action='Action.php' method='post'>
is a bad tool , you can report by clicking on the following button <input type='submit' value='Report Item' />
</form>";
}
}
The only problem is hat in line $_SESSION["sup"] = $row['id'];
Keeps sending a fixed value which it's 144 while the $row['id']; is not a fixed value , i'm really lost lol
If session is a bad idea , how can i send ID to action.php without inserting the ID in a hidden input ?
Update the two pages
First PAge
<?php
$conn = mysqli_connect("localhost", "localhost", "localhost", "localhost");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$buyer = $_SESSION['username'];
$sql_shells = "SELECT buytime,id,situation,buyer FROM shells WHERE situation = 'sold' AND buyer = '$buyer' ";
$dt = new DateTime();
$dt->modify('+172799 seconds');
$hi = $dt->format('Y-m-d H:i:s');
$_SESSION["sup"] = [];
$result = $conn->query($sql_shells);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$_SESSION["sup"][] = $row['id'];
$_SESSION["sup"] = implode(',', $session['sup']); // use this var
if ($hi < $row['buytime']) {
}else{
echo " <form action='view_item.php' method='get'>
Thanks for buying from our shop , if the item with id <input type='submit' value='" . $row['id'] ."' class='btn-link'/> </form>";
echo "<form action='reportinsert.php' method='post'>
is a bad tool , you can report by clicking on the following button <input type='submit' value='Report Item' />
</form>";
}
}
}else {
}
?>
Second page
<?php
session_start();
if (isset($_SESSION['username'])) {
$link = mysqli_connect("localhost", "localhost", "localhost", "localhost");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$trn_date = date("Y-m-d H:i:s");
$seller = $_SESSION['username'];
$id = $_POST['whatever'];
$id = explode(',', $id); // You now have an array of IDs.
$sql = "INSERT INTO reports (reporter,stats,trn_date,itemid) VALUES ('$seller','Opened','$trn_date','$id')";
if(mysqli_query($link, $sql)){
echo $id;
echo $seller;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
} else
{
header("location:/quickshops/login.php");
}
?>
now it gives me Array in insert
Remove inside $row '' from $row['id'].
You will always get the last row's value, the reason is, you set the session in each iteration so whenever you plan to use it out of the loop, you will get the value of last iteration.
In case you want to set the array within the session, that's how you can do that:
$idsArray= array();
while($row = $result->fetch_assoc()) {
$idsArray[] = $row['id'];
}
$_SESSION["ids"] = $idsArray;
You are rewriting the value every time you go through the loop:
// loop through results
while($row = $result->fetch_assoc()) {
// overwrite session variable with the last id
$_SESSION["sup"] = $row['id'];
So if you have 10 results, the session var will be the id of the 10th row.
Without more detail on what you are trying to achieve with your result set, we can't really help much more than that. Maybe update your question with more details if this isn't enough to solvce your problem?
Update Ok so you need ALL Id's
You could make the session var an array, and when it's time to post the ID's, implode() them with a comma. Then in the receiving script, explode on a comma to get all the ids.
$_SESSION["sup"] = [];
while($row = $result->fetch_assoc()) {
$_SESSION["sup"][] = $row['id'];
// etc
}
$_SESSION["sup"] = implode(',', $session['sup']); // use this var
And in the other script
$ids = $_POST['whatever'];
$ids = explode(',', $ids); // You now have an array of IDs.
Incidentally, since you are using a session variable, you probably don't even need to post it, and just access the session in the other script, but then I've no idea what your code is doing
My dropdown menu is loading from the database, I can select multiple options from the list. When I click my 'Add' button everything appears to be behaving as expected, apart from the fact that nothing is saving back to the database. Unfortunately I've done so many tweaks now, having looked at stack overflow and others, I'm in the realm of confusion rather than progress.
I have set up a logger file to show when a page is reached. So I can confirm that I do get to the insert_rooms.inc.php page.
<?php
session_start(); // gets current session data for user // this function sends headers so it cannot be called after any output.
require_once '../dbconfig.php';
$date = new DateTime();
$date = $date->format("y:m:d h:i:s");
$id = $_SESSION['u_nickname'];
$u_id = $_SESSION['u_id'];
$file = "../ips.txt";
$text = file_get_contents($file);
$text .= $date ." " . $id . " visited insert_rooms.inc.php"."\n"; ///////// this text must be changed for each page
file_put_contents($file, $text);
$conn = OpenCon();
if ($conn)
{
if(isset($_POST['room[]']))
{
$room = mysqli_real_escape_string($conn, $_POST['room']);
if($room) // if a room exists insert into db with users id.
{
foreach($_POST['room'] as $r)
{
//here we need to take for example the word kitchen and find the id belonging to kitchen from the master_rooms table use it to find the master_room_id for kitchen and insert that into the table called user_room_list - along with the user id taken from the session u_id
$room_id = mysqli_query($conn, "SELECT master_room_id FROM master_rooms WHERE master_room_name = '$r'");
$sql = "INSERT INTO user_room_list(user_info_id, master_room_id)
VALUES(' ".$u_id." ', ' " .$room_id. " ') ";
mysqli_query($conn, $sql);
}
}
}
//session_unset();
//session_destroy();
header("Location: ../room_choice.php");
exit();
CloseCon($conn);
}
?>
extract from other file:
<div class="dropdown">
<form action="includes/insert_rooms.inc.php" method="POST">
"Hold down the Ctrl (windows) / Command (Mac) button to select multiple options."
<br/>
<br/>
<select name="room[]" multiple>
<?php
$conn = OpenCon();
if ($conn)
{
$query = "SELECT master_room_name FROM master_rooms";
mysqli_query($conn, $query) or die('Error querying database.');
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_NUM))
{
for ($i = 0; $i < count($row); $i++)
{
echo "<option value=". $row[$i] . ">" . $row[$i] ."</option>";
}
}
CloseCon($conn);
echo "</select>";
echo " <input type="."submit"." value="." Add "." name="."send"."> ";
echo " </form> ";
}
?>
Below is the solution I found. Code is corrected accordingly.
foreach($room as $r) {
$result = mysqli_query($conn, "SELECT master_room_id FROM master_rooms WHERE master_room_name = '$r' ;");
$room_id_array = mysqli_fetch_array($result);
$room_id = $room_id_array[0]; // required as room_id goes into an array of length 1
$stmt = $conn->prepare("INSERT INTO user_room_list(user_info_id, master_room_id) VALUES (?, ?)");
$stmt->bind_param("si", $u_id, $room_id);
$stmt->execute();
I have two tables:
'courses' with these fields:COURSE_ID(auto
increment),start_date,end_date,title
'courses_students' with these fields:ID(auto
increment),COURSE_ID,STUDENT_ID.
I want to insert some values in my mysql table called "courses_students" from my other table called "courses".
Users can see in a page the data from 'courses'(courses names,starting dates,ending dates) and they must select which course they want to attend,by clicking the button 'attent course'.
Everytime someone clicks the submit button,the values are inserted in courses_students table,but not correctly.The problem is that everytime,the COURSE_ID from 'courses_students' has the value of the last COURSE_ID from 'courses'.And,other strange problem is that the values are inserted twice,everytime.
This is the code:
<?php
$link = mysql_connect('localhost','root','');
if(!$link){
die('Could not connect: '.mysql_error());
}
mysql_selectdb("db");
?>
<ul>
<?php
$sql = "SELECT * FROM courses";
$result = mysql_query($sql);
while($file = mysql_fetch_array($result)){
echo '<ul>';
echo '<li>';
$STUDENT_ID = $_SESSION['ID'];
$COURSE_ID = $file['COURSE_ID']; //**It dislays the CORRECT ID for each course!**
echo 'the course id: ' .$COURSE_ID;
echo 'course name: ' .$file['title'];
echo 'Starting: ' .$file['start_date'];
echo ' ending: '.$file['end_date'];
echo '<form action="lista_cursuri.php" method="post"> <input type="submit" name="submit" value="attent course!"> </form>';
echo '</li>';
}
?>
</ul>
<?php
if(isset($_POST['submit'])){
$sql1 = "INSERT INTO `courses_students` (COURSE_ID,STUDENT_ID) VALUES ($COURSE_ID,$STUDENT_ID)";
$result = mysql_query($sql1);
}
?>
I can't manage to see where the problem is.Maybe this is not the correct procedure.
Salut
Change mysql_fetch_array which is a multidimensional array once numerically indexed and once by field name which gives you double results to mysql_fetch_assoc
and $COURSE_ID is always last because for each loop it is overwritten
Try this:
Part 1:
while($file = mysql_fetch_assoc($result)){
echo '<ul>';
echo '<li>';
$STUDENT_ID = $_SESSION['ID'];
$COURSE_ID = $file['COURSE_ID'];
echo 'the course id: ' .$COURSE_ID;
echo 'course name: ' .$file['title'];
echo 'Starting: ' .$file['start_date'];
echo ' ending: '.$file['end_date'];
echo "<form action='lista_cursuri.php' method='post'>
<input type='hidden' name='courseid' value='".$COURSE_ID."' >
<input type='submit' name='submit' value='attent course!''> </form>";
echo '</li>';
}
Part 2:
if(isset($_POST['submit'])){
$course = $_POST['courseid'];
$sql1 = "INSERT INTO `courses_students` (COURSE_ID,STUDENT_ID) VALUES ($course,$STUDENT_ID)";
$result = mysql_query($sql1);
}
Try this:
$sql1 = "INSERT INTO `courses_students` (COURSE_ID,STUDENT_ID)
VALUES ('".$COURSE_ID."','".$STUDENT_ID."')"; $result = mysql_query($sql1);
I have a form on a page that posts a record id to a page I want to display that record on. The form is:
<form method="post" action="update.php">
<input type="hidden" name="sel_record" value="$id">
<input type="submit" name="update" value="Update this Order">
</form>
I have tested to see if $id is getting the correct value and it does. When it post to update.php it does not return any values. Any ideas? here is the update page code:
$sel_record = $_POST['sel_record'];
$result = mysql_query("SELECT * FROM `order` WHERE `id` = '$sel_record'") or die (mysql_error());
if (!$result) {
print "Something has gone wrong!";
} else {
while ($record = mysql_fetch_array($result)) {
$id = $record['id'];
$firstName = $record['firstName'];
$lastName = $record['lastName'];
$division = $record['division'];
$phone = $record['phone'];
$email = $record['email'];
$itemType = $record['itemType'];
$job = $record['jobDescription'];
$uploads = $record['file'];
$dateNeeded = $record['dateNeeded'];
$quantity = $record['quantity'];
$orderNumber = $record['orderNumber'];
}
}
you have not put the php tags <?php ?> inside the html
<input type="hidden" name="sel_record" value="<?php echo $id; ?>">
You should also try to define those variables outside of the while loop.
$id = '';
$result = mysql_query("SELECT * FROM `order` WHERE `id` = '$sel_record'") or die (mysql_error());
if (!$result) {
print "Something has gone wrong!";
} else {
while ($record = mysql_fetch_array($result)) {
$id = $record['id'];
}
}
Not a full example, but you get the idea.
You have to escape the string... and you can drop the single quotes around order and id.
Try:
$result = mysql_query("SELECT * FROM order WHERE id = '" . $sel_record . "'")
if $sel_record is a String, otherwise remove the single quotes:
...WHERE id = " . $sel_record)
You can also use functions sprintf and mysql_real_escape_string to format:
$query = sprintf("SELECT * FROM order WHERE id = '%s'",
mysql_real_escape_string($sel_record));
I am trying to create a form to allow a user to update data from the form to the existing amount in the database. Here is what I have so far it appears to double the value. I was thinking I needed to pull the value from the database and then add the data from the form.
<?php
$username = "username";
$password = "password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "<font face=tahoma color=#ff000><b>Connected to MySQL</b></font><br><br>";
//select a database to work with
$selected = mysql_select_db("pdogclan_points",$dbhandle)
or die("Did this change");
// Formulate Query
$_POST["filter"];
$memid = mysql_real_escape_string($_POST["Member_ID"]);
$query = sprintf("SELECT Member_ID, Bank, Reward_1, Reward_2, Reward_3 FROM Points_Rewards WHERE Member_ID = '$memid'") or die("Could Not Formulate the Query");
//execute the SQL query and return records
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
//fetch tha data from the database
while ($row = mysql_fetch_array($result))
echo "<table width=750 cellspacing=2 cellpadding=2 border=2>
<tr>
<td bgcolor=#000000 width=150><font face=tahoma color=white>ID: {$row['Member_ID']}</font></td>".
"<td width=150><font face=tahoma>Bank: {$row['Bank']}</td>".
"<td width=150><font face=tahoma>Reward 1: {$row['Reward_1']}</td>".
"<td width=150><font face=tahoma>Reward 2: {$row['Reward_2']}</td> ".
"<td width=150><font face=tahoma>Reward 3: {$row['Reward_3']}</td>
</tr>
</table><br></font>";//display the results
// Formulate Update Query
$_POST["submit"];
$memid = mysql_real_escape_string($_POST["Member_ID"]);
$query = sprintf("SELECT Member_ID, Bank, Reward_1, Reward_2, Reward_3 FROM Points_Rewards WHERE Member_ID = '$memid'") or die("Could Not Formulate the Query");
while ($row = mysql_fetch_array($result))
{
$bankdb = $row['Bank'];
$reward1db = $row['Reward_1'];
$reward2db = $row['Reward_2'];
$reward3db = $row['Reward_3'];
}
echo $bank;
echo $reward1;
echo $reward2;
echo $reward3;
$memid = mysql_real_escape_string($_POST["Member_ID"]);
$bank = $_POST['bank'];
$reward1 = $_POST['reward1'];
$reward2 = $_POST['reward2'];
$reward3 = $_POST['reward3'];
$query = "UPDATE Points_Rewards Set Bank = ('$bank' + '$bankdb'), Reward_1 = ('$reward1' + '$reward1'), Reward_2 = ('$reward2' + '$reward2'), Reward_3 = ('$reward3' + '$reward3') WHERE Member_ID = '$memid'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_query($query)){
echo "updated";}
else{
echo "fail";}
//close the connection
mysql_close($dbhandle);
?>
Just create a form using basic HTML, store data you fetched from database in PHP variables, then display that data using PHP tags, like this:
<form action="..." method="post" >
<?php
$memid = mysql_real_escape_string($_POST["Member_ID"]);
$query = sprintf("SELECT Member_ID, Bank, Reward_1, Reward_2, Reward_3 FROM Points_Rewards WHERE Member_ID = '$memid'") or die("Could Not Formulate the Query");
while ($row = mysql_fetch_array($result))
{
?>
<input type="text" name="r1" value="<?php echo $row['Reward_1']; ?>" /> ;
<input type="text" name="r2" value="<?php echo $row['Reward_2']; ?>" /> ;
<input type="text" name="r3" value="<?php echo $row['Reward_3']; ?>" /> ;
...
<?php
}
?>
...
</form>
You can use operators on the tables values in your SQL - it would look something like this:
$query = "UPDATE Points_Rewards Set Bank = (Bank + '$bankdb'), Reward_1 = (Reward_1 + '$reward1'), Reward_2 = (Reward_2 + '$reward2'), Reward_3 = (Reward_3 + '$reward3') WHERE Member_ID = '$memid'";
This is the structure
// if a form is submitted
if(isset($_POST['submit'])) {
$memid = $_POST["Member_ID"];
//SELECT or INSERT or UPDATE your DATABASE. Yes use PDO and prepared statements.
$query = $dbh->prepare("SELECT Member_ID, Bank, Reward_1, Reward_2, Reward_3 FROM Points_Rewards WHERE Member_ID = '$memid'")
//don't forget to bind parameters
$sth->bindParam(':memid', $memid, PDO::PARAM_INT);
$sth->execute(...);
//the loop
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo '';
}
//close the if statement
}
//write the form
<form method="post"/>
<input name="Member_ID" type="text" required/>
<input name="submit" type="submit" value="submit" />
</form>