I'm working on my first PHP/MySQL project, and I've gotten basic logins and INSERT queries working, but not updates. This is my first update, which is just one row with a state and zipcode. Is anything wrong?
$dbc = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$state=$_POST['state'];
$zip=$_POST['zip'];
$custnum = 0;
$sql="UPDATE $tbl_name SET state = '$state', zip = '$zip', WHERE custnum = '$custnum'";
$result = mysqli_query($dbc, $sql)
or die('Error querying database.');
$sql="UPDATE {$tbl_name} SET state='{$state}', zip='{$zip}' WHERE custnum='{$custnum}'";
Remove the last comma before "WHERE" clause. Also, if you're just starting out it's good to put parenthesis around variables names when using double-quotes for strings. Helps you to distinguish the variables better.
Pekka is also correct in his comments, you are mixing mysql and mysqli functions. Use mysql_query() instead.
I think you need to get rid of the comma just before the WHERE.
$suitno =mysqli_real_escape_string($ecms,$_POST['suitno']);//protecting sql injection
$defendant=mysqli_real_escape_string($ecms,$_POST['defendant']);//protecting sql injection
$casenature=mysqli_real_escape_string($ecms,$_POST['casenature']);//protecting sql injection
$sql="UPDATE causelist SET suitno='{$suitno}',
casenature='{$casenature}' WHERE suitno='{$suitno}'";
$result = mysqli_query($ecms, $sql)
or die('Error querying database.');
$dbc = mysql_connect($host, $username, $password)or die("cannot connect"); //don't need quotes
mysql_select_db($db_name,$dbc)or die("cannot select DB"); //added the $dbc (connection link) as a second parameter
$state=mysql_real_escape_string($_POST['state']); //Should make it safe!
$zip=mysql_real_escape_string($_POST['zip']); //Should make it safe!
$custnum = 0;
$sql="UPDATE $tbl_name SET state = '$state', zip = '$zip' WHERE custnum = '$custnum'";
//removed an extra comma
//Notice that $tbl_name isn't defined!
u
$result = mysql_query($sql)
or die('Error querying database.'); //from mysqli to mysql
Looks like a sql syntax error:Remove the comma before WHERE
if(isset($_POST['update']))
{
$name=$_POST['name'];
//echo $name; die;
$surname=$_POST['surname'];
$upd="update table_name SET name='$name',surname='$surname' where id=$id";
mysql_query($upd);
}
Related
I'm trying to make it possible to add something to my guestbook through the website. But the problem is: I fail to insert into the database.
Using my WAMP server I can insert into it directly using the query down here.
I've tested the $name variables as well and they are properly filled in. I've switched $con and $sql. and I tried to format the query in different ways without{} with {}. But not even one option seems to work. The connection with my DBS works (I didn't include that part here). I tried mysql_query and mysqlI_query.
My WAMP server has php_mysqli enabled. And when I run this it doesn't give any errors.
Do you guys know what I'm doing wrong?
$con = mysqli_connect($host, $username, $password)or die("cannot connect");
mysqli_select_db($con, $db_name)or die("cannot select DB");
$datetime=date("y-m-d h:i:s"); //date time
$name= $_POST['name'];
$email= $_POST['email'];
$comment= $_POST['comment'];
$sql="INSERT INTO guestbook(name, email, comment, datetime) VALUES('{$name}','${email}','{$comment}','{$datetime}')";
mysql_query($sql,$con);
// link to view guestbook page
header('location:viewguestbook.php');
Please try this,And next time you must search mysqli prepared statements.
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->query("insert...");
here is the problem in this statement
mysql_query($sql,$con);
problem 1: you are using mysqli and in above statement your are querying mysql.
problem 2: $con(connection variable is must be the first parameter)
Write this statement as folloing. that will solve the problem
mysqli_query($con,$sql);
In your insert query you have ${email} instead of {$email} and change mysql_query to mysqli_query
below is the code that should work
$con = mysqli_connect($host, $username, $password)or die("cannot connect");
mysqli_select_db($con, $db_name)or die("cannot select DB");
$datetime=date("y-m-d h:i:s"); //date time
$name= $_POST['name'];
$email= $_POST['email'];
$comment= $_POST['comment'];
$sql="INSERT INTO guestbook(name, email, comment, datetime) VALUES('{$name}','{$email}','{$comment}','{$datetime}')";
mysqli_query($sql,$con);
I don't know what error do you get. You can do this:
mysqli_query($con, $query) or die(mysqli_error($con));
I am working on a site to share names of songs, and I have made a recommendation form that I include in every page. This recommendation form is in HTML and leads to a PHP action page, where the information received is added to a SQL table. Here is the code:
<?php
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="MYPASSWORD"; // Mysql password
$db_name="DB NAME"; // Database name
$tbl_name="songshare"; // Table name
// Connect to server and select databse.
$link = mysqli_connect("$host", "$username", "$password")or die("cannot connect");
mysqli_select_db($link, "$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$song=$_POST['song'];
$album=$_POST['album'];
$artist=$_POST['artist'];
$linkitunes=$_POST['linkitunes'];
$artwork=$_POST['albumPic'];
// To protect MySQL injection (more detail about MySQL injection)
$song = stripslashes($song);
$album = stripslashes($album);
$artist = stripslashes($artist);
$song = mysqli_real_escape_string($link, $song);
$album = mysqli_real_escape_string($link, $album);
$artist = mysqli_real_escape_string($link, $artist);
$sql="SELECT * FROM $tbl_name WHERE song='$song'";
$result=mysqli_query($link, $sql);
if ($result->num_rows){
echo "Song already taken" . "<br />";
echo "<a href='/music.php'>music</a>";
exit();
}
$sql="INSERT INTO recommendation (user_id, artist, song, album, artwork, linkitunes)";
$sql = $sql . " VALUES ('$_SESSION['user_id']', '$artist', '$song', '$album'. '$artwork'. '$linkitunes');";
$result=mysqli_query($link, $sql);
if(!$result) {
echo "Recommendation failed" . "<br />";
echo $sql;
} else {
print "$song, $artist, $album";
}
ob_end_flush();
?>
I have checked that every username, password, link is correct and valid. My server does, in fact, run PHP. It doesn't seem to me like the PHP code is even running though.
Thank you so much in advance.
-Cameron
Turn on error reporting by adding this on top of page:
ini_set("display_errors",true);
and change this line:
$link = mysqli_connect("$host", "$username", "$password")
to
$link = mysqli_connect($host, $username, $password,$db_name);
Please have a look how to work with mysqli
Instead of '$album'. '$artwork'. '$linkitunes' Do: '$album', '$artwork', '$linkitunes', while saving data.
Try this :-
$sql = $sql . " VALUES ('".$_SESSION['user_id']."', '$artist', '$song', '$album', '$artwork', '$linkitunes')";
instead of
$sql = $sql . " VALUES ('$_SESSION['user_id']', '$artist', '$song', '$album'. '$artwork'. '$linkitunes');";
You should check the version of local server you are working with. If you are working with a higher of local server and you php was written in a lower version it throws a blank page.
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="hsp_property"; // Database name
$tbl_name="project_directory"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
//Get values from form
$id = $_POST['id'];
$hospital = $_POST['hospital'];
$project = $_POST['project'];
$state = $_POST['state'];
$status = $_POST['status'];
$da_status = $_POST['da_status'];
$pm = $_POST['pm'];
$budgett = $_POST['budgett'];
$budgetat = $_POST['budgetat'];
$pdapproval = $_POST['pdapproval'];
$pdcs = $_POST['pdcs'];
$pdcd = $_POST['pdcd'];
$pdcf = $_POST['pdcf'];
$pnm = $_POST['pnm'];
$prm = $_POST['prm'];
$comments = $_POST['comments'];
// update data in mysql database
$sql="UPDATE $tbl_name SET Hospital='$hospital', Project='$project', State='$state',Project_Status='$status',DA_Status='$da_status',Project_Manager='$pm',Budget_Total='$budgett',Budget_Approved='$budgetat',Project_Approval_Dates='$pdapproval',Project_Contstruction_Dates='$pdcs',Project_Contract_Dates='$pdcd',Project_Current_Dates='$pdcf',Program_Next_Milestone='$pnm',Program_Milestone='$prm',Comments='$comments' WHERE id='$id'";
$result=mysql_query($sql);
// if successfully updated.
if ($result) {
header ('Location: ../project_directory.php');
}
else {
echo 'Error';
}
?>
The above is some code to update a MySQL db, i'm running WAMP to test the website before I'll upload.
I've been using the phpeasysteps tutorial as php and mysql is new to me. It's been working all ok until now.
Would love to know what i'm doing wrong, the PhpEasySteps tutorial might be a tad old as i've had to update a few elements of the initial code to get it to work..
Replace echo 'Error'; with echo mysql_error(); to see why you didn't get a result and then slap yourself for misspelling a column name or something most likely easily overlooked. If you still can't figure it out, post the error. And if you go that far, post the result of SHOW CREATE TABLE project_directory
You need to add $link_identifier to your mysql_select_db database selection,
Syntax: bool mysql_select_db ( string $database_name [, resource $link_identifier = NULL ] )
$link = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name", $link)or die("cannot select DB");
You can use mysql_error(); function to find the mysql related errors.
I've got two different sites. What I'd like to do is to automatically run a script that sends some of the data inserted into the database in site 1 when a user registers and updates a table in the database for site 2 so that an account is automatically created in site 2 using the same details.
I'm at the stage of trying to create a query that will update the database. I'm the self-made type so don't know that well what I'm doing. Got this query from somewhere but can't make it work. Can anyone tell what's wrong with it? It's not executing the query.
Thanks!
Eugenie
<?php
$host = "localhost"; // Host name
$username = "----"; // Mysql username
$password = "----"; // Mysql password
$db_name1 = "------"; // Database name
$db_name2 = "-----"; // Database name
$tbl_name1 = "-----"; // Table name
$tbl_name2 = "---"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name1")or die("cannot select DB");
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name2")or die("cannot select DB");
$query = "USE $db_name2
UPDATE $db_name2.dbo.$tbl_name2
SET email=d2.email FROM $db_name1.dbo.$tbl_name1 d2
WHERE d2.uid = $tbl_name1.uid";
$result = mysql_query($query) or die ("could't execute query.");
?>
<?php
$host = "localhost"; // Host name
$username = "----"; // Mysql username
$password = "----"; // Mysql password
$db_name1 = "------"; // Database name
$db_name2 = "-----"; // Database name
$tbl_name1 = "-----"; // Table name
$tbl_name2 = "---"; // Table name
$conn = mysql_connect($host, $username, $password);
mysql_select_db($db_name1, $conn) or die("cannot select DB");
mysql_select_db($db_name2, $conn) or die("cannot select DB");;
$query1 = "SELECT * FROM `" . $db_name1.$tb1_name1 . "` ";
$query2 = "SELECT * FROM `" . $db_name2.$tb1_name2 . "` ";
You can fetch data of above query from both database as below
$result1 = mysql_query($query1);
while($row = mysql_fetch_assoc($result1)) {
$data1[] = $row;
}
$result2 = mysql_query($query2);
while($row = mysql_fetch_assoc($result2)) {
$data2[] = $row;
}
print_r($data1);
print_r($data2);
?>
Suggestion: Try shifting to mysqli or PDO since mysql is depreciated now.
Recall the documentation for mysql_connect:
Returns a MySQL link identifier on success or FALSE on failure.
... and the documentation for the second parameter for mysql_query:
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
... should solve your problem. Example:
$link1 = mysql_connect( ... ); // For db 1.
$link2 = mysql_connect( ... ); // For db 2.
$result1 = mysql_query( "some query for db 1", $link1 );
$result2 = mysql_query( "some query for db 2", $link2 );
Well,
first of all, you're not connecting to two different databases, but using two different schemas in the same database. So only a mysql_connect should be used.
Also, if you're using full qualified names to access your tables you don't need to call mysql_select_db, nor the 'use db_name' mysql command.
Your query string is wrong. After USE $db_name2 you should have a semi-colon, and the update sentence is not correct.
Code could be somthing like that:
mysql_connect(...)
$query = "update $db2.$table2, $db1.$table1
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Warning when using mysql_fetch_assoc in PHP
i am having a problem with the following codes, i am new in encountering this error
here is the code
session_start();
$uname=$_SESSION['login'];
$host="localhost";
$username="root";
$password="";
$db_name="sampledb";
$tbl_name="tblsched";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT * FROM tblteacher WHERE teacherName=$uname";
$result=mysql_query($sql);
$row = mysql_fetch_assoc($result);
$teacherid = $row['teacherID'];
it gives me a "mysql_fetch_assoc() expects parameter 1 to be resource, boolean" error, how do i deal with this error?? i have used this code already a few times in other files and it worked perfectly except now, i checked the names of the rows and it was correct
i already tried using other commands such as mysql_fetch_array, mysql_result, mysql_fetch_row and it gives the same error
You seem to be using a variable that is a string, you need to encapsulate it in quotes:
SELECT * FROM tblteacher WHERE teacherName='$uname'
On that note, I see that it is coming from a Session variable, I take it that it is already cleansed to make sure there are no possible injection attacks within it - yes?
Try
$sql = "SELECT * FROM tblteacher WHERE teacherName='$uname'";
The problem is in this line
$sql = "SELECT * FROM tblteacher WHERE teacherName=$uname";
change to
$sql = "SELECT * FROM tblteacher WHERE teacherName='$uname'";
the uname is string and it should be quoted using single or double quotes.
Try This // user index no
session_start();
$uname=$_SESSION['login'];
$host="localhost";
$username="root";
$password="";
$db_name="sampledb";
$tbl_name="tblsched";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT * FROM tblteacher WHERE teacherName=$uname";
$result=mysql_query($sql);
$row = mysql_fetch_assoc($result);
**$teacherid = $row[0];**