Onchange update database - php

I'm trying to make an page where you can select a value in a dropdown select box. When the selection is made it should update the database using the selected value.
I use 2 pages one including the html/javascript and one using php.
Currently when i select something nothing happens.
What am i doing wrong?
test.php
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
function updateDb() {
$.post("buh.php", $("#form").serialize());
}
</script>
</head>
<body>
<form id="form">
<?php
include 'Includes/database_connection.php';
$sql = "select * FROM sims ORDER BY phonenr asc" ;
$result = mysql_query($sql,$con);
echo "<select id='select' name='select' onChange='updateDb()'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['phonenr'] . "'>" . $row['phonenr'] . "</option>";
}
echo "</select>";
?>
</form>
</body>
And buh.php
<?php
include 'Includes/database_connection.php';
$sql = "select * FROM sims ORDER WHERE phonenr='".mysql_escape_string($_POST["select"])."'" ;
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
mysql_query("UPDATE pairings SET sim_id='$id' WHERE unit_id='1'")
or die(mysql_error());
}
?>

You have something wrong with you SELECT query
$sql = "select * FROM sims ORDER WHERE phonenr='".mysql_escape_string($_POST["select"])."'" ;
^this ORDER here makes no sense
Either remove the word ORDER wich is a clause to order by a column, or assign it a column to order by with the correct syntax
SELECT * FROM tablename WHERE yourcolumncondition ORDER BY yourcolumntoorderby
Then I would like to remember you that mysql_ functions are deprecated so i would advise you to switch to mysqli or PDO

select * FROM sims ORDER ..You have added ORDER here wrongly in buh.php
$sql = "select * FROM sims ORDER WHERE phonenr='".mysql_escape_string($_POST["select"])."'" ;

$sql = "select * FROM sims ORDER WHERE phonenr='".mysql_escape_string($_POST["select"])."'" ;
remove order.

Related

Changing cell value based on another cell

I am working on a simple php app where I store employees data.
Basically, I have in MySQL few tables, one of them is Employees where I have many columns like name, position, costcenter, manager, etc...
Via php I am able to change the records in the table (simple CRUD).
What I want to achieve is when I change Position based on this Cost Center to be changed.
I have a separate table (CostCenters.sql) with all positions and their cost centers with a structure like this:
CostCenter
Position
124
Engineer
199
Manager
In my edit.php I am taking the positions from this table like this:
echo "<select name='position' required>";
include "dbConn.php";
$records = mysqli_query($db,
"SELECT position
from employees
WHERE id = $id
UNION SELECT jobtitle from costcenters");
while($data = mysqli_fetch_array($records))
{
echo "<option value='".$data['position'] ."'>"
.$data['position'] .
"</option>";
}
echo "</select>";`
In the same file for cost centers I have:
echo "<select name='costcenter' required>";
//echo "<option disabled selected>-- Избери --</option>";
include "dbConn.php";
$records = mysqli_query($db,
"SELECT costcenter, POSITION
FROM employees
WHERE id = $id
UNION ALL SELECT constcenternr, jobtitle
FROM costcenters ");
while($data = mysqli_fetch_array($records))
{
echo "<option value='".$data['costcenter'] ."'>"
.$data['costcenter'] . "-" .$data['POSITION'] . "
</option>";
}
echo "</select>";`
And my update query is very simple:
UPDATE employees
SET costcenter ='$costcenter',idcard ='$idcard',
personalnr ='$personalnr',position ='$position';
The question is how to make it when I update the record for Position to automatically changed also the CostCenter based on the value corresponding from (CostCenters.sql).
I have tried editing the select query for edit.php to union also the records from (CostCenters.sql) but had no success.
Here is my select query: (simple)
$result = mysqli_query($mysqli,
"SELECT * FROM employees WHERE id ='$id' ");
while($data = mysqli_fetch_array($result))
My first trial was to modify update query in this way:
UPDATE employees
SET costcenter =
(select costcenternr
from CostCenters
where ****),idcard ='$idcard',
personalnr = '$personalnr',position = '$position';
Frankly speaking, my SQL skills are not enough to complete this query

$_POST Insert into many to many, wrong PHP Syntax?

EDIT: IGNORE ANY SQL INJECTIONS OR VULNERABLE CODE STATEMENTS :D
(School Project).
I wish to create a insert form on my webpage where I can select an artist from a table, including a song from a table and combine them for an insert into a combined foreign key table.
I have managed to do selects and insert with only individual artist and song drop-downs on my web-page, but would wish for combining the two ID's from each table to combine them to a many to many relative table. But when I press the submit button nothing happens, and I'm a beginner and don't know if I'm missing any important bits of actually Posting the information.
For troubleshooting I have tried my code, and tested it. I see if I remove my code theres no problem, so the problem persists on the syntax I believe, as the first dropdown shows, alongside the second dropdown and submit button, but the problem is within the actual processing and SQL query part, where it never goes to the DB..
The problem:
As you can see below I have a the text Song Name appear with a drop-down menu in the bottom left corner including the Artist Name with a submit button. But my problem persists as the select and then insert from the two drop downs into the combined table does not work, it does not actually submit, I want it to post into the DB what can I do. But somethings off? I would appreciate any questions or help, this community is so amazing and wonderful to operate in!
Database
PHP
<form method='POST'>
<?php
include('connect_mysql.php');
if(isset($_POST["mangetilmange"])) {
$song_id = $_POST["song_id"];
$artist_id = $_POST["artist_id"];
$sql ="INSERT INTO artist_has_song (song_id, artist_id) VALUES
('$song_id', '$artist_id')";
if($conn->query($sql)) {
echo "Completed";
} else {
echo "Blablalbablablablablablablabl $sql
($conn->error.";
}
}
?>
Song Name
<?php
$sql = "SELECT * FROM song";
$resultat = $conn->query($sql);
echo "<select name='song_id'>";
while ($rad = $resultat->fetch_assoc()) {
$song_id = $rad["song_id"];
$songname = $rad["songname"];
echo "<option value='$song_id'>$songname</option>";
}
echo "</select>";
?>
Artist Name
<?php
$sql = "SELECT * FROM artist";
$resultat = $conn->query($sql);
echo "<select name='artist_id'>";
while ($rad = $resultat->fetch_assoc()) {
$artist_id = $rad["artist_id"];
$artistname = $rad["artistname"];
echo "<option value='$artist_id'>$artistname</option>";
}
echo "</select>";
?>
</form>
<input type="submit" name="mangetilmange" value ="Submit">
change you code to this:
<form method='POST'>
<?php
include('connect_mysql.php');
if(isset($_POST["mangetilmange"])) {
$song_id = $_POST["song_id"];
$artist_id = $_POST["artist_id"];
$sql ="INSERT INTO artist_has_song (song_id, artist_id) VALUES
('$song_id', '$artist_id')";
if($conn->query($sql)) {
echo "Completed";
} else {
echo "Blablalbablablablablablablabl";
}
}
?>
Song Name
<?php
$sql = "SELECT * FROM song";
$resultat = $conn->query($sql);
echo "<select name='song_id'>";
while ($rad = $resultat->fetch_assoc()) {
$song_id = $rad["song_id"];
$songname = $rad["songname"];
echo "<option value='$song_id'>$songname</option>";
}
echo "</select>";
?>
Artist Name
<?php
$sql = "SELECT * FROM artist";
$resultat = $conn->query($sql);
echo "<select name='artist_id'>";
while ($rad = $resultat->fetch_assoc()) {
$artist_id = $rad["artist_id"];
$artistname = $rad["artistname"];
echo "<option value='$artist_id'>$artistname</option>";
}
echo "</select>";
?>
<input type="submit" name="mangetilmange" value ="Submit">
</form>

Using PHP variables as name of table in MySQL

I want to use a PHP variable ( $username ) as the name of the SQL table I am creating.
I need to use this because in my webpage each user needs to have his own table where he can put data , When I try to select the data from the table doesn't work, I have tried a lot of times but it is not working, can you help me with this problem?
$result = mysqli_query($mysqli, "SELECT * FROM `$username` ORDER BY id DESC");
and
$sql= "SELECT * FROM `$username` ORDER BY data DESC";
Neither of these do not work , Can you please help me?
This is the code I have
<?php
session_start();
if (!isset($_SESSION['username'])) {
$_SESSION['msg'] = "You must log in first";
header('location: login.php');
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header("location: login.php");
}
$sql= 'SELECT * FROM '.$username.' ORDER BY data DESC';
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<br/><br/>
<div>
<table align="center" width='100%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Data</td>
<td>Cantiere</td>
<td>Pranzo</td>
<td>Cena</td>
<td>Hotel</td>
<td>Macchina</td>
<td>Note</td>
<td>Edit/Delete</td>
</tr>
<?php
while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$res['data']."</td>";
echo "<td>".$res['cantiere']."</td>";
echo "<td>".$res['pranzo']."</td>";
echo "<td>".$res['cena']."</td>";
echo "<td>".$res['hotel']."</td>";
echo "<td>".$res['macchina']."</td>";
echo "<td>".$res['note']."</td>";
echo "<td>Edit | <a
href=\"delete.php?id=$res[id]\" onClick=\"return confirm('Are you sure you
want to delete?')\">Delete</a></td>";
}
?>
</table>
</div>
</body>
</html>
and i get the error :
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in index.php on line 36
Try it like this
$sql= 'SELECT * FROM '.$username.' ORDER BY data DESC';
or
$result = mysqli_query($mysqli, "SELECT * FROM " .$username. " ORDER BY id DESC");
When you use a variable you need to use quotes
You should try something like this:
$result = mysqli_query($mysqli, "SELECT * FROM " . $username . " ORDER BY id DESC");
Because SQL does not know what $username is
This goes for both of the query's
As suggested by Loek:
Note that this answer (and the question) contain sql that easily be hijacked! Please prepare your statements before executing them!
Try to add string concatenation:
$result = mysqli_query($mysqli, "SELECT * FROM " . $username . " ORDER BY id DESC");
and
$sql= "SELECT * FROM " . $username . " ORDER BY data DESC";
You need to concatinate your variable into your select statement, i.e.
$sql="SELECT * FROM ".$username." ORDER BY id DESC";
And
$sql="SELECT * FROM ".$username." ORDER BY data DESC";

database rows to HTML select

I'm trying to populate my dropdown list with informations of my DB. I Use this code:
<select name="teste">
<?php
include "conecta.php";
$sql = sqlsrv_query("select * from carro");
sqlsrv_query($conn, $sql);
while ($row = sqlsrv_fetch_array($sql)) {
echo "<option value=\"teste1\">" . $row['placa'] . "</option>";
}
sqlsrv_close($conn);
?>
</select>
But don't appear any information in my list.
Someone can help me to figure whats wrong in my code?
You are not making the query to the database correctly. This is then causing a PHP error and hence not executing the while loop. The line should be:
$sql = sqlsrv_query($conn, "select * from carro");
or
$query = "select * from carro";
$sql = sqlsrv_query($conn, $query);
You might also want to specify that you are wanting the associative array from the query response, as you are looking for $row['placa']. Like so:
while ($row = sqlsrv_fetch_array($sql, SQLSRV_FETCH_ASSOC)){...}

php msql sort values by name

I'm struggling a bit with the new mysql/php code, I have a sniplet which picks out all my books, but I would like to sort it by the author. (row[1])
$db=new mysqli("$dbhost","$dbuser","$dbpass");
$db->select_db("$dbname");
$query="select * from book";
$result=$db->query($query);
//find number of rows
$num_rows=$result->num_rows;
for($i=0;$i<$num_rows;$i++)
{
//fetch row
$row=$result->fetch_row();
$total=$total+$row[2];
echo "<tr>";
echo "<td><a href='http://isbndb.com/search/all?query=".$row[8]."'>$row[4]</td>" ;
echo "<td>$row[1]</td>" ;
echo "<td>$row[10]</td>" ;
echo "<td>$row[9]</td>" ;
$stoke=$row[2]-$row[3];
$tstoke=$tstoke+$stoke;
$tout=$total-$tstoke;
echo "<td width=\"30\">$stoke</td>" ;
echo "</tr>";
}
how does one do this?
you can use this in your query after your select
$query="select * from book ORDER BY author";
//or
$query="select * from book ORDER BY author DESC";
Avoid using * try mentioning the field names (i.e.)
$query="select id,books,author,etc from book ORDER BY author";
further reference here
$query="select * from tablename order by coloumnname ASC or DESC";
where you can choose your condition ASC or DESc

Categories