i would really appreciate if anyone can help me out with this mysql php problem of which i have no idea how to do it.
I Have a column named = 'x'
The text of that column 'x' is = "yz,zz,zy"
I want to edit the value of the column 'x' to = "yz,zyz,zy".
Now how do i add that 'y' in the middle term between yz and zy using CONCAT.
Regards.
You haven't provided any code or an attempt for us to go off of something so I'll give you a brief way of doing it. Look up PDO here This is a really easy to follow and secure way to manipulate data in your database using php. Again as you haven't given me much to go off i'm unsure if you want to just set something at specific count of characters along OR if you want to just update the entire thing, SO i'll help you with the latter as it will help give you some base understanding.
Please read into PDO further as this is just an example further down the line and will not run if you just blindly copy and paste it in.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE table SET x='yz,zyz,zy' WHERE id= 1"; // No clue if you've even given anything IDs
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
As you haven't really provided any Schema of the table you are updating this is the best I could provide based off of what you have given me.. try to include as much information as possible as I'm unsure if this is what you even want
Related
MySQL is not using the variables as it should. it is not taking any value from them it is incrementing the auto-increment numbers in the MYSQL table, however the row is not saved. I am not given any errors.
I have tried like this:
$sql = "INSERT INTO `tbl_bike` (`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`, `BikeWheel`, `BikeColour`, `BikeSpeed`, `BrakeType`, `FrameGender`, `AgeGroup`, `DistFeatures`)
VALUES (“.$userID.”, “.$PartNo.”, “.$BikeManufacturer.”, “.$BikeModel.”, “.$BikeType.”, “.$BikeWheel.”, “.$BikeColour.”, “.$BikeSpeed.”, “.$BrakeType.”, “.$FrameGender.”, “.$AgeGroup.”, “.$DistFeatures.”)";
I have also tried replacing the " with ', Removing the . and even completely removing the ". Nothing has helped with this issue. When I use this query but remove the variables and instead put string, int etc in the correct places the query will function perfectly and put the results into the table. My variables are normally as follows:
$PartNo = $_POST['ManuPartNo’];
$BikeManufacturer = $_POST['BikeManufacturer’];
$BikeModel = $_POST['BikeModel’];
$BikeType = $_POST['BikeType’];
$BikeWheel = $_POST['BikeWheel’];
$BikeColour = $_POST['BikeColour’];
$BikeSpeed = $_POST['BikeSpeed’];
$BrakeType = $_POST['BrakeType’];
$FrameGender = $_POST['FrameGender’];
$AgeGroup = $_POST['AgeGroup’];
$DistFeatures = $_POST['DistFeatures’];
These variables normally take input from a separate PHP/HTML file with the '$_POST['DistFeatures’];'
I have tried removing the $_POST['DistFeatures’]; from the ends of each of them and just replacing the values with normal string or int values but still nothing helps. I am completely stuck and would appreciate any help with this.
This is all running on a plesk server.
Please stop using deprecated MySQL. I will suggest an answer using PDO. You can use this to frame your other queries using PDO.
// Establish a connection in db.php (or your connection file)
$dbname = "dbname"; // your database name
$username = "root"; // your database username
$password = ""; // your database password or leave blank if none
$dbhost = "localhost";
$dbport = "10832";
$dsn = "mysql:dbname=$dbname;host=$dbhost";
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
// Include db.php on every page where queries are executed and perform queries the following way
// Take Inputs this way (your method is obsolete and will return "Undefined Index" error)
$userId = (!empty($_SESSION['sessionname']))?$_SESSION['sessionname']:null; // If session is empty it will be set to Null else the session value will be set
$PartNo = (!empty($_POST['ManuPartNo']))?$_POST['ManuPartNo']:null; // If post value is empty it will be set to Null else the posted value will be set
$BikeManufacturer = (!empty($_POST['BikeManufacturer']))?$_POST['BikeManufacturer']:null;
$BikeModel = (!empty($_POST['BikeModel']))?$_POST['BikeModel']:null;
$BikeType = (!empty($_POST['BikeType']))?$_POST['BikeType']:null;
$BikeWheel = (!empty($_POST['BikeWheel']))?$_POST['BikeWheel']:null;
// Query like this
$stmt = $pdo->prepare("INSERT INTO(`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`)VALUES(:uid, :manuptno, :bkman, :bkmodel, :bktype)");
$stmt-> bindValue(':uid', $userId);
$stmt-> bindValue(':manuptno', $PartNo);
$stmt-> bindValue(':bkman', $BikeManufacturer);
$stmt-> bindValue(':bkmodel', $BikeModel);
$stmt-> bindValue(':bktype', $BikeType);
$stmt-> execute();
if($stmt){
echo "Row inserted";
}else{
echo "Error!";
}
See, it's that simple. Use PDO from now on. It's more secured. To try this, just copy the whole code in a blank PHP file and and run it. Your database will receive an entry. Make sure to change your database values here.
You should try this
$sql = "INSERT INTO tbl_bike (userID, ManuPartNo, BikeManufacturer, BikeModel, BikeType, BikeWheel, BikeColour, BikeSpeed, BrakeType, FrameGender, AgeGroup, DistFeatures) VALUES ('$userID', '$PartNo', '$BikeManufacturer', '$BikeModel', '$BikeType', '$BikeWheel', '$BikeColour', '$BikeSpeed', '$BrakeType', '$FrameGender', '$AgeGroup', '$DistFeatures')";
If this doesn't work, enable the null property in sql values. So you can find out where the error originated.
Here's my code:
<?php
//recently added
$result = mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
if ($result == 1){
?>
<script>
jQuery(document).ready(function(){
jQuery(".eltdf-psc-slide").addClass("no-background");
});
</script>
<?php
}
//=============
?>
Basically what I'm trying to do is checking and see if the value stored in the $shadowless_background_table "DB" is == 1 and I only want that column (background). I have browse the web, but what I see are examples with while loops which I was wondering if I could do something like this instead.
If you want to fetch a single record based on a condition you can do this -
$result = mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
if (mysql_num_rows($result)>0){
$fetchedColum = mysql_result($result, 0, 'COLUMN_NAME');
}
There are couple of issues with your code.The first thing that i have noticed is that you are using mysql API instead of PDO.I don't blame you since the internet is full of old tutorials and you probably didn't have a chance to get some guidance.
MySql is getting old It doesn't support modern SQL database concepts such as prepared statements, stored procs, transactions etc... and it's method for escaping parameters with mysql_real_escape_string and concatenating into SQL strings is error prone and old fashioned.
Organize your project better.
As i have seen from this example you probably have a poor project organization.You should consider reading about PSR Standards
And to go back to your question ,and to update it a bit.
Instead of doing
mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
I would do it this way:
<?php
$host = "localhost";
$username = "user name of db";
$password = "password of db";
$dbname = "database name ";
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//your data
$id = 1; // id
$stmt = $conn->prepare("SELECT background FROM database_name WHERE id=:id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$data = $stmt->fetchAll();
foreach ($data as $row) {
echo $row["row_name"];
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
Go read more about PHP in general ,it will help you out a lot.The biggest problem is that there are so much wrong tutorials and references or they are just old.And people learn from wrong sources.
I had the same problem ,but thanks to right people on this site i have managed to learn more.
My suggestion is that you read about PSR,PDO and PHP in general!!!
Also a thing you should consider reading about is security in php.
Good luck mate :D
I have a database named hrRecords and a table named employee in that table. It has a field named contract_end. In that field, I have the contract info of the employee specifically the duration of said contract (datetime).
What I want to achieve is to check that info to see when the contract is going to come to an end and if it is display a message saying so.
I am very new to php and I tried something but I am totally lost I was wondering if I could get some guidance of some sort thank you for your support:
<?php
$employee1= mysql_real_escape($_GET["employee1"]);
$DataBase = "hrRecords";
mysql_connect("server","username", "password") or die(mysql_error());
mysql_select_db($DataBase) or die(mysql_error());
$query = SELECT contract_end From hrRecords
// current date being compared
if(contract_end== date(Y-m-d) {
echo "something"
}
else {
echo " employe name , Your contract will expire in x amount of days "
}
/* This is the point where everything becomes fuzzy because im thinking there has to be some other way to do this for all the employees */
fist stop using mysql it has been depreciated
use either mysqli or pdo. I will show you how to do it with mysqli
<?php
$employee1= mysql_real_escape($_GET["employee1"]); // i am not sure why you are doing this since you are not using this any where
$DataBase = "hrRecords";
$ServerName = "server";
$UserName = "username";
$Password = "password";
$mysqli = new mysqli($ServerName, $UserName, $Password,$DataBase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// since i don't know all of colum names i am making them up
$stmt= $mysqli->prepare("SELECT contract_end employe_name From hrRecords");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($contract_end, $employe_name)
while($stmt->fetch()) { // this will go thorough all of the records
// current date being compared
if($contract_end== date(Y-m-d) {
echo "something"
} else {
// you need some more code here to find x
echo " $employe name , Your contract will expire in x amount of days "
}
}
i don't know if this will help you at all. you did not have enough info for a better answer
Hy everyone, I can't wrap my head around this. I'm trying to get some data from a table using PDO. this is my code:
//in db.php I have the connection:
$host = 'localhost';
$db = 'APL';
$dbuser = '';
$pass = ' ';
try{
$conn = new PDO("mysql:host=$host;dbname=$db", $dbuser, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
//in my file I have this:
$id = $_GET['id'];
$sel_sql = "SELECT * FROM users WHERE id =:id";
$stmt = $conn ->prepare($sel_sql);
$stmt -> bindParam(':id', $id);
$stmt -> execute();
$result = $stmt -> fetchAll(PDO::FETCH_ASSOC);
The problem is that print_r($result) returns '1' (just the value 1, therefore I can't access any data stored in the table) as long as $_SESSION['user'] is set.
The whole data-retrieving worked just fine if the $_SESSION['user'] is not set.
Can someone please explain why this is happening? (I'm fairly new to all this and I'm really trying to understand why some issues occur).
Thank you!
The fetchAll function should be returning either an array, or a boolean FALSE.
You report that print_r($result) is displaying an integer value of 1.
I don't see how that's possible, unless you are assigning a different value to $result. Try relocating print_r($result) to immediately follow the assignment from fetchAll.
(My suspicion is that $result is being assigned a value of 1 elsewhere in your code, before you do the print_r. If there were "Issues with php connection to MySQL database", we'd be expecting to see a PDO error of some sort.)
NOTE: I don't think PDO::FETCH_ASSOC is a defined fetch style for the fetchAll function. (fetchAll has different fetch styles than fetch.)
Just in case someone else stumbles upon this, between the $result variable and the print_r($result) I had an include_once(); statement (which was wrongly put there in the first place).
Thank you everyone for your answers.
I want to update MySQL database by below code, but it doesn't work why?
<?php
mysql_connect("localhost","root","");
mysql_select_db("timer");
$update=$_COOKIE['name'];
mysql_query("UPDATE user SET password='2' WHERE username=$update");
?>
String values should be quoted: MySQL String Literals.
mysql_query("UPDATE user SET password='2' WHERE username='$update'");
$dsn = 'mysql:dbname=timer;host=127.0.0.1';
$user = 'root';
$password = '';
$update=$_COOKIE['name'];
$query = 'UPDATE user SET password='2' WHERE username=(?)';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->prepare( $query )->execute( array($query) );
} catch (PDOException $e) {
echo 'Connection failed ' . $e->getMessage();
}
Can't be sure if it works because I don't know what you have in your $_COOKIE array.
But the code should look like this.
For security, you can add some text transformation to the variable $update like addslashes or other ones.
Use prepared queries, the way you do it isn't a good practice. Check also if $update isn't empty, otherwise the query will not work, Finally, use mysqli_* functions instead of mysql_* :)
<?php
mysql_connect("localhost","root","");
mysql_select_db("timer");
$update=$_COOKIE['name'];
mysql_query("UPDATE ´user´ SET password='2' WHERE username='$update'");
?>
Try to mention the name of your table in this query like this: ´user´
Let me recommend you that if your query doesn't work then you could put the whole query in an echo (or print) to see whats wrong.
For example:
echo "mysql_query(\"UPDATE user SET password='2' WHERE username=$update\";