MySqli error using time() in query to update a table - php

MySqli problem:
i used this query to update a field in table.
mysqli_query($con, " UPDATE users SET profile_pic = '$img_name' WHERE id = '$id' ");
where
$img_name = time().$id;
and
$id = 3;
when I echo $img_name, it give correct result.
but value stored in database it gives 2147483647 ie maximum integer value for my 32bit computer.

get rid of profile_pic field in the table
when uploading image, rename it to 'profile'.$id.'.jpg'

Related

inserting into two different mysql tables using php

I have 2 mysql tables : details and detimages. Details table has a column named id which is a primary key of that table and it also auto increments. And detimages table has a column named detkey which is a foreign key which links with id column of details table.
What I'm trying to achieve: the user enters the details and also choose the images which is related to the details he entered and then the details gets inserted in the details table and the images which is related to the details gets inserted in the detimages tables with the details id as the foreign key.
I'm able to insert in those two different tables but i'm stuck on the foreign key one . I don't know how i can automatically get the primary key of the inserted details and then use it to insert into the detimages table. Thank you
Here are my codes:
include 'DatabaseConfig.php';
if (isset($_POST['uploadImageBtn'])) {
$details = mysqli_real_escape_string($db, $_POST['details']);
$detail_query= "INSERT INTO details(description) values('$details')";
$run = $db->query($detail_query) or die("Error in saving detail".$db->error);
$uploadFolder = 'upload/';
foreach ($_FILES['imageFile']['tmp_name'] as $key => $image) {
$imageTmpName = $_FILES['imageFile']['tmp_name'][$key];
$imageName = $_FILES['imageFile']['name'][$key];
$result = move_uploaded_file($imageTmpName,$uploadFolder.$imageName);
// save to database
$image_query = "INSERT INTO detimages SET file_name='$imageName' " ;
$run = $db->query($image_query) or die("Error in saving image".$db->error);
}
if ($result) {
echo '<script>alert("Images uploaded successfully !")</script>';
}
}
You can use either of these:
mysql_insert_id
PDO::lastInsertId
When you execute a sql you have something like that
$query = $pdo->prepare(sql);
$query->execute();
For every type of SQL type you use is a command like
$query->lastinsertid();
Maybe for pdo is different and for SQLite.
Search for the query -> lastinsertid();
Or say to us more information of you MySQL connection type ,
Is it pdo, mysql, mysqli..

using update statement in php

I am trying to update my database using php however my update clause is not working.
This is the code:
<?php
if (isset($_POST['submit']))
{
date_default_timezone_set('Australia/Sydney');
$date = date("Y-m-d h:i:s");
$sqlUpdate = " UPDATE booking
SET checkedin = '1', checkin_datetime = '$date'
WHERE id = '$flightID'";
$result3 = mysqli_query($dbConn, $sqlUpdate) or trigger_error("Query Failed! SQL: $sqlUpdate - Error: ".mysqli_error($dbConn), E_USER_ERROR);
}
?>
In my database the flightID is an auto increment integer and the checkin is a tiny int.
I believe that it could be treating my variable as a string and not a integer which is why it is not updating in my database.
I have tried creating a variable to to hold the value of 1 and replace it with the hard coded value in the SQL which did not change anything.
Any ideas what the problem is and how to fix it?
here is a photo for my booking table
please note in my sql the 'flightID' variable is actually referring to the id column in the booking table

php adding wrong value to mySql database

i have built an air for android app that posts content to facebook and on success sends a url query to a php file to add the post id of the content along with fb_id and the users name. the problem is it is not adding the value i am giving it it is instead adding the same number(dont know where it is coming from) to the post_id and fb_id. i know the right values are being sent by the mobile app.
php:
<?php
/*
------------variables set in flash--------------
videoVars.postId = result.id
videoVars.uid = uid //fb user id
videoVars.firstName = firstName
videoVars.lastName = lastName
*/
$postId = $_REQUEST['postId'];
$uid = $_REQUEST['uid'];
$firstName = $_REQUEST['firstName'];
$lastName = $_REQUEST['lastName'];
echo $postId.'<br/>';
echo $uid.'<br/>';
echo $firstName.'<br/>';
echo $lastName.'<br/>';
//connect to database
include('db-connect.php');
$addVideo = mysqli_query($dbc , "INSERT INTO content (content_id, post_id, fb_id, first_name, last_name ) VALUES('','".$postId."','".$uid."','".$firstName."','".$lastName."')");
?>
the value i am getting for post_id and user_id are the same even though they should be different. i manually typed the vars in to addressbar in browser and it still misbehaved in the same way. the only way i can add more than one row is to add it in the sql tab of phpMyAdmin
If your echo calls output the correct values, check your database table structure and make sure there's no UNIQUE key set for fb_id.
Then, make sure you're escaping all your content with mysqli_real_escape_string ( mysqli $link , string $escapestr ). http://ca3.php.net/manual/en/mysqli.real-escape-string.php
Is content_id an auto_increment value? If so, try passing NULL for it, without the single quotes, instead of an empty string.
To debug, you can also try echoing your query (first assign it to a variable $sql = "[QUERY HERE]";, then pass the variable to the function, then echo the $sql variable and finally call your file manually.
I guess that you have problem on content_id field. it should has auto_increment property.
In your sql, when you inserts content_id as a blank value '' it will convert to 0, next time when you insert a blank value again you will has "Duplicate entry '0' for key 'PRIMARY'" message.
to fix it just remove the primary key field in your query
i.e:
$addVideo = mysqli_query($dbc , "INSERT INTO content ( post_id, fb_id, first_name, last_name ) VALUES('".$postId."','".$uid."','".$firstName."','".$lastName."')");
Or you can insert a null value for it:
$addVideo = mysqli_query($dbc , "INSERT INTO content (content_id, post_id, fb_id, first_name, last_name ) VALUES(null,'".$postId."','".$uid."','".$firstName."','".$lastName."')");
You can try to print out your current - wrong sql error like this:
$addVideo = mysqli_query($dbc , "INSERT INTO content (content_id, post_id, fb_id, first_name, last_name ) VALUES('','".$postId."','".$uid."','".$firstName."','".$lastName."')");
if (!$addVideo) {
printf("Error: %s\n", mysqli_error($dbc));
}
The problem is the id were being stored as ints in the database and the biggest allowable int value is 2147483647 which is being put in each time and as the numeric ids are bigger numbers than 2147483647 and one of the fields is set to unique it can only add one row. i have changed the type to bigint and it is working fine now. i have also implemented some of # dAngelov suggestions.

Last insert id value store to same table another specific column

i had following table and columns
Table Name = users
column = user_id, name, email, password, status, identity
i'm using following query for insert data to table users
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['name']);
$password = mysql_real_escape_string($_POST['txtPassword']);
$password = md5($password); //===Encrypt Password
if(isset($_POST['btnRegister'])) //===When I will Set the Button to 1 or Press Button to register
{
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','0')";
$res = mysql_query($query);
header('location:success_register.php');//Redirect To Success Page
}
what i am asking is, i want store last id to column identity also
for example: if last user_id= 10, identity also will be = 10. i mean get last id then store that id to identity column
Result will be look like this
user_id name email password status identity
5 aa aaa#ab.com **** 1 5
6 bbb bbb#ac.com **** 1 6
how to do it,?
In MYSQL, you have alternative possibility to find it, when you think last_insert_id() is not working. You may require to have SELECT privilege on INFORMATION_SCHEMA and its tables.
If you have that privileges, try the following query.
$query = "insert into users( name, email, pasword, status, identity )"
. " values( '$name', '$email', '$password', '1',"
. " ( SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES"
. " WHERE TABLE_NAME='users' and TABLE_SCHEMA=DATABASE() )"
. " )";
And, lastly, suggesting to stop using deprecated API.
Save last insert id like this:
$id = mysql_insert_id();
and use it in next insert
You are looking for:
mysql_insert_id()
mysqli_insert_id(mysqli $link)//for mysqli
PDO::lastInsertId()//for PDO
Other Approach:
if your id column is auto increment and not random then you can select the max id(everytime just after your insert query) from the users table and insert it into whatever column you want.
$id=mysql_result(mysql_query(select max(user_id)
from users),0);
Dont use mysql_ as they are depracated.*
here is what you are looking for. Select max(user_id)+1 and store it in a variable.
Now you need to pass this variable in user_id and identity parameter.
Note that even though user_id is auto increment, it will allow you to insert the new row with specified user_id
i think you can also put it like this
$lastID = MySQLI_insert_id($DBcon); //where Dbcon is your connection to your database
and then
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','$lastID')";
$res = mysql_query($query);
I think you need to insert number of rows in the table after the insert:
It may useful to you
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','0',(select COUNT(*)+1 FROM users))";

how to get insert_id in a variable before insert query

I like to create a specific filename for a file that will be created by the input of the fields from the insert query. i like to have an unique key for that. this key consists of an user_id, a timestamp and at the end of this, it should be placed the generated insert_id from the insert query fired. it should be placed the auto_increment no. for the end of my generated variable. so the problem is, that i create a variable before the insert query fired so that this variable will be part of the insert query like:
$get_num = $db->query("SELECT COUNT (*) FROM tableA");
$num = $query->fetch_assoc();
$end = $num + 1;
$file_id = $id .".". time() .".". $end;
$insert = $db->query("INSERT INTO tableA ( file_id, a, b, c) VALUES('".$file_id."','".$a."','".$b."','".c."')");
Actually, forget what I wrote previously. You cannot count on COUNT working for you because what happens when a row is deleted? You will have duplicate values. The best bet for you is to first create the row, grab the insert_id, then UPDATE the file_id uing the function you previously described.
$uid = uniqid();
$insert = $db->query("INSERT INTO tableA ( file_id, a, b, c) VALUES('".$uid."','".$a."','".$b."','".c."')");
$file_id = $id .".". time() .".". mysql_insert_id();
$db->query("UPDATE tableA SET file_id='{$file_id}' WHERE file_id='{$uid}' LIMIT 1;");
In the end, you still have to use two queries anyway, so its not like this takes any more resources. Plus you aren't doing a COUNT operation anymore.
In other news, please be sure to read up on SQLi, depending on where your a,b,c variable are coming from.
This is a bad idea. Do your insert and then use LAST_INSERT_ID. Otherwise, as #AuthmanApatira noted, you could have the wrong id. The PHP for this is mysql_insert_id().
Also note that if your index column is auto_increment, you don't even need to worry about the id; the db takes care of it for you. You can just get it after your query runs.

Categories