I've got this:
foreach($_POST['pos'] as $value) {
$new_value = "UPDATE users SET regnr='" . $value . "'
WHERE username='" . mysql_real_escape_string($_COOKIE['username']) . "'";
}
// Connect to database
$opendb = mysql_connect($dbhost, $dbuser, $dbpass) or die("Kunde inte ansluta till MySQL:<br>" . mysql_error());
mysql_select_db($dbname) or die("Kunde inte ansluta till databasen:<br>" . mysql_error());
mysql_query($new_value) or die(mysql_error());
// Close database
mysql_close($opendb);
Information:
$_POST['pos'] holds a value from the database in a hidden input. This value I have choosen to split with str_split($r['regnr'], 6); into a JQuery sortable list. If I type echo $value; in the foreach loop I've got the new value (not splitted, as I want) from the JQuery sortable list. I need all values from the list, and I get it with echo. But if I use $value variable to UPDATE the database that it came from, it just updates with the last value from the JQuery sortable list.
Can someone solve that? :D
Here is the solution:
$str = '';
foreach($_POST['pos'] as $value) {
$str = $str.$value;
}
// Connect to database
$opendb = mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$new_value = "UPDATE users SET regnr='" . $str . "' WHERE username='" . mysql_real_escape_string($_COOKIE['username']) . "'";
mysql_query($new_value) or die(mysql_error());
// Close database
mysql_close($opendb);
Related
When trying to post data to the database it gives an error saying no database selected. But the content from the database is displaying on a table and select menu.
<?php
$con = mysqli_connect("localhost", "root", "","radian");
if(!$con)
{
exit("Couldn't connect: ".mysqli_connect_error());
}
mysqli_set_charset($con, "utf8");
$insert_data = "UPDATE enquiries
SET ResponseDate = '".$current_date."',
Response = '".$txtResponse."',
Enquiry_No = '".$_SESSION['ses_staff']
."' WHERE Enquiry_No = '".$txtStudentId."'";
$execute = mysql_query($insert_data) or die(mysql_error());
$output= '<h4 style="margin-left:1em;width:15em;color:red;"> Response successful!. </h4>';
}else{
$output= '<h4 style="margin-left:1em;width:15em;color:red;"> </h4>';
}
Your final code should be identical to:
<?php
$con = mysqli_connect("localhost", "root", "", "radian");
if (!$con) {
exit("Couldn't connect: " . mysqli_connect_error());
}
mysqli_set_charset($con, "utf8");
$insert_data = "UPDATE enquiries SET ResponseDate = '" . $current_date . "', Response = '" . $txtResponse . "',Enquiry_No = '" . $_SESSION['ses_staff'] . "' WHERE Enquiry_No = '" . $txtStudentId . "'";
$execute = mysqli_query($con, $insert_data) or die(mysqli_error($con));
$output = '<h4 style="margin-left:1em;
width:15em;
color:red;"> Response successful!. </h4>';
Changes made:
Remove all instances of mysql_* and replace with the correct mysqli_* function.
Remove the orphaned } else {.
Note: Officially mysql_* functions are deprecated. So no point using them. Use either mysqli_* or PDO.
I am trying to get my PHP script to print all rows i have in my database in a neat order. Currently Im not getting anything. My table has 4 columns, Name, Address, Long and Lat, and 2 rows with data. The table is called Locations. I am using the following code but im not getting to to work:
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
Here is a simple example using pdo instead of mysqli
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS); // create connection
$stmt = $pdo->prepare("SELECT Name, Address, Long, Lat FROM Locations");
//you should never use *, just call each field name you are going to use
$stmt->execute(); // run the statement
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC); // fetch the rows and put into associative array
print_r($arr); // print all array items, unformatted
and you can echo out the data and format it yourself using a for loop like so
for($i=0; $i<sizeof($arr); $i++) { // this will loop through each row in the database. i prefer this method over while loops as testing has shown this is much faster for large scale tables
echo 'Name: ' . $arr[$i]['Name'] . '<br />'; // $arr is the array name, $i is the number of the array item, or iterator, ['Name'] is the field name
echo 'Address: ' . $arr[$i]['Address'] . '<br>';
echo 'Long: ' . $arr[$i]['Long'] . '<br>';
echo 'Lat: ' . $arr[$i]['Lat'] . '<br>';
}
If the names are correct, this would echo out your row ID and row CITY. Just change the names to your field names. If you want further assistance, feel free to ask.
However, if you want to stick with mysqli, give the following code a wirl.
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$mysqli = mysqli_connect($dbHOST, $dbUSER, $dbPASS, $dbNAME);
$query = "SELECT Name, Address, Long, Lat FROM Locations";
$result = mysqli_query($mysqli, $query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
echo 'Name: ' . $row['Name'] . '<br />';
echo 'Address: ' . $row['Address'] . '<br>';
echo 'Long: ' . $row['Long'] . '<br>';
echo 'Lat: ' . $row['Lat'] . '<br>';
}
}
change fieldname to the field you want to display
EDIT: Paste the following code. It will echo out the number of rows. This will tell you if the query statement is correct.
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS);
$stmt = $pdo->query("SELECT Name, Address, Long, Lat FROM Locations");
echo $stmt->rowCount();
Fetch query result as associative array and use for each to print all results
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
while($rows = mysqli_fetch_assoc($result)) {
foreach($rows as $key => $val)
{
echo $val;
}
}
}
mysqli_close($con);
?>
I'm newbie in PHP sorry. How can i update a user defined var in user defined table with user defined value in MySql? I cant get it work.
<?PHP
$table = $_POST['table'];
$id = $_POST['id'];
$key = $_POST['key'];
$value = $_POST['value'];
$con = mysql_connect("mysql.serversfree.com","u105645000***","mf***") or ("Cannot connect!" . mysql_error());
if (!$con)
die('Could not connect: ' . mysql_error());
mysql_select_db("u10564500***" , $con) or die ("could not load the database" . mysql_error());
/*$mysql = mysql_query("INSERT INTO $table ($key) VALUES ('".$value."');");*/
$sql = "UPDATE $table Set ".$key."='".$value."'";
?>
Why your code is not working
You're not launching the query.
No where clause
Without specifying any conditions, every record of the coulmn $key will be updated with $value.
Solution
Use this code:
<?PHP
$con = mysqli_connect("mysql.serversfree.com","u105645000***","mf***","u10564500***");
$table = mysqli_real_escape_string($con,$_POST['table']);
$id = mysqli_real_escape_string($con,$_POST['id']);
$key = mysqli_real_escape_string($con,$_POST['key']);
$value = mysqli_real_escape_string($con,$_POST['value']);
if (!$con){die('Could not connect: ' . mysqli_error($con));}
$sql = mysqli_query($con,"UPDATE ".$table." Set ".$key."='".$value."'");
?>
I am trying to import xml data into a mysql table. I have the below fields to be Imported:
reference
price
category
type
city
property
imgurl1
imgurl2
The problem is that the number of <imgurl>(url to image file) is not the same. Below is the code:
$conn = mysql_connect($hostname, $username, $password);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname,$conn) or die( mysql_error() );
$xml = simplexml_load_file('http://astonpearlemail.net/feeds/feedsmall.xml');
$data = $fields = array();
foreach ($xml->xpath('listing') as $listing) {
$fields = array_keys((array)($listing));
$data[] = '("' . join('", "', (array)$listing) . '")';
}
$sql = "INSERT INTO ap_prop (" . join(', ', $fields) . ") VALUES\n" ;
$sql .= join (",\n", $data);
$result1 = mysql_query($sql,$conn);
echo "<pre>$sql</pre>"
Please suggest how I can import the varying number of imgurl.
Thanks in advance
I'm trying to display all my database fields like radio buttons. For example I have this database fields :
hostess_id
hostess_name_en
hostess_surname_en
... etc ...
I want to display them as radio buttons, in order to select them, then display data information only for the selected buttons.
How can I do that?
I have something like this:
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = 'db_up';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from hostess', $link);
while ($row = mysql_fetch_assoc($result)){
echo "<td><input type=\'checkbox\' name=\'hostess[]\' value=\'" . $row['hostess_id'] . "\'>" . $row['hostess_firstname_en'] . "<br />";
}
?>
With PDO, It will get all fields
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
With deprecated mysql_*
function mysql_field_array( $query ) {
$field = mysql_num_fields( $query );
for ( $i = 0; $i < $field; $i++ ) {
$names[] = mysql_field_name( $query, $i );
}
return $names;
}
// Example of use
$fields = mysql_field_array( $query );
Than you can loop through that array of field names and use the name with your check box.
Checkboxes need a unique name or they need to be an array. A checkbox array would be appropriate for what you're doing:
while ($row = mysql_fetch_assoc($result)){
echo "<input type='checkbox' name='hostess[]' value='" . $row['id'] . "' />" . htmlentities($row['hostess_surname_en']) . "<br />";
}
This will give you a list of checkboxes with the hostess surname next to each.
Now, when this form is submitted to a PHP script, you will be able to access the selected row id's with:
$selectedIds = $_POST['hostess']; // an array
$selectedIds is an array of the checked record ids.
I suggest using PDO or MySQLi for new code because the mysql_* library is deprecated.